blob: 8091d685f73ed94361d18203bc659fdbee9aa450 [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"
29#include "clang/AST/TypeLoc.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000030#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000031#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000032#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000033#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000034#include "llvm/ADT/StringExtras.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000035#include "llvm/Support/Capacity.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000036#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000037#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +000038#include <map>
Anders Carlsson29445a02009-07-18 21:19:52 +000039
Reid Spencer5f016e22007-07-11 17:01:13 +000040using namespace clang;
41
Douglas Gregor18274032010-07-03 00:47:00 +000042unsigned ASTContext::NumImplicitDefaultConstructors;
43unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000044unsigned ASTContext::NumImplicitCopyConstructors;
45unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000046unsigned ASTContext::NumImplicitMoveConstructors;
47unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000048unsigned ASTContext::NumImplicitCopyAssignmentOperators;
49unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000050unsigned ASTContext::NumImplicitMoveAssignmentOperators;
51unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000052unsigned ASTContext::NumImplicitDestructors;
53unsigned ASTContext::NumImplicitDestructorsDeclared;
54
Reid Spencer5f016e22007-07-11 17:01:13 +000055enum FloatingRank {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +000056 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Reid Spencer5f016e22007-07-11 17:01:13 +000057};
58
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000059RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +000060 if (!CommentsLoaded && ExternalSource) {
61 ExternalSource->ReadComments();
62 CommentsLoaded = true;
63 }
64
65 assert(D);
66
Dmitri Gribenkoc3fee352012-06-28 16:19:39 +000067 // User can not attach documentation to implicit declarations.
68 if (D->isImplicit())
69 return NULL;
70
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +000071 // User can not attach documentation to implicit instantiations.
72 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
73 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
74 return NULL;
75 }
76
Dmitri Gribenkodce750b2012-08-20 22:36:31 +000077 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
78 if (VD->isStaticDataMember() &&
79 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
80 return NULL;
81 }
82
83 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
84 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
85 return NULL;
86 }
87
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +000088 if (const ClassTemplateSpecializationDecl *CTSD =
89 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
90 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
91 if (TSK == TSK_ImplicitInstantiation ||
92 TSK == TSK_Undeclared)
93 return NULL;
94 }
95
Dmitri Gribenkodce750b2012-08-20 22:36:31 +000096 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
97 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
98 return NULL;
99 }
100
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000101 // TODO: handle comments for function parameters properly.
102 if (isa<ParmVarDecl>(D))
103 return NULL;
104
Dmitri Gribenko96b09862012-07-31 22:37:06 +0000105 // TODO: we could look up template parameter documentation in the template
106 // documentation.
107 if (isa<TemplateTypeParmDecl>(D) ||
108 isa<NonTypeTemplateParmDecl>(D) ||
109 isa<TemplateTemplateParmDecl>(D))
110 return NULL;
111
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000112 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000113
114 // If there are no comments anywhere, we won't find anything.
115 if (RawComments.empty())
116 return NULL;
117
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000118 // Find declaration location.
119 // For Objective-C declarations we generally don't expect to have multiple
120 // declarators, thus use declaration starting location as the "declaration
121 // location".
122 // For all other declarations multiple declarators are used quite frequently,
123 // so we use the location of the identifier as the "declaration location".
124 SourceLocation DeclLoc;
125 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko96b09862012-07-31 22:37:06 +0000126 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +0000127 isa<RedeclarableTemplateDecl>(D) ||
128 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000129 DeclLoc = D->getLocStart();
130 else
131 DeclLoc = D->getLocation();
132
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000133 // If the declaration doesn't map directly to a location in a file, we
134 // can't find the comment.
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000135 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
136 return NULL;
137
138 // Find the comment that occurs just after this declaration.
Dmitri Gribenkoa444f182012-07-17 22:01:09 +0000139 ArrayRef<RawComment *>::iterator Comment;
140 {
141 // When searching for comments during parsing, the comment we are looking
142 // for is usually among the last two comments we parsed -- check them
143 // first.
144 RawComment CommentAtDeclLoc(SourceMgr, SourceRange(DeclLoc));
145 BeforeThanCompare<RawComment> Compare(SourceMgr);
146 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
147 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
148 if (!Found && RawComments.size() >= 2) {
149 MaybeBeforeDecl--;
150 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
151 }
152
153 if (Found) {
154 Comment = MaybeBeforeDecl + 1;
155 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
156 &CommentAtDeclLoc, Compare));
157 } else {
158 // Slow path.
159 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
160 &CommentAtDeclLoc, Compare);
161 }
162 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000163
164 // Decompose the location for the declaration and find the beginning of the
165 // file buffer.
166 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
167
168 // First check whether we have a trailing comment.
169 if (Comment != RawComments.end() &&
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000170 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Dmitri Gribenko9c006762012-07-06 23:27:33 +0000171 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000172 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000173 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000174 // Check that Doxygen trailing comment comes after the declaration, starts
175 // on the same line and in the same file as the declaration.
176 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
177 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
178 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
179 CommentBeginDecomp.second)) {
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000180 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000181 }
182 }
183
184 // The comment just after the declaration was not a trailing comment.
185 // Let's look at the previous comment.
186 if (Comment == RawComments.begin())
187 return NULL;
188 --Comment;
189
190 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000191 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000192 return NULL;
193
194 // Decompose the end of the comment.
195 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000196 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000197
198 // If the comment and the declaration aren't in the same file, then they
199 // aren't related.
200 if (DeclLocDecomp.first != CommentEndDecomp.first)
201 return NULL;
202
203 // Get the corresponding buffer.
204 bool Invalid = false;
205 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
206 &Invalid).data();
207 if (Invalid)
208 return NULL;
209
210 // Extract text between the comment and declaration.
211 StringRef Text(Buffer + CommentEndDecomp.second,
212 DeclLocDecomp.second - CommentEndDecomp.second);
213
Dmitri Gribenko8bdb58a2012-06-27 23:43:37 +0000214 // There should be no other declarations or preprocessor directives between
215 // comment and declaration.
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000216 if (Text.find_first_of(",;{}#@") != StringRef::npos)
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000217 return NULL;
218
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000219 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000220}
221
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000222namespace {
223/// If we have a 'templated' declaration for a template, adjust 'D' to
224/// refer to the actual template.
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000225/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000226const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregorcd81df22012-08-13 16:37:30 +0000227 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000228 // Is this function declaration part of a function template?
Douglas Gregorcd81df22012-08-13 16:37:30 +0000229 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000230 return FTD;
231
232 // Nothing to do if function is not an implicit instantiation.
233 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
234 return D;
235
236 // Function is an implicit instantiation of a function template?
237 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
238 return FTD;
239
240 // Function is instantiated from a member definition of a class template?
241 if (const FunctionDecl *MemberDecl =
242 FD->getInstantiatedFromMemberFunction())
243 return MemberDecl;
244
245 return D;
Douglas Gregorcd81df22012-08-13 16:37:30 +0000246 }
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000247 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
248 // Static data member is instantiated from a member definition of a class
249 // template?
250 if (VD->isStaticDataMember())
251 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
252 return MemberDecl;
253
254 return D;
255 }
256 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
257 // Is this class declaration part of a class template?
258 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
259 return CTD;
260
261 // Class is an implicit instantiation of a class template or partial
262 // specialization?
263 if (const ClassTemplateSpecializationDecl *CTSD =
264 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
265 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
266 return D;
267 llvm::PointerUnion<ClassTemplateDecl *,
268 ClassTemplatePartialSpecializationDecl *>
269 PU = CTSD->getSpecializedTemplateOrPartial();
270 return PU.is<ClassTemplateDecl*>() ?
271 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
272 static_cast<const Decl*>(
273 PU.get<ClassTemplatePartialSpecializationDecl *>());
274 }
275
276 // Class is instantiated from a member definition of a class template?
277 if (const MemberSpecializationInfo *Info =
278 CRD->getMemberSpecializationInfo())
279 return Info->getInstantiatedFrom();
280
281 return D;
282 }
283 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
284 // Enum is instantiated from a member definition of a class template?
285 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
286 return MemberDecl;
287
288 return D;
289 }
290 // FIXME: Adjust alias templates?
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000291 return D;
292}
293} // unnamed namespace
294
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000295const RawComment *ASTContext::getRawCommentForAnyRedecl(
296 const Decl *D,
297 const Decl **OriginalDecl) const {
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000298 D = adjustDeclToTemplate(D);
Douglas Gregorcd81df22012-08-13 16:37:30 +0000299
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000300 // Check whether we have cached a comment for this declaration already.
301 {
302 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
303 RedeclComments.find(D);
304 if (Pos != RedeclComments.end()) {
305 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000306 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
307 if (OriginalDecl)
308 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000309 return Raw.getRaw();
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000310 }
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000311 }
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000312 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000313
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000314 // Search for comments attached to declarations in the redeclaration chain.
315 const RawComment *RC = NULL;
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000316 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000317 for (Decl::redecl_iterator I = D->redecls_begin(),
318 E = D->redecls_end();
319 I != E; ++I) {
320 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
321 RedeclComments.find(*I);
322 if (Pos != RedeclComments.end()) {
323 const RawCommentAndCacheFlags &Raw = Pos->second;
324 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
325 RC = Raw.getRaw();
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000326 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000327 break;
328 }
329 } else {
330 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000331 OriginalDeclForRC = *I;
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000332 RawCommentAndCacheFlags Raw;
333 if (RC) {
334 Raw.setRaw(RC);
335 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
336 } else
337 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000338 Raw.setOriginalDecl(*I);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000339 RedeclComments[*I] = Raw;
340 if (RC)
341 break;
342 }
343 }
344
Dmitri Gribenko8376f592012-06-28 16:25:36 +0000345 // If we found a comment, it should be a documentation comment.
346 assert(!RC || RC->isDocumentation());
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000347
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000348 if (OriginalDecl)
349 *OriginalDecl = OriginalDeclForRC;
350
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000351 // Update cache for every declaration in the redeclaration chain.
352 RawCommentAndCacheFlags Raw;
353 Raw.setRaw(RC);
354 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000355 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000356
357 for (Decl::redecl_iterator I = D->redecls_begin(),
358 E = D->redecls_end();
359 I != E; ++I) {
360 RawCommentAndCacheFlags &R = RedeclComments[*I];
361 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
362 R = Raw;
363 }
364
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000365 return RC;
366}
367
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000368static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
369 SmallVectorImpl<const NamedDecl *> &Redeclared) {
370 const DeclContext *DC = ObjCMethod->getDeclContext();
371 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
372 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
373 if (!ID)
374 return;
375 // Add redeclared method here.
Douglas Gregord3297242013-01-16 23:00:23 +0000376 for (ObjCInterfaceDecl::known_extensions_iterator
377 Ext = ID->known_extensions_begin(),
378 ExtEnd = ID->known_extensions_end();
379 Ext != ExtEnd; ++Ext) {
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000380 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregord3297242013-01-16 23:00:23 +0000381 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000382 ObjCMethod->isInstanceMethod()))
383 Redeclared.push_back(RedeclaredMethod);
384 }
385 }
386}
387
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000388comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
389 const Decl *D) const {
390 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
391 ThisDeclInfo->CommentDecl = D;
392 ThisDeclInfo->IsFilled = false;
393 ThisDeclInfo->fill();
394 ThisDeclInfo->CommentDecl = FC->getDecl();
395 comments::FullComment *CFC =
396 new (*this) comments::FullComment(FC->getBlocks(),
397 ThisDeclInfo);
398 return CFC;
399
400}
401
Dmitri Gribenko19523542012-09-29 11:40:46 +0000402comments::FullComment *ASTContext::getCommentForDecl(
403 const Decl *D,
404 const Preprocessor *PP) const {
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000405 D = adjustDeclToTemplate(D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000406
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000407 const Decl *Canonical = D->getCanonicalDecl();
408 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
409 ParsedComments.find(Canonical);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000410
411 if (Pos != ParsedComments.end()) {
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000412 if (Canonical != D) {
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000413 comments::FullComment *FC = Pos->second;
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000414 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000415 return CFC;
416 }
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000417 return Pos->second;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000418 }
419
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000420 const Decl *OriginalDecl;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000421
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000422 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000423 if (!RC) {
424 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko1e905da2012-11-03 14:24:57 +0000425 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanianc328d9c2013-01-12 00:28:34 +0000426 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000427 if (OMD && OMD->isPropertyAccessor())
428 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
429 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
430 return cloneFullComment(FC, D);
Fariborz Jahanianc328d9c2013-01-12 00:28:34 +0000431 if (OMD)
Dmitri Gribenko1e905da2012-11-03 14:24:57 +0000432 addRedeclaredMethods(OMD, Overridden);
433 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000434 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
435 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
436 return cloneFullComment(FC, D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000437 }
Fariborz Jahanian41170b52013-01-25 22:48:32 +0000438 else if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +0000439 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000440 // does not have one of its own.
Fariborz Jahanian41170b52013-01-25 22:48:32 +0000441 QualType QT = TD->getUnderlyingType();
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +0000442 if (const TagType *TT = QT->getAs<TagType>())
443 if (const Decl *TD = TT->getDecl())
444 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000445 return cloneFullComment(FC, D);
Fariborz Jahanian41170b52013-01-25 22:48:32 +0000446 }
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000447 return NULL;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000448 }
449
Dmitri Gribenko4b41c652012-08-22 18:12:19 +0000450 // If the RawComment was attached to other redeclaration of this Decl, we
451 // should parse the comment in context of that other Decl. This is important
452 // because comments can contain references to parameter names which can be
453 // different across redeclarations.
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000454 if (D != OriginalDecl)
Dmitri Gribenko19523542012-09-29 11:40:46 +0000455 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000456
Dmitri Gribenko19523542012-09-29 11:40:46 +0000457 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000458 ParsedComments[Canonical] = FC;
459 return FC;
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000460}
461
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000462void
463ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
464 TemplateTemplateParmDecl *Parm) {
465 ID.AddInteger(Parm->getDepth());
466 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +0000467 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000468
469 TemplateParameterList *Params = Parm->getTemplateParameters();
470 ID.AddInteger(Params->size());
471 for (TemplateParameterList::const_iterator P = Params->begin(),
472 PEnd = Params->end();
473 P != PEnd; ++P) {
474 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
475 ID.AddInteger(0);
476 ID.AddBoolean(TTP->isParameterPack());
477 continue;
478 }
479
480 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
481 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000482 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000483 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000484 if (NTTP->isExpandedParameterPack()) {
485 ID.AddBoolean(true);
486 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000487 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
488 QualType T = NTTP->getExpansionType(I);
489 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
490 }
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000491 } else
492 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000493 continue;
494 }
495
496 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
497 ID.AddInteger(2);
498 Profile(ID, TTP);
499 }
500}
501
502TemplateTemplateParmDecl *
503ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +0000504 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000505 // Check if we already have a canonical template template parameter.
506 llvm::FoldingSetNodeID ID;
507 CanonicalTemplateTemplateParm::Profile(ID, TTP);
508 void *InsertPos = 0;
509 CanonicalTemplateTemplateParm *Canonical
510 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
511 if (Canonical)
512 return Canonical->getParam();
513
514 // Build a canonical template parameter list.
515 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000516 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000517 CanonParams.reserve(Params->size());
518 for (TemplateParameterList::const_iterator P = Params->begin(),
519 PEnd = Params->end();
520 P != PEnd; ++P) {
521 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
522 CanonParams.push_back(
523 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000524 SourceLocation(),
525 SourceLocation(),
526 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000527 TTP->getIndex(), 0, false,
528 TTP->isParameterPack()));
529 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000530 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
531 QualType T = getCanonicalType(NTTP->getType());
532 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
533 NonTypeTemplateParmDecl *Param;
534 if (NTTP->isExpandedParameterPack()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000535 SmallVector<QualType, 2> ExpandedTypes;
536 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000537 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
538 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
539 ExpandedTInfos.push_back(
540 getTrivialTypeSourceInfo(ExpandedTypes.back()));
541 }
542
543 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000544 SourceLocation(),
545 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000546 NTTP->getDepth(),
547 NTTP->getPosition(), 0,
548 T,
549 TInfo,
550 ExpandedTypes.data(),
551 ExpandedTypes.size(),
552 ExpandedTInfos.data());
553 } else {
554 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000555 SourceLocation(),
556 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000557 NTTP->getDepth(),
558 NTTP->getPosition(), 0,
559 T,
560 NTTP->isParameterPack(),
561 TInfo);
562 }
563 CanonParams.push_back(Param);
564
565 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000566 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
567 cast<TemplateTemplateParmDecl>(*P)));
568 }
569
570 TemplateTemplateParmDecl *CanonTTP
571 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
572 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000573 TTP->getPosition(),
574 TTP->isParameterPack(),
575 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000576 TemplateParameterList::Create(*this, SourceLocation(),
577 SourceLocation(),
578 CanonParams.data(),
579 CanonParams.size(),
580 SourceLocation()));
581
582 // Get the new insert position for the node we care about.
583 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
584 assert(Canonical == 0 && "Shouldn't be in the map!");
585 (void)Canonical;
586
587 // Create the canonical template template parameter entry.
588 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
589 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
590 return CanonTTP;
591}
592
Charles Davis071cc7d2010-08-16 03:33:14 +0000593CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000594 if (!LangOpts.CPlusPlus) return 0;
595
John McCallb8b2c9d2013-01-25 22:30:49 +0000596 switch (T.getCXXABI().getKind()) {
597 case TargetCXXABI::GenericARM:
598 case TargetCXXABI::iOS:
John McCallee79a4c2010-08-21 22:46:04 +0000599 return CreateARMCXXABI(*this);
John McCallb8b2c9d2013-01-25 22:30:49 +0000600 case TargetCXXABI::GenericItanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000601 return CreateItaniumCXXABI(*this);
John McCallb8b2c9d2013-01-25 22:30:49 +0000602 case TargetCXXABI::Microsoft:
Charles Davis20cf7172010-08-19 02:18:14 +0000603 return CreateMicrosoftCXXABI(*this);
604 }
David Blaikie7530c032012-01-17 06:56:22 +0000605 llvm_unreachable("Invalid CXXABI type!");
Charles Davis071cc7d2010-08-16 03:33:14 +0000606}
607
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000608static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000609 const LangOptions &LOpts) {
610 if (LOpts.FakeAddressSpaceMap) {
611 // The fake address space map must have a distinct entry for each
612 // language-specific address space.
613 static const unsigned FakeAddrSpaceMap[] = {
614 1, // opencl_global
615 2, // opencl_local
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +0000616 3, // opencl_constant
617 4, // cuda_device
618 5, // cuda_constant
619 6 // cuda_shared
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000620 };
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000621 return &FakeAddrSpaceMap;
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000622 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000623 return &T.getAddressSpaceMap();
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000624 }
625}
626
Douglas Gregor3e3cd932011-09-01 20:23:19 +0000627ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000628 const TargetInfo *t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000629 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000630 Builtin::Context &builtins,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000631 unsigned size_reserve,
632 bool DelayInitialization)
633 : FunctionProtoTypes(this_()),
634 TemplateSpecializationTypes(this_()),
635 DependentTemplateSpecializationTypes(this_()),
636 SubstTemplateTemplateParmPacks(this_()),
637 GlobalNestedNameSpecifier(0),
638 Int128Decl(0), UInt128Decl(0),
Meador Ingec5613b22012-06-16 03:34:49 +0000639 BuiltinVaListDecl(0),
Douglas Gregora6ea10e2012-01-17 18:09:05 +0000640 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanian96171302012-08-30 18:49:41 +0000641 BOOLDecl(0),
Douglas Gregore97179c2011-09-08 01:46:34 +0000642 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000643 FILEDecl(0),
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +0000644 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
645 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
646 cudaConfigureCallDecl(0),
Douglas Gregore6649772011-12-03 00:30:27 +0000647 NullTypeSourceInfo(QualType()),
648 FirstLocalImport(), LastLocalImport(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000649 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor30c42402011-09-27 22:38:19 +0000650 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000651 Idents(idents), Selectors(sels),
652 BuiltinInfo(builtins),
653 DeclarationNames(*this),
Douglas Gregor30c42402011-09-27 22:38:19 +0000654 ExternalSource(0), Listener(0),
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000655 Comments(SM), CommentsLoaded(false),
Dmitri Gribenkoe4330a32012-09-10 20:32:42 +0000656 CommentCommandTraits(BumpAlloc),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000657 LastSDM(0, 0),
Fariborz Jahanianf7992132013-01-04 18:45:40 +0000658 UniqueBlockByRefTypeID(0)
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000659{
Mike Stump1eb44332009-09-09 15:08:12 +0000660 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000661 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000662
663 if (!DelayInitialization) {
664 assert(t && "No target supplied for ASTContext initialization");
665 InitBuiltinTypes(*t);
666 }
Daniel Dunbare91593e2008-08-11 04:54:23 +0000667}
668
Reid Spencer5f016e22007-07-11 17:01:13 +0000669ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000670 // Release the DenseMaps associated with DeclContext objects.
671 // FIXME: Is this the ideal solution?
672 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000673
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000674 // Call all of the deallocation functions.
675 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
676 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000677
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000678 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000679 // because they can contain DenseMaps.
680 for (llvm::DenseMap<const ObjCContainerDecl*,
681 const ASTRecordLayout*>::iterator
682 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
683 // Increment in loop to prevent using deallocated memory.
684 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
685 R->Destroy(*this);
686
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000687 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
688 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
689 // Increment in loop to prevent using deallocated memory.
690 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
691 R->Destroy(*this);
692 }
Douglas Gregor63200642010-08-30 16:49:28 +0000693
694 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
695 AEnd = DeclAttrs.end();
696 A != AEnd; ++A)
697 A->second->~AttrVec();
698}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000699
Douglas Gregor00545312010-05-23 18:26:36 +0000700void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
701 Deallocations.push_back(std::make_pair(Callback, Data));
702}
703
Mike Stump1eb44332009-09-09 15:08:12 +0000704void
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000705ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000706 ExternalSource.reset(Source.take());
707}
708
Reid Spencer5f016e22007-07-11 17:01:13 +0000709void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000710 llvm::errs() << "\n*** AST Context Stats:\n";
711 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000712
Douglas Gregordbe833d2009-05-26 14:40:08 +0000713 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000714#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000715#define ABSTRACT_TYPE(Name, Parent)
716#include "clang/AST/TypeNodes.def"
717 0 // Extra
718 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000719
Reid Spencer5f016e22007-07-11 17:01:13 +0000720 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
721 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000722 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000723 }
724
Douglas Gregordbe833d2009-05-26 14:40:08 +0000725 unsigned Idx = 0;
726 unsigned TotalBytes = 0;
727#define TYPE(Name, Parent) \
728 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000729 llvm::errs() << " " << counts[Idx] << " " << #Name \
730 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000731 TotalBytes += counts[Idx] * sizeof(Name##Type); \
732 ++Idx;
733#define ABSTRACT_TYPE(Name, Parent)
734#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000735
Chandler Carruthcd92a652011-07-04 05:32:14 +0000736 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
737
Douglas Gregor4923aa22010-07-02 20:37:36 +0000738 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000739 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
740 << NumImplicitDefaultConstructors
741 << " implicit default constructors created\n";
742 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
743 << NumImplicitCopyConstructors
744 << " implicit copy constructors created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000745 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000746 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
747 << NumImplicitMoveConstructors
748 << " implicit move constructors created\n";
749 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
750 << NumImplicitCopyAssignmentOperators
751 << " implicit copy assignment operators created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000752 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000753 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
754 << NumImplicitMoveAssignmentOperators
755 << " implicit move assignment operators created\n";
756 llvm::errs() << NumImplicitDestructorsDeclared << "/"
757 << NumImplicitDestructors
758 << " implicit destructors created\n";
759
Douglas Gregor2cf26342009-04-09 22:27:44 +0000760 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000761 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000762 ExternalSource->PrintStats();
763 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000764
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000765 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000766}
767
Douglas Gregor772eeae2011-08-12 06:49:56 +0000768TypedefDecl *ASTContext::getInt128Decl() const {
769 if (!Int128Decl) {
770 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
771 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
772 getTranslationUnitDecl(),
773 SourceLocation(),
774 SourceLocation(),
775 &Idents.get("__int128_t"),
776 TInfo);
777 }
778
779 return Int128Decl;
780}
781
782TypedefDecl *ASTContext::getUInt128Decl() const {
783 if (!UInt128Decl) {
784 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
785 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
786 getTranslationUnitDecl(),
787 SourceLocation(),
788 SourceLocation(),
789 &Idents.get("__uint128_t"),
790 TInfo);
791 }
792
793 return UInt128Decl;
794}
Reid Spencer5f016e22007-07-11 17:01:13 +0000795
John McCalle27ec8a2009-10-23 23:03:21 +0000796void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000797 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000798 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000799 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000800}
801
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000802void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
803 assert((!this->Target || this->Target == &Target) &&
804 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000805 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000806
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000807 this->Target = &Target;
808
809 ABI.reset(createCXXABI(Target));
810 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
811
Reid Spencer5f016e22007-07-11 17:01:13 +0000812 // C99 6.2.5p19.
813 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000814
Reid Spencer5f016e22007-07-11 17:01:13 +0000815 // C99 6.2.5p2.
816 InitBuiltinType(BoolTy, BuiltinType::Bool);
817 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000818 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000819 InitBuiltinType(CharTy, BuiltinType::Char_S);
820 else
821 InitBuiltinType(CharTy, BuiltinType::Char_U);
822 // C99 6.2.5p4.
823 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
824 InitBuiltinType(ShortTy, BuiltinType::Short);
825 InitBuiltinType(IntTy, BuiltinType::Int);
826 InitBuiltinType(LongTy, BuiltinType::Long);
827 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000828
Reid Spencer5f016e22007-07-11 17:01:13 +0000829 // C99 6.2.5p6.
830 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
831 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
832 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
833 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
834 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000835
Reid Spencer5f016e22007-07-11 17:01:13 +0000836 // C99 6.2.5p10.
837 InitBuiltinType(FloatTy, BuiltinType::Float);
838 InitBuiltinType(DoubleTy, BuiltinType::Double);
839 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000840
Chris Lattner2df9ced2009-04-30 02:43:43 +0000841 // GNU extension, 128-bit integers.
842 InitBuiltinType(Int128Ty, BuiltinType::Int128);
843 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
844
Abramo Bagnarae75bb612012-09-09 10:13:32 +0000845 if (LangOpts.CPlusPlus && LangOpts.WChar) { // C++ 3.9.1p5
Eli Friedmand3d77cd2011-04-30 19:24:24 +0000846 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattner3f59c972010-12-25 23:25:43 +0000847 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
848 else // -fshort-wchar makes wchar_t be unsigned.
849 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
Abramo Bagnarae75bb612012-09-09 10:13:32 +0000850 } else // C99 (or C++ using -fno-wchar)
Chris Lattner3a250322009-02-26 23:43:47 +0000851 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000852
James Molloy392da482012-05-04 10:55:22 +0000853 WIntTy = getFromTargetType(Target.getWIntType());
854
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000855 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
856 InitBuiltinType(Char16Ty, BuiltinType::Char16);
857 else // C99
858 Char16Ty = getFromTargetType(Target.getChar16Type());
859
860 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
861 InitBuiltinType(Char32Ty, BuiltinType::Char32);
862 else // C99
863 Char32Ty = getFromTargetType(Target.getChar32Type());
864
Douglas Gregor898574e2008-12-05 23:32:09 +0000865 // Placeholder type for type-dependent expressions whose type is
866 // completely unknown. No code should ever check a type against
867 // DependentTy and users should never see it; however, it is here to
868 // help diagnose failures to properly check for type-dependent
869 // expressions.
870 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000871
John McCall2a984ca2010-10-12 00:20:44 +0000872 // Placeholder type for functions.
873 InitBuiltinType(OverloadTy, BuiltinType::Overload);
874
John McCall864c0412011-04-26 20:42:42 +0000875 // Placeholder type for bound members.
876 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
877
John McCall3c3b7f92011-10-25 17:37:35 +0000878 // Placeholder type for pseudo-objects.
879 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
880
John McCall1de4d4e2011-04-07 08:22:57 +0000881 // "any" type; useful for debugger-like clients.
882 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
883
John McCall0ddaeb92011-10-17 18:09:15 +0000884 // Placeholder type for unbridged ARC casts.
885 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
886
Eli Friedmana6c66ce2012-08-31 00:14:07 +0000887 // Placeholder type for builtin functions.
888 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
889
Reid Spencer5f016e22007-07-11 17:01:13 +0000890 // C99 6.2.5p11.
891 FloatComplexTy = getComplexType(FloatTy);
892 DoubleComplexTy = getComplexType(DoubleTy);
893 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000894
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000895 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000896 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
897 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000898 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeib13621d2012-12-18 14:38:23 +0000899
900 if (LangOpts.OpenCL) {
901 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
902 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
903 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
904 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
905 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
906 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000907
908 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeib13621d2012-12-18 14:38:23 +0000909 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000910
911 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian93a49942012-04-16 21:03:30 +0000912 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
913 SignedCharTy : BoolTy);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000914
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000915 ObjCConstantStringType = QualType();
Fariborz Jahanianf7992132013-01-04 18:45:40 +0000916
917 ObjCSuperType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000918
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000919 // void * type
920 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000921
922 // nullptr type (C++0x 2.14.7)
923 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000924
925 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
926 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingefb40e3f2012-07-01 15:57:25 +0000927
928 // Builtin type used to help define __builtin_va_list.
929 VaListTagTy = QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000930}
931
David Blaikied6471f72011-09-25 23:23:43 +0000932DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000933 return SourceMgr.getDiagnostics();
934}
935
Douglas Gregor63200642010-08-30 16:49:28 +0000936AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
937 AttrVec *&Result = DeclAttrs[D];
938 if (!Result) {
939 void *Mem = Allocate(sizeof(AttrVec));
940 Result = new (Mem) AttrVec;
941 }
942
943 return *Result;
944}
945
946/// \brief Erase the attributes corresponding to the given declaration.
947void ASTContext::eraseDeclAttrs(const Decl *D) {
948 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
949 if (Pos != DeclAttrs.end()) {
950 Pos->second->~AttrVec();
951 DeclAttrs.erase(Pos);
952 }
953}
954
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000955MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000956ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000957 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000958 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000959 = InstantiatedFromStaticDataMember.find(Var);
960 if (Pos == InstantiatedFromStaticDataMember.end())
961 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000962
Douglas Gregor7caa6822009-07-24 20:34:43 +0000963 return Pos->second;
964}
965
Mike Stump1eb44332009-09-09 15:08:12 +0000966void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000967ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000968 TemplateSpecializationKind TSK,
969 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000970 assert(Inst->isStaticDataMember() && "Not a static data member");
971 assert(Tmpl->isStaticDataMember() && "Not a static data member");
972 assert(!InstantiatedFromStaticDataMember[Inst] &&
973 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000974 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000975 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000976}
977
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000978FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
979 const FunctionDecl *FD){
980 assert(FD && "Specialization is 0");
981 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000982 = ClassScopeSpecializationPattern.find(FD);
983 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000984 return 0;
985
986 return Pos->second;
987}
988
989void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
990 FunctionDecl *Pattern) {
991 assert(FD && "Specialization is 0");
992 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000993 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000994}
995
John McCall7ba107a2009-11-18 02:36:19 +0000996NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000997ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000998 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000999 = InstantiatedFromUsingDecl.find(UUD);
1000 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +00001001 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001002
Anders Carlsson0d8df782009-08-29 19:37:28 +00001003 return Pos->second;
1004}
1005
1006void
John McCalled976492009-12-04 22:46:56 +00001007ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1008 assert((isa<UsingDecl>(Pattern) ||
1009 isa<UnresolvedUsingValueDecl>(Pattern) ||
1010 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1011 "pattern decl is not a using decl");
1012 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1013 InstantiatedFromUsingDecl[Inst] = Pattern;
1014}
1015
1016UsingShadowDecl *
1017ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1018 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1019 = InstantiatedFromUsingShadowDecl.find(Inst);
1020 if (Pos == InstantiatedFromUsingShadowDecl.end())
1021 return 0;
1022
1023 return Pos->second;
1024}
1025
1026void
1027ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1028 UsingShadowDecl *Pattern) {
1029 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1030 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00001031}
1032
Anders Carlssond8b285f2009-09-01 04:26:58 +00001033FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1034 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1035 = InstantiatedFromUnnamedFieldDecl.find(Field);
1036 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1037 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001038
Anders Carlssond8b285f2009-09-01 04:26:58 +00001039 return Pos->second;
1040}
1041
1042void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1043 FieldDecl *Tmpl) {
1044 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1045 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1046 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1047 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +00001048
Anders Carlssond8b285f2009-09-01 04:26:58 +00001049 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1050}
1051
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +00001052bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
1053 const FieldDecl *LastFD) const {
1054 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001055 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +00001056}
1057
Fariborz Jahanian340fa242011-05-02 17:20:56 +00001058bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
1059 const FieldDecl *LastFD) const {
1060 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001061 FD->getBitWidthValue(*this) == 0 &&
1062 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +00001063}
1064
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001065bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
1066 const FieldDecl *LastFD) const {
1067 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001068 FD->getBitWidthValue(*this) &&
1069 LastFD->getBitWidthValue(*this));
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001070}
1071
Chad Rosierdd7fddb2011-08-04 23:34:15 +00001072bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001073 const FieldDecl *LastFD) const {
1074 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001075 LastFD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001076}
1077
Chad Rosierdd7fddb2011-08-04 23:34:15 +00001078bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001079 const FieldDecl *LastFD) const {
1080 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001081 FD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001082}
1083
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001084ASTContext::overridden_cxx_method_iterator
1085ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1086 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001087 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001088 if (Pos == OverriddenMethods.end())
1089 return 0;
1090
1091 return Pos->second.begin();
1092}
1093
1094ASTContext::overridden_cxx_method_iterator
1095ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1096 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001097 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001098 if (Pos == OverriddenMethods.end())
1099 return 0;
1100
1101 return Pos->second.end();
1102}
1103
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001104unsigned
1105ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1106 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001107 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001108 if (Pos == OverriddenMethods.end())
1109 return 0;
1110
1111 return Pos->second.size();
1112}
1113
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001114void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1115 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001116 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001117 OverriddenMethods[Method].push_back(Overridden);
1118}
1119
Dmitri Gribenko1e905da2012-11-03 14:24:57 +00001120void ASTContext::getOverriddenMethods(
1121 const NamedDecl *D,
1122 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001123 assert(D);
1124
1125 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisbc0a2bb2012-10-09 20:08:43 +00001126 Overridden.append(CXXMethod->begin_overridden_methods(),
1127 CXXMethod->end_overridden_methods());
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001128 return;
1129 }
1130
1131 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1132 if (!Method)
1133 return;
1134
Argyrios Kyrtzidis740ae672012-10-09 18:19:01 +00001135 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1136 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisbc0a2bb2012-10-09 20:08:43 +00001137 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001138}
1139
Douglas Gregore6649772011-12-03 00:30:27 +00001140void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1141 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1142 assert(!Import->isFromASTFile() && "Non-local import declaration");
1143 if (!FirstLocalImport) {
1144 FirstLocalImport = Import;
1145 LastLocalImport = Import;
1146 return;
1147 }
1148
1149 LastLocalImport->NextLocalImport = Import;
1150 LastLocalImport = Import;
1151}
1152
Chris Lattner464175b2007-07-18 17:52:12 +00001153//===----------------------------------------------------------------------===//
1154// Type Sizing and Analysis
1155//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +00001156
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001157/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1158/// scalar floating point type.
1159const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +00001160 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001161 assert(BT && "Not a floating point type!");
1162 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001163 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001164 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001165 case BuiltinType::Float: return Target->getFloatFormat();
1166 case BuiltinType::Double: return Target->getDoubleFormat();
1167 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001168 }
1169}
1170
Ken Dyck8b752f12010-01-27 17:10:57 +00001171/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +00001172/// specified decl. Note that bitfields do not have a valid alignment, so
1173/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +00001174/// If @p RefAsPointee, references are treated like their underlying type
1175/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +00001176CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001177 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +00001178
John McCall4081a5c2010-10-08 18:24:19 +00001179 bool UseAlignAttrOnly = false;
1180 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1181 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +00001182
John McCall4081a5c2010-10-08 18:24:19 +00001183 // __attribute__((aligned)) can increase or decrease alignment
1184 // *except* on a struct or struct member, where it only increases
1185 // alignment unless 'packed' is also specified.
1186 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +00001187 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +00001188 // ignore that possibility; Sema should diagnose it.
1189 if (isa<FieldDecl>(D)) {
1190 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1191 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1192 } else {
1193 UseAlignAttrOnly = true;
1194 }
1195 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +00001196 else if (isa<FieldDecl>(D))
1197 UseAlignAttrOnly =
1198 D->hasAttr<PackedAttr>() ||
1199 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +00001200
John McCallba4f5d52011-01-20 07:57:12 +00001201 // If we're using the align attribute only, just ignore everything
1202 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +00001203 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +00001204 // do nothing
1205
John McCall4081a5c2010-10-08 18:24:19 +00001206 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001207 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001208 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001209 if (RefAsPointee)
1210 T = RT->getPointeeType();
1211 else
1212 T = getPointerType(RT->getPointeeType());
1213 }
1214 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +00001215 // Adjust alignments of declarations with array type by the
1216 // large-array alignment on the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001217 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +00001218 const ArrayType *arrayType;
1219 if (MinWidth && (arrayType = getAsArrayType(T))) {
1220 if (isa<VariableArrayType>(arrayType))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001221 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall3b657512011-01-19 10:06:00 +00001222 else if (isa<ConstantArrayType>(arrayType) &&
1223 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001224 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +00001225
John McCall3b657512011-01-19 10:06:00 +00001226 // Walk through any array types while we're at it.
1227 T = getBaseElementType(arrayType);
1228 }
Chad Rosier9f1210c2011-07-26 07:03:04 +00001229 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedmandcdafb62009-02-22 02:56:25 +00001230 }
John McCallba4f5d52011-01-20 07:57:12 +00001231
1232 // Fields can be subject to extra alignment constraints, like if
1233 // the field is packed, the struct is packed, or the struct has a
1234 // a max-field-alignment constraint (#pragma pack). So calculate
1235 // the actual alignment of the field within the struct, and then
1236 // (as we're expected to) constrain that by the alignment of the type.
1237 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1238 // So calculate the alignment of the field.
1239 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1240
1241 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +00001242 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +00001243
1244 // Use the GCD of that and the offset within the record.
1245 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1246 if (offset > 0) {
1247 // Alignment is always a power of 2, so the GCD will be a power of 2,
1248 // which means we get to do this crazy thing instead of Euclid's.
1249 uint64_t lowBitOfOffset = offset & (~offset + 1);
1250 if (lowBitOfOffset < fieldAlign)
1251 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1252 }
1253
1254 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +00001255 }
Chris Lattneraf707ab2009-01-24 21:53:27 +00001256 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001257
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001258 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001259}
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001260
John McCall929bbfb2012-08-21 04:10:00 +00001261// getTypeInfoDataSizeInChars - Return the size of a type, in
1262// chars. If the type is a record, its data size is returned. This is
1263// the size of the memcpy that's performed when assigning this type
1264// using a trivial copy/move assignment operator.
1265std::pair<CharUnits, CharUnits>
1266ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1267 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1268
1269 // In C++, objects can sometimes be allocated into the tail padding
1270 // of a base-class subobject. We decide whether that's possible
1271 // during class layout, so here we can just trust the layout results.
1272 if (getLangOpts().CPlusPlus) {
1273 if (const RecordType *RT = T->getAs<RecordType>()) {
1274 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1275 sizeAndAlign.first = layout.getDataSize();
1276 }
1277 }
1278
1279 return sizeAndAlign;
1280}
1281
John McCallea1471e2010-05-20 01:18:31 +00001282std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001283ASTContext::getTypeInfoInChars(const Type *T) const {
John McCallea1471e2010-05-20 01:18:31 +00001284 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001285 return std::make_pair(toCharUnitsFromBits(Info.first),
1286 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +00001287}
1288
1289std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001290ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +00001291 return getTypeInfoInChars(T.getTypePtr());
1292}
1293
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001294std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1295 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1296 if (it != MemoizedTypeInfo.end())
1297 return it->second;
1298
1299 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1300 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1301 return Info;
1302}
1303
1304/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1305/// method does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +00001306///
1307/// FIXME: Pointers into different addr spaces could have different sizes and
1308/// alignment requirements: getPointerInfo should take an AddrSpace, this
1309/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001310std::pair<uint64_t, unsigned>
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001311ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +00001312 uint64_t Width=0;
1313 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +00001314 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001315#define TYPE(Class, Base)
1316#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +00001317#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +00001318#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1319#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +00001320 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +00001321
Chris Lattner692233e2007-07-13 22:27:08 +00001322 case Type::FunctionNoProto:
1323 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +00001324 // GCC extension: alignof(function) = 32 bits
1325 Width = 0;
1326 Align = 32;
1327 break;
1328
Douglas Gregor72564e72009-02-26 23:50:07 +00001329 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +00001330 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +00001331 Width = 0;
1332 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1333 break;
1334
Steve Narofffb22d962007-08-30 01:06:46 +00001335 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001336 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001337
Chris Lattner98be4942008-03-05 18:54:05 +00001338 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001339 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001340 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1341 "Overflow in array type bit size evaluation");
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001342 Width = EltInfo.first*Size;
Chris Lattner030d8842007-07-19 22:06:24 +00001343 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +00001344 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +00001345 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +00001346 }
Nate Begeman213541a2008-04-18 23:10:10 +00001347 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +00001348 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001349 const VectorType *VT = cast<VectorType>(T);
1350 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1351 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +00001352 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001353 // If the alignment is not a power of 2, round up to the next power of 2.
1354 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +00001355 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001356 Align = llvm::NextPowerOf2(Align);
1357 Width = llvm::RoundUpToAlignment(Width, Align);
1358 }
Chad Rosierf9e9af72012-07-13 23:57:43 +00001359 // Adjust the alignment based on the target max.
1360 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1361 if (TargetVectorAlign && TargetVectorAlign < Align)
1362 Align = TargetVectorAlign;
Chris Lattner030d8842007-07-19 22:06:24 +00001363 break;
1364 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001365
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001366 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +00001367 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001368 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001369 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +00001370 // GCC extension: alignof(void) = 8 bits.
1371 Width = 0;
1372 Align = 8;
1373 break;
1374
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001375 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001376 Width = Target->getBoolWidth();
1377 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001378 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001379 case BuiltinType::Char_S:
1380 case BuiltinType::Char_U:
1381 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001382 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001383 Width = Target->getCharWidth();
1384 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001385 break;
Chris Lattner3f59c972010-12-25 23:25:43 +00001386 case BuiltinType::WChar_S:
1387 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001388 Width = Target->getWCharWidth();
1389 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001390 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001391 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001392 Width = Target->getChar16Width();
1393 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001394 break;
1395 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001396 Width = Target->getChar32Width();
1397 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001398 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001399 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001400 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001401 Width = Target->getShortWidth();
1402 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001403 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001404 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001405 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001406 Width = Target->getIntWidth();
1407 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001408 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001409 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001410 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001411 Width = Target->getLongWidth();
1412 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001413 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001414 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001415 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001416 Width = Target->getLongLongWidth();
1417 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001418 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +00001419 case BuiltinType::Int128:
1420 case BuiltinType::UInt128:
1421 Width = 128;
1422 Align = 128; // int128_t is 128-bit aligned on all targets.
1423 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001424 case BuiltinType::Half:
1425 Width = Target->getHalfWidth();
1426 Align = Target->getHalfAlign();
1427 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001428 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001429 Width = Target->getFloatWidth();
1430 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001431 break;
1432 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001433 Width = Target->getDoubleWidth();
1434 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001435 break;
1436 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001437 Width = Target->getLongDoubleWidth();
1438 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001439 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001440 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001441 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1442 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +00001443 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001444 case BuiltinType::ObjCId:
1445 case BuiltinType::ObjCClass:
1446 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001447 Width = Target->getPointerWidth(0);
1448 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001449 break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00001450 case BuiltinType::OCLEvent:
Guy Benyeib13621d2012-12-18 14:38:23 +00001451 case BuiltinType::OCLImage1d:
1452 case BuiltinType::OCLImage1dArray:
1453 case BuiltinType::OCLImage1dBuffer:
1454 case BuiltinType::OCLImage2d:
1455 case BuiltinType::OCLImage2dArray:
1456 case BuiltinType::OCLImage3d:
1457 // Currently these types are pointers to opaque types.
1458 Width = Target->getPointerWidth(0);
1459 Align = Target->getPointerAlign(0);
1460 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001461 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +00001462 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001463 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001464 Width = Target->getPointerWidth(0);
1465 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001466 break;
Steve Naroff485eeff2008-09-24 15:05:44 +00001467 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001468 unsigned AS = getTargetAddressSpace(
1469 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001470 Width = Target->getPointerWidth(AS);
1471 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +00001472 break;
1473 }
Sebastian Redl5d484e82009-11-23 17:18:46 +00001474 case Type::LValueReference:
1475 case Type::RValueReference: {
1476 // alignof and sizeof should never enter this code path here, so we go
1477 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001478 unsigned AS = getTargetAddressSpace(
1479 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001480 Width = Target->getPointerWidth(AS);
1481 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +00001482 break;
1483 }
Chris Lattnerf72a4432008-03-08 08:34:58 +00001484 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001485 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001486 Width = Target->getPointerWidth(AS);
1487 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +00001488 break;
1489 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00001490 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +00001491 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001492 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001493 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +00001494 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001495 Align = PtrDiffInfo.second;
1496 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001497 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001498 case Type::Complex: {
1499 // Complex types have the same alignment as their elements, but twice the
1500 // size.
Mike Stump1eb44332009-09-09 15:08:12 +00001501 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +00001502 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001503 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +00001504 Align = EltInfo.second;
1505 break;
1506 }
John McCallc12c5bb2010-05-15 11:32:37 +00001507 case Type::ObjCObject:
1508 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +00001509 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001510 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +00001511 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001512 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001513 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +00001514 break;
1515 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001516 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001517 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001518 const TagType *TT = cast<TagType>(T);
1519
1520 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001521 Width = 8;
1522 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001523 break;
1524 }
Mike Stump1eb44332009-09-09 15:08:12 +00001525
Daniel Dunbar1d751182008-11-08 05:48:37 +00001526 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001527 return getTypeInfo(ET->getDecl()->getIntegerType());
1528
Daniel Dunbar1d751182008-11-08 05:48:37 +00001529 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001530 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001531 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001532 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001533 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001534 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001535
Chris Lattner9fcfe922009-10-22 05:17:15 +00001536 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001537 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1538 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001539
Richard Smith34b41d92011-02-20 03:19:35 +00001540 case Type::Auto: {
1541 const AutoType *A = cast<AutoType>(T);
1542 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001543 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001544 }
1545
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001546 case Type::Paren:
1547 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1548
Douglas Gregor18857642009-04-30 17:32:17 +00001549 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001550 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001551 std::pair<uint64_t, unsigned> Info
1552 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001553 // If the typedef has an aligned attribute on it, it overrides any computed
1554 // alignment we have. This violates the GCC documentation (which says that
1555 // attribute(aligned) can only round up) but matches its implementation.
1556 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1557 Align = AttrAlign;
1558 else
1559 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001560 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001561 break;
Chris Lattner71763312008-04-06 22:05:18 +00001562 }
Douglas Gregor18857642009-04-30 17:32:17 +00001563
1564 case Type::TypeOfExpr:
1565 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1566 .getTypePtr());
1567
1568 case Type::TypeOf:
1569 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1570
Anders Carlsson395b4752009-06-24 19:06:50 +00001571 case Type::Decltype:
1572 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1573 .getTypePtr());
1574
Sean Huntca63c202011-05-24 22:41:36 +00001575 case Type::UnaryTransform:
1576 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1577
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001578 case Type::Elaborated:
1579 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001580
John McCall9d156a72011-01-06 01:58:22 +00001581 case Type::Attributed:
1582 return getTypeInfo(
1583 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1584
Richard Smith3e4c6c42011-05-05 21:57:07 +00001585 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00001586 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +00001587 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +00001588 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1589 // A type alias template specialization may refer to a typedef with the
1590 // aligned attribute on it.
1591 if (TST->isTypeAlias())
1592 return getTypeInfo(TST->getAliasedType().getTypePtr());
1593 else
1594 return getTypeInfo(getCanonicalType(T));
1595 }
1596
Eli Friedmanb001de72011-10-06 23:00:33 +00001597 case Type::Atomic: {
Eli Friedman2be46072011-10-14 20:59:01 +00001598 std::pair<uint64_t, unsigned> Info
1599 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1600 Width = Info.first;
1601 Align = Info.second;
1602 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1603 llvm::isPowerOf2_64(Width)) {
1604 // We can potentially perform lock-free atomic operations for this
1605 // type; promote the alignment appropriately.
1606 // FIXME: We could potentially promote the width here as well...
1607 // is that worthwhile? (Non-struct atomic types generally have
1608 // power-of-two size anyway, but structs might not. Requires a bit
1609 // of implementation work to make sure we zero out the extra bits.)
1610 Align = static_cast<unsigned>(Width);
1611 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001612 }
1613
Douglas Gregor18857642009-04-30 17:32:17 +00001614 }
Mike Stump1eb44332009-09-09 15:08:12 +00001615
Eli Friedman2be46072011-10-14 20:59:01 +00001616 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001617 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001618}
1619
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001620/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1621CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1622 return CharUnits::fromQuantity(BitSize / getCharWidth());
1623}
1624
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001625/// toBits - Convert a size in characters to a size in characters.
1626int64_t ASTContext::toBits(CharUnits CharSize) const {
1627 return CharSize.getQuantity() * getCharWidth();
1628}
1629
Ken Dyckbdc601b2009-12-22 14:23:30 +00001630/// getTypeSizeInChars - Return the size of the specified type, in characters.
1631/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001632CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001633 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001634}
Jay Foad4ba2a172011-01-12 09:06:06 +00001635CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001636 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001637}
1638
Ken Dyck16e20cc2010-01-26 17:25:18 +00001639/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001640/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001641CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001642 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001643}
Jay Foad4ba2a172011-01-12 09:06:06 +00001644CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001645 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001646}
1647
Chris Lattner34ebde42009-01-27 18:08:34 +00001648/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1649/// type for the current target in bits. This can be different than the ABI
1650/// alignment in cases where it is beneficial for performance to overalign
1651/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001652unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001653 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001654
1655 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001656 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001657 T = CT->getElementType().getTypePtr();
1658 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosiercde7a1d2012-03-21 20:20:47 +00001659 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1660 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman1eed6022009-05-25 21:27:19 +00001661 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1662
Chris Lattner34ebde42009-01-27 18:08:34 +00001663 return ABIAlign;
1664}
1665
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001666/// DeepCollectObjCIvars -
1667/// This routine first collects all declared, but not synthesized, ivars in
1668/// super class and then collects all ivars, including those synthesized for
1669/// current class. This routine is used for implementation of current class
1670/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001671///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001672void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1673 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001674 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001675 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1676 DeepCollectObjCIvars(SuperClass, false, Ivars);
1677 if (!leafClass) {
1678 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1679 E = OI->ivar_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001680 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001681 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001682 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001683 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001684 Iv= Iv->getNextIvar())
1685 Ivars.push_back(Iv);
1686 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001687}
1688
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001689/// CollectInheritedProtocols - Collect all protocols in current class and
1690/// those inherited by it.
1691void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001692 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001693 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001694 // We can use protocol_iterator here instead of
1695 // all_referenced_protocol_iterator since we are walking all categories.
1696 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1697 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001698 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001699 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001700 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001701 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001702 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001703 CollectInheritedProtocols(*P, Protocols);
1704 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001705 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001706
1707 // Categories of this Interface.
Douglas Gregord3297242013-01-16 23:00:23 +00001708 for (ObjCInterfaceDecl::visible_categories_iterator
1709 Cat = OI->visible_categories_begin(),
1710 CatEnd = OI->visible_categories_end();
1711 Cat != CatEnd; ++Cat) {
1712 CollectInheritedProtocols(*Cat, Protocols);
1713 }
1714
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001715 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1716 while (SD) {
1717 CollectInheritedProtocols(SD, Protocols);
1718 SD = SD->getSuperClass();
1719 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001720 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001721 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001722 PE = OC->protocol_end(); P != PE; ++P) {
1723 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001724 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001725 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1726 PE = Proto->protocol_end(); P != PE; ++P)
1727 CollectInheritedProtocols(*P, Protocols);
1728 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001729 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001730 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1731 PE = OP->protocol_end(); P != PE; ++P) {
1732 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001733 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001734 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1735 PE = Proto->protocol_end(); P != PE; ++P)
1736 CollectInheritedProtocols(*P, Protocols);
1737 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001738 }
1739}
1740
Jay Foad4ba2a172011-01-12 09:06:06 +00001741unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001742 unsigned count = 0;
1743 // Count ivars declared in class extension.
Douglas Gregord3297242013-01-16 23:00:23 +00001744 for (ObjCInterfaceDecl::known_extensions_iterator
1745 Ext = OI->known_extensions_begin(),
1746 ExtEnd = OI->known_extensions_end();
1747 Ext != ExtEnd; ++Ext) {
1748 count += Ext->ivar_size();
1749 }
1750
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001751 // Count ivar defined in this class's implementation. This
1752 // includes synthesized ivars.
1753 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001754 count += ImplDecl->ivar_size();
1755
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001756 return count;
1757}
1758
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +00001759bool ASTContext::isSentinelNullExpr(const Expr *E) {
1760 if (!E)
1761 return false;
1762
1763 // nullptr_t is always treated as null.
1764 if (E->getType()->isNullPtrType()) return true;
1765
1766 if (E->getType()->isAnyPointerType() &&
1767 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1768 Expr::NPC_ValueDependentIsNull))
1769 return true;
1770
1771 // Unfortunately, __null has type 'int'.
1772 if (isa<GNUNullExpr>(E)) return true;
1773
1774 return false;
1775}
1776
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001777/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1778ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1779 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1780 I = ObjCImpls.find(D);
1781 if (I != ObjCImpls.end())
1782 return cast<ObjCImplementationDecl>(I->second);
1783 return 0;
1784}
1785/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1786ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1787 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1788 I = ObjCImpls.find(D);
1789 if (I != ObjCImpls.end())
1790 return cast<ObjCCategoryImplDecl>(I->second);
1791 return 0;
1792}
1793
1794/// \brief Set the implementation of ObjCInterfaceDecl.
1795void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1796 ObjCImplementationDecl *ImplD) {
1797 assert(IFaceD && ImplD && "Passed null params");
1798 ObjCImpls[IFaceD] = ImplD;
1799}
1800/// \brief Set the implementation of ObjCCategoryDecl.
1801void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1802 ObjCCategoryImplDecl *ImplD) {
1803 assert(CatD && ImplD && "Passed null params");
1804 ObjCImpls[CatD] = ImplD;
1805}
1806
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001807ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1808 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1809 return ID;
1810 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1811 return CD->getClassInterface();
1812 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1813 return IMD->getClassInterface();
1814
1815 return 0;
1816}
1817
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001818/// \brief Get the copy initialization expression of VarDecl,or NULL if
1819/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001820Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001821 assert(VD && "Passed null params");
1822 assert(VD->hasAttr<BlocksAttr>() &&
1823 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001824 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001825 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001826 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1827}
1828
1829/// \brief Set the copy inialization expression of a block var decl.
1830void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1831 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001832 assert(VD->hasAttr<BlocksAttr>() &&
1833 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001834 BlockVarCopyInits[VD] = Init;
1835}
1836
John McCalla93c9342009-12-07 02:54:59 +00001837TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001838 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001839 if (!DataSize)
1840 DataSize = TypeLoc::getFullDataSizeForType(T);
1841 else
1842 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001843 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001844
John McCalla93c9342009-12-07 02:54:59 +00001845 TypeSourceInfo *TInfo =
1846 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1847 new (TInfo) TypeSourceInfo(T);
1848 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001849}
1850
John McCalla93c9342009-12-07 02:54:59 +00001851TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001852 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001853 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001854 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001855 return DI;
1856}
1857
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001858const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001859ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001860 return getObjCLayout(D, 0);
1861}
1862
1863const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001864ASTContext::getASTObjCImplementationLayout(
1865 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001866 return getObjCLayout(D->getClassInterface(), D);
1867}
1868
Chris Lattnera7674d82007-07-13 22:13:22 +00001869//===----------------------------------------------------------------------===//
1870// Type creation/memoization methods
1871//===----------------------------------------------------------------------===//
1872
Jay Foad4ba2a172011-01-12 09:06:06 +00001873QualType
John McCall3b657512011-01-19 10:06:00 +00001874ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1875 unsigned fastQuals = quals.getFastQualifiers();
1876 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001877
1878 // Check if we've already instantiated this type.
1879 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001880 ExtQuals::Profile(ID, baseType, quals);
1881 void *insertPos = 0;
1882 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1883 assert(eq->getQualifiers() == quals);
1884 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001885 }
1886
John McCall3b657512011-01-19 10:06:00 +00001887 // If the base type is not canonical, make the appropriate canonical type.
1888 QualType canon;
1889 if (!baseType->isCanonicalUnqualified()) {
1890 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall200fa532012-02-08 00:46:36 +00001891 canonSplit.Quals.addConsistentQualifiers(quals);
1892 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00001893
1894 // Re-find the insert position.
1895 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1896 }
1897
1898 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1899 ExtQualNodes.InsertNode(eq, insertPos);
1900 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001901}
1902
Jay Foad4ba2a172011-01-12 09:06:06 +00001903QualType
1904ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001905 QualType CanT = getCanonicalType(T);
1906 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001907 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001908
John McCall0953e762009-09-24 19:53:00 +00001909 // If we are composing extended qualifiers together, merge together
1910 // into one ExtQuals node.
1911 QualifierCollector Quals;
1912 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001913
John McCall0953e762009-09-24 19:53:00 +00001914 // If this type already has an address space specified, it cannot get
1915 // another one.
1916 assert(!Quals.hasAddressSpace() &&
1917 "Type cannot be in multiple addr spaces!");
1918 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001919
John McCall0953e762009-09-24 19:53:00 +00001920 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001921}
1922
Chris Lattnerb7d25532009-02-18 22:53:11 +00001923QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001924 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001925 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001926 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001927 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001928
John McCall7f040a92010-12-24 02:08:15 +00001929 if (const PointerType *ptr = T->getAs<PointerType>()) {
1930 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001931 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001932 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1933 return getPointerType(ResultType);
1934 }
1935 }
Mike Stump1eb44332009-09-09 15:08:12 +00001936
John McCall0953e762009-09-24 19:53:00 +00001937 // If we are composing extended qualifiers together, merge together
1938 // into one ExtQuals node.
1939 QualifierCollector Quals;
1940 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001941
John McCall0953e762009-09-24 19:53:00 +00001942 // If this type already has an ObjCGC specified, it cannot get
1943 // another one.
1944 assert(!Quals.hasObjCGCAttr() &&
1945 "Type cannot have multiple ObjCGCs!");
1946 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001947
John McCall0953e762009-09-24 19:53:00 +00001948 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001949}
Chris Lattnera7674d82007-07-13 22:13:22 +00001950
John McCalle6a365d2010-12-19 02:44:49 +00001951const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1952 FunctionType::ExtInfo Info) {
1953 if (T->getExtInfo() == Info)
1954 return T;
1955
1956 QualType Result;
1957 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1958 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1959 } else {
1960 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1961 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1962 EPI.ExtInfo = Info;
1963 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1964 FPT->getNumArgs(), EPI);
1965 }
1966
1967 return cast<FunctionType>(Result.getTypePtr());
1968}
1969
Reid Spencer5f016e22007-07-11 17:01:13 +00001970/// getComplexType - Return the uniqued reference to the type for a complex
1971/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001972QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001973 // Unique pointers, to guarantee there is only one pointer of a particular
1974 // structure.
1975 llvm::FoldingSetNodeID ID;
1976 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001977
Reid Spencer5f016e22007-07-11 17:01:13 +00001978 void *InsertPos = 0;
1979 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1980 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001981
Reid Spencer5f016e22007-07-11 17:01:13 +00001982 // If the pointee type isn't canonical, this won't be a canonical type either,
1983 // so fill in the canonical type field.
1984 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001985 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001986 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001987
Reid Spencer5f016e22007-07-11 17:01:13 +00001988 // Get the new insert position for the node we care about.
1989 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001990 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001991 }
John McCall6b304a02009-09-24 23:30:46 +00001992 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001993 Types.push_back(New);
1994 ComplexTypes.InsertNode(New, InsertPos);
1995 return QualType(New, 0);
1996}
1997
Reid Spencer5f016e22007-07-11 17:01:13 +00001998/// getPointerType - Return the uniqued reference to the type for a pointer to
1999/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002000QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002001 // Unique pointers, to guarantee there is only one pointer of a particular
2002 // structure.
2003 llvm::FoldingSetNodeID ID;
2004 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002005
Reid Spencer5f016e22007-07-11 17:01:13 +00002006 void *InsertPos = 0;
2007 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2008 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002009
Reid Spencer5f016e22007-07-11 17:01:13 +00002010 // If the pointee type isn't canonical, this won't be a canonical type either,
2011 // so fill in the canonical type field.
2012 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002013 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002014 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002015
Reid Spencer5f016e22007-07-11 17:01:13 +00002016 // Get the new insert position for the node we care about.
2017 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002018 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002019 }
John McCall6b304a02009-09-24 23:30:46 +00002020 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002021 Types.push_back(New);
2022 PointerTypes.InsertNode(New, InsertPos);
2023 return QualType(New, 0);
2024}
2025
Mike Stump1eb44332009-09-09 15:08:12 +00002026/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00002027/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00002028QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00002029 assert(T->isFunctionType() && "block of function types only");
2030 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00002031 // structure.
2032 llvm::FoldingSetNodeID ID;
2033 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002034
Steve Naroff5618bd42008-08-27 16:04:49 +00002035 void *InsertPos = 0;
2036 if (BlockPointerType *PT =
2037 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2038 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002039
2040 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00002041 // type either so fill in the canonical type field.
2042 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002043 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00002044 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002045
Steve Naroff5618bd42008-08-27 16:04:49 +00002046 // Get the new insert position for the node we care about.
2047 BlockPointerType *NewIP =
2048 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002049 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00002050 }
John McCall6b304a02009-09-24 23:30:46 +00002051 BlockPointerType *New
2052 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00002053 Types.push_back(New);
2054 BlockPointerTypes.InsertNode(New, InsertPos);
2055 return QualType(New, 0);
2056}
2057
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002058/// getLValueReferenceType - Return the uniqued reference to the type for an
2059/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002060QualType
2061ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00002062 assert(getCanonicalType(T) != OverloadTy &&
2063 "Unresolved overloaded function type");
2064
Reid Spencer5f016e22007-07-11 17:01:13 +00002065 // Unique pointers, to guarantee there is only one pointer of a particular
2066 // structure.
2067 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002068 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002069
2070 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002071 if (LValueReferenceType *RT =
2072 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002073 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002074
John McCall54e14c42009-10-22 22:37:11 +00002075 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2076
Reid Spencer5f016e22007-07-11 17:01:13 +00002077 // If the referencee type isn't canonical, this won't be a canonical type
2078 // either, so fill in the canonical type field.
2079 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002080 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2081 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2082 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002083
Reid Spencer5f016e22007-07-11 17:01:13 +00002084 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002085 LValueReferenceType *NewIP =
2086 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002087 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002088 }
2089
John McCall6b304a02009-09-24 23:30:46 +00002090 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00002091 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2092 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002093 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002094 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00002095
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002096 return QualType(New, 0);
2097}
2098
2099/// getRValueReferenceType - Return the uniqued reference to the type for an
2100/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002101QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002102 // Unique pointers, to guarantee there is only one pointer of a particular
2103 // structure.
2104 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002105 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002106
2107 void *InsertPos = 0;
2108 if (RValueReferenceType *RT =
2109 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2110 return QualType(RT, 0);
2111
John McCall54e14c42009-10-22 22:37:11 +00002112 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2113
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002114 // If the referencee type isn't canonical, this won't be a canonical type
2115 // either, so fill in the canonical type field.
2116 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002117 if (InnerRef || !T.isCanonical()) {
2118 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2119 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002120
2121 // Get the new insert position for the node we care about.
2122 RValueReferenceType *NewIP =
2123 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002124 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002125 }
2126
John McCall6b304a02009-09-24 23:30:46 +00002127 RValueReferenceType *New
2128 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002129 Types.push_back(New);
2130 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002131 return QualType(New, 0);
2132}
2133
Sebastian Redlf30208a2009-01-24 21:16:55 +00002134/// getMemberPointerType - Return the uniqued reference to the type for a
2135/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00002136QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002137 // Unique pointers, to guarantee there is only one pointer of a particular
2138 // structure.
2139 llvm::FoldingSetNodeID ID;
2140 MemberPointerType::Profile(ID, T, Cls);
2141
2142 void *InsertPos = 0;
2143 if (MemberPointerType *PT =
2144 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2145 return QualType(PT, 0);
2146
2147 // If the pointee or class type isn't canonical, this won't be a canonical
2148 // type either, so fill in the canonical type field.
2149 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00002150 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002151 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2152
2153 // Get the new insert position for the node we care about.
2154 MemberPointerType *NewIP =
2155 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002156 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00002157 }
John McCall6b304a02009-09-24 23:30:46 +00002158 MemberPointerType *New
2159 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002160 Types.push_back(New);
2161 MemberPointerTypes.InsertNode(New, InsertPos);
2162 return QualType(New, 0);
2163}
2164
Mike Stump1eb44332009-09-09 15:08:12 +00002165/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00002166/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002167QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00002168 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00002169 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002170 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00002171 assert((EltTy->isDependentType() ||
2172 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00002173 "Constant array of VLAs is illegal!");
2174
Chris Lattner38aeec72009-05-13 04:12:56 +00002175 // Convert the array size into a canonical width matching the pointer size for
2176 // the target.
2177 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002178 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002179 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00002180
Reid Spencer5f016e22007-07-11 17:01:13 +00002181 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002182 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00002183
Reid Spencer5f016e22007-07-11 17:01:13 +00002184 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002185 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002186 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002187 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002188
John McCall3b657512011-01-19 10:06:00 +00002189 // If the element type isn't canonical or has qualifiers, this won't
2190 // be a canonical type either, so fill in the canonical type field.
2191 QualType Canon;
2192 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2193 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002194 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002195 ASM, IndexTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002196 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00002197
Reid Spencer5f016e22007-07-11 17:01:13 +00002198 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00002199 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002200 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002201 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002202 }
Mike Stump1eb44332009-09-09 15:08:12 +00002203
John McCall6b304a02009-09-24 23:30:46 +00002204 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002205 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002206 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002207 Types.push_back(New);
2208 return QualType(New, 0);
2209}
2210
John McCallce889032011-01-18 08:40:38 +00002211/// getVariableArrayDecayedType - Turns the given type, which may be
2212/// variably-modified, into the corresponding type with all the known
2213/// sizes replaced with [*].
2214QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2215 // Vastly most common case.
2216 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002217
John McCallce889032011-01-18 08:40:38 +00002218 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002219
John McCallce889032011-01-18 08:40:38 +00002220 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00002221 const Type *ty = split.Ty;
John McCallce889032011-01-18 08:40:38 +00002222 switch (ty->getTypeClass()) {
2223#define TYPE(Class, Base)
2224#define ABSTRACT_TYPE(Class, Base)
2225#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2226#include "clang/AST/TypeNodes.def"
2227 llvm_unreachable("didn't desugar past all non-canonical types?");
2228
2229 // These types should never be variably-modified.
2230 case Type::Builtin:
2231 case Type::Complex:
2232 case Type::Vector:
2233 case Type::ExtVector:
2234 case Type::DependentSizedExtVector:
2235 case Type::ObjCObject:
2236 case Type::ObjCInterface:
2237 case Type::ObjCObjectPointer:
2238 case Type::Record:
2239 case Type::Enum:
2240 case Type::UnresolvedUsing:
2241 case Type::TypeOfExpr:
2242 case Type::TypeOf:
2243 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00002244 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00002245 case Type::DependentName:
2246 case Type::InjectedClassName:
2247 case Type::TemplateSpecialization:
2248 case Type::DependentTemplateSpecialization:
2249 case Type::TemplateTypeParm:
2250 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00002251 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00002252 case Type::PackExpansion:
2253 llvm_unreachable("type should never be variably-modified");
2254
2255 // These types can be variably-modified but should never need to
2256 // further decay.
2257 case Type::FunctionNoProto:
2258 case Type::FunctionProto:
2259 case Type::BlockPointer:
2260 case Type::MemberPointer:
2261 return type;
2262
2263 // These types can be variably-modified. All these modifications
2264 // preserve structure except as noted by comments.
2265 // TODO: if we ever care about optimizing VLAs, there are no-op
2266 // optimizations available here.
2267 case Type::Pointer:
2268 result = getPointerType(getVariableArrayDecayedType(
2269 cast<PointerType>(ty)->getPointeeType()));
2270 break;
2271
2272 case Type::LValueReference: {
2273 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2274 result = getLValueReferenceType(
2275 getVariableArrayDecayedType(lv->getPointeeType()),
2276 lv->isSpelledAsLValue());
2277 break;
2278 }
2279
2280 case Type::RValueReference: {
2281 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2282 result = getRValueReferenceType(
2283 getVariableArrayDecayedType(lv->getPointeeType()));
2284 break;
2285 }
2286
Eli Friedmanb001de72011-10-06 23:00:33 +00002287 case Type::Atomic: {
2288 const AtomicType *at = cast<AtomicType>(ty);
2289 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2290 break;
2291 }
2292
John McCallce889032011-01-18 08:40:38 +00002293 case Type::ConstantArray: {
2294 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2295 result = getConstantArrayType(
2296 getVariableArrayDecayedType(cat->getElementType()),
2297 cat->getSize(),
2298 cat->getSizeModifier(),
2299 cat->getIndexTypeCVRQualifiers());
2300 break;
2301 }
2302
2303 case Type::DependentSizedArray: {
2304 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2305 result = getDependentSizedArrayType(
2306 getVariableArrayDecayedType(dat->getElementType()),
2307 dat->getSizeExpr(),
2308 dat->getSizeModifier(),
2309 dat->getIndexTypeCVRQualifiers(),
2310 dat->getBracketsRange());
2311 break;
2312 }
2313
2314 // Turn incomplete types into [*] types.
2315 case Type::IncompleteArray: {
2316 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2317 result = getVariableArrayType(
2318 getVariableArrayDecayedType(iat->getElementType()),
2319 /*size*/ 0,
2320 ArrayType::Normal,
2321 iat->getIndexTypeCVRQualifiers(),
2322 SourceRange());
2323 break;
2324 }
2325
2326 // Turn VLA types into [*] types.
2327 case Type::VariableArray: {
2328 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2329 result = getVariableArrayType(
2330 getVariableArrayDecayedType(vat->getElementType()),
2331 /*size*/ 0,
2332 ArrayType::Star,
2333 vat->getIndexTypeCVRQualifiers(),
2334 vat->getBracketsRange());
2335 break;
2336 }
2337 }
2338
2339 // Apply the top-level qualifiers from the original.
John McCall200fa532012-02-08 00:46:36 +00002340 return getQualifiedType(result, split.Quals);
John McCallce889032011-01-18 08:40:38 +00002341}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002342
Steve Naroffbdbf7b02007-08-30 18:14:25 +00002343/// getVariableArrayType - Returns a non-unique reference to the type for a
2344/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002345QualType ASTContext::getVariableArrayType(QualType EltTy,
2346 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00002347 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002348 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00002349 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002350 // Since we don't unique expressions, it isn't possible to unique VLA's
2351 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00002352 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00002353
John McCall3b657512011-01-19 10:06:00 +00002354 // Be sure to pull qualifiers off the element type.
2355 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2356 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002357 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002358 IndexTypeQuals, Brackets);
John McCall200fa532012-02-08 00:46:36 +00002359 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor715e9c82010-05-23 16:10:32 +00002360 }
2361
John McCall6b304a02009-09-24 23:30:46 +00002362 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002363 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002364
2365 VariableArrayTypes.push_back(New);
2366 Types.push_back(New);
2367 return QualType(New, 0);
2368}
2369
Douglas Gregor898574e2008-12-05 23:32:09 +00002370/// getDependentSizedArrayType - Returns a non-unique reference to
2371/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00002372/// type.
John McCall3b657512011-01-19 10:06:00 +00002373QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2374 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00002375 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002376 unsigned elementTypeQuals,
2377 SourceRange brackets) const {
2378 assert((!numElements || numElements->isTypeDependent() ||
2379 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00002380 "Size must be type- or value-dependent!");
2381
John McCall3b657512011-01-19 10:06:00 +00002382 // Dependently-sized array types that do not have a specified number
2383 // of elements will have their sizes deduced from a dependent
2384 // initializer. We do no canonicalization here at all, which is okay
2385 // because they can't be used in most locations.
2386 if (!numElements) {
2387 DependentSizedArrayType *newType
2388 = new (*this, TypeAlignment)
2389 DependentSizedArrayType(*this, elementType, QualType(),
2390 numElements, ASM, elementTypeQuals,
2391 brackets);
2392 Types.push_back(newType);
2393 return QualType(newType, 0);
2394 }
2395
2396 // Otherwise, we actually build a new type every time, but we
2397 // also build a canonical type.
2398
2399 SplitQualType canonElementType = getCanonicalType(elementType).split();
2400
2401 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00002402 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002403 DependentSizedArrayType::Profile(ID, *this,
John McCall200fa532012-02-08 00:46:36 +00002404 QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002405 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002406
John McCall3b657512011-01-19 10:06:00 +00002407 // Look for an existing type with these properties.
2408 DependentSizedArrayType *canonTy =
2409 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002410
John McCall3b657512011-01-19 10:06:00 +00002411 // If we don't have one, build one.
2412 if (!canonTy) {
2413 canonTy = new (*this, TypeAlignment)
John McCall200fa532012-02-08 00:46:36 +00002414 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002415 QualType(), numElements, ASM, elementTypeQuals,
2416 brackets);
2417 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2418 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002419 }
2420
John McCall3b657512011-01-19 10:06:00 +00002421 // Apply qualifiers from the element type to the array.
2422 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall200fa532012-02-08 00:46:36 +00002423 canonElementType.Quals);
Mike Stump1eb44332009-09-09 15:08:12 +00002424
John McCall3b657512011-01-19 10:06:00 +00002425 // If we didn't need extra canonicalization for the element type,
2426 // then just use that as our result.
John McCall200fa532012-02-08 00:46:36 +00002427 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall3b657512011-01-19 10:06:00 +00002428 return canon;
2429
2430 // Otherwise, we need to build a type which follows the spelling
2431 // of the element type.
2432 DependentSizedArrayType *sugaredType
2433 = new (*this, TypeAlignment)
2434 DependentSizedArrayType(*this, elementType, canon, numElements,
2435 ASM, elementTypeQuals, brackets);
2436 Types.push_back(sugaredType);
2437 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00002438}
2439
John McCall3b657512011-01-19 10:06:00 +00002440QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00002441 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002442 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002443 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002444 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002445
John McCall3b657512011-01-19 10:06:00 +00002446 void *insertPos = 0;
2447 if (IncompleteArrayType *iat =
2448 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2449 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002450
2451 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00002452 // either, so fill in the canonical type field. We also have to pull
2453 // qualifiers off the element type.
2454 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00002455
John McCall3b657512011-01-19 10:06:00 +00002456 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2457 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall200fa532012-02-08 00:46:36 +00002458 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002459 ASM, elementTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002460 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002461
2462 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00002463 IncompleteArrayType *existing =
2464 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2465 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00002466 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00002467
John McCall3b657512011-01-19 10:06:00 +00002468 IncompleteArrayType *newType = new (*this, TypeAlignment)
2469 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002470
John McCall3b657512011-01-19 10:06:00 +00002471 IncompleteArrayTypes.InsertNode(newType, insertPos);
2472 Types.push_back(newType);
2473 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00002474}
2475
Steve Naroff73322922007-07-18 18:00:27 +00002476/// getVectorType - Return the unique reference to a vector type of
2477/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00002478QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00002479 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00002480 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00002481
Reid Spencer5f016e22007-07-11 17:01:13 +00002482 // Check if we've already instantiated a vector of this type.
2483 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00002484 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00002485
Reid Spencer5f016e22007-07-11 17:01:13 +00002486 void *InsertPos = 0;
2487 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2488 return QualType(VTP, 0);
2489
2490 // If the element type isn't canonical, this won't be a canonical type either,
2491 // so fill in the canonical type field.
2492 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00002493 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00002494 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002495
Reid Spencer5f016e22007-07-11 17:01:13 +00002496 // Get the new insert position for the node we care about.
2497 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002498 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002499 }
John McCall6b304a02009-09-24 23:30:46 +00002500 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00002501 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002502 VectorTypes.InsertNode(New, InsertPos);
2503 Types.push_back(New);
2504 return QualType(New, 0);
2505}
2506
Nate Begeman213541a2008-04-18 23:10:10 +00002507/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00002508/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002509QualType
2510ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00002511 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00002512
Steve Naroff73322922007-07-18 18:00:27 +00002513 // Check if we've already instantiated a vector of this type.
2514 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00002515 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002516 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00002517 void *InsertPos = 0;
2518 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2519 return QualType(VTP, 0);
2520
2521 // If the element type isn't canonical, this won't be a canonical type either,
2522 // so fill in the canonical type field.
2523 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002524 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002525 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00002526
Steve Naroff73322922007-07-18 18:00:27 +00002527 // Get the new insert position for the node we care about.
2528 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002529 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00002530 }
John McCall6b304a02009-09-24 23:30:46 +00002531 ExtVectorType *New = new (*this, TypeAlignment)
2532 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00002533 VectorTypes.InsertNode(New, InsertPos);
2534 Types.push_back(New);
2535 return QualType(New, 0);
2536}
2537
Jay Foad4ba2a172011-01-12 09:06:06 +00002538QualType
2539ASTContext::getDependentSizedExtVectorType(QualType vecType,
2540 Expr *SizeExpr,
2541 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002542 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002543 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002544 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002545
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002546 void *InsertPos = 0;
2547 DependentSizedExtVectorType *Canon
2548 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2549 DependentSizedExtVectorType *New;
2550 if (Canon) {
2551 // We already have a canonical version of this array type; use it as
2552 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002553 New = new (*this, TypeAlignment)
2554 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2555 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002556 } else {
2557 QualType CanonVecTy = getCanonicalType(vecType);
2558 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002559 New = new (*this, TypeAlignment)
2560 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2561 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002562
2563 DependentSizedExtVectorType *CanonCheck
2564 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2565 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2566 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002567 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2568 } else {
2569 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2570 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002571 New = new (*this, TypeAlignment)
2572 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002573 }
2574 }
Mike Stump1eb44332009-09-09 15:08:12 +00002575
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002576 Types.push_back(New);
2577 return QualType(New, 0);
2578}
2579
Douglas Gregor72564e72009-02-26 23:50:07 +00002580/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002581///
Jay Foad4ba2a172011-01-12 09:06:06 +00002582QualType
2583ASTContext::getFunctionNoProtoType(QualType ResultTy,
2584 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00002585 const CallingConv DefaultCC = Info.getCC();
2586 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2587 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00002588 // Unique functions, to guarantee there is only one function of a particular
2589 // structure.
2590 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002591 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002592
Reid Spencer5f016e22007-07-11 17:01:13 +00002593 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002594 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002595 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002596 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002597
Reid Spencer5f016e22007-07-11 17:01:13 +00002598 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00002599 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00002600 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00002601 Canonical =
2602 getFunctionNoProtoType(getCanonicalType(ResultTy),
2603 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00002604
Reid Spencer5f016e22007-07-11 17:01:13 +00002605 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002606 FunctionNoProtoType *NewIP =
2607 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002608 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002609 }
Mike Stump1eb44332009-09-09 15:08:12 +00002610
Roman Divackycfe9af22011-03-01 17:40:53 +00002611 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002612 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002613 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002614 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002615 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002616 return QualType(New, 0);
2617}
2618
Douglas Gregor02dd7982013-01-17 23:36:45 +00002619/// \brief Determine whether \p T is canonical as the result type of a function.
2620static bool isCanonicalResultType(QualType T) {
2621 return T.isCanonical() &&
2622 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2623 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2624}
2625
Reid Spencer5f016e22007-07-11 17:01:13 +00002626/// getFunctionType - Return a normal function type with a typed argument
2627/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002628QualType
2629ASTContext::getFunctionType(QualType ResultTy,
2630 const QualType *ArgArray, unsigned NumArgs,
2631 const FunctionProtoType::ExtProtoInfo &EPI) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002632 // Unique functions, to guarantee there is only one function of a particular
2633 // structure.
2634 llvm::FoldingSetNodeID ID;
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002635 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002636
2637 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002638 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002639 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002640 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002641
2642 // Determine whether the type being created is already canonical or not.
Richard Smitheefb3d52012-02-10 09:58:53 +00002643 bool isCanonical =
Douglas Gregor02dd7982013-01-17 23:36:45 +00002644 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smitheefb3d52012-02-10 09:58:53 +00002645 !EPI.HasTrailingReturn;
Reid Spencer5f016e22007-07-11 17:01:13 +00002646 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002647 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002648 isCanonical = false;
2649
Roman Divackycfe9af22011-03-01 17:40:53 +00002650 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2651 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2652 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002653
Reid Spencer5f016e22007-07-11 17:01:13 +00002654 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002655 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002656 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002657 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002658 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002659 CanonicalArgs.reserve(NumArgs);
2660 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002661 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002662
John McCalle23cf432010-12-14 08:05:40 +00002663 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +00002664 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002665 CanonicalEPI.ExceptionSpecType = EST_None;
2666 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002667 CanonicalEPI.ExtInfo
2668 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2669
Douglas Gregor02dd7982013-01-17 23:36:45 +00002670 // Result types do not have ARC lifetime qualifiers.
2671 QualType CanResultTy = getCanonicalType(ResultTy);
2672 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2673 Qualifiers Qs = CanResultTy.getQualifiers();
2674 Qs.removeObjCLifetime();
2675 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2676 }
2677
2678 Canonical = getFunctionType(CanResultTy,
Jay Foadbeaaccd2009-05-21 09:52:38 +00002679 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00002680 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002681
Reid Spencer5f016e22007-07-11 17:01:13 +00002682 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002683 FunctionProtoType *NewIP =
2684 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002685 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002686 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002687
John McCallf85e1932011-06-15 23:02:42 +00002688 // FunctionProtoType objects are allocated with extra bytes after
2689 // them for three variable size arrays at the end:
2690 // - parameter types
2691 // - exception types
2692 // - consumed-arguments flags
2693 // Instead of the exception types, there could be a noexcept
Richard Smithb9d0b762012-07-27 04:22:15 +00002694 // expression, or information used to resolve the exception
2695 // specification.
John McCalle23cf432010-12-14 08:05:40 +00002696 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002697 NumArgs * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002698 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00002699 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002700 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002701 Size += sizeof(Expr*);
Richard Smithe6975e92012-04-17 00:58:00 +00002702 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smith13bffc52012-04-19 00:08:28 +00002703 Size += 2 * sizeof(FunctionDecl*);
Richard Smithb9d0b762012-07-27 04:22:15 +00002704 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2705 Size += sizeof(FunctionDecl*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002706 }
John McCallf85e1932011-06-15 23:02:42 +00002707 if (EPI.ConsumedArguments)
2708 Size += NumArgs * sizeof(bool);
2709
John McCalle23cf432010-12-14 08:05:40 +00002710 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002711 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2712 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002713 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002714 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002715 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002716 return QualType(FTP, 0);
2717}
2718
John McCall3cb0ebd2010-03-10 03:28:59 +00002719#ifndef NDEBUG
2720static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2721 if (!isa<CXXRecordDecl>(D)) return false;
2722 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2723 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2724 return true;
2725 if (RD->getDescribedClassTemplate() &&
2726 !isa<ClassTemplateSpecializationDecl>(RD))
2727 return true;
2728 return false;
2729}
2730#endif
2731
2732/// getInjectedClassNameType - Return the unique reference to the
2733/// injected class name type for the specified templated declaration.
2734QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002735 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002736 assert(NeedsInjectedClassNameType(Decl));
2737 if (Decl->TypeForDecl) {
2738 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregoref96ee02012-01-14 16:38:05 +00002739 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002740 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2741 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2742 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2743 } else {
John McCallf4c73712011-01-19 06:33:43 +00002744 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002745 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002746 Decl->TypeForDecl = newType;
2747 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002748 }
2749 return QualType(Decl->TypeForDecl, 0);
2750}
2751
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002752/// getTypeDeclType - Return the unique reference to the type for the
2753/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002754QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002755 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002756 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002757
Richard Smith162e1c12011-04-15 14:24:37 +00002758 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002759 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002760
John McCallbecb8d52010-03-10 06:48:02 +00002761 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2762 "Template type parameter types are always available.");
2763
John McCall19c85762010-02-16 03:57:14 +00002764 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002765 assert(!Record->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002766 "struct/union has previous declaration");
2767 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002768 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002769 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002770 assert(!Enum->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002771 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002772 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002773 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002774 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002775 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2776 Decl->TypeForDecl = newType;
2777 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002778 } else
John McCallbecb8d52010-03-10 06:48:02 +00002779 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002780
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002781 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002782}
2783
Reid Spencer5f016e22007-07-11 17:01:13 +00002784/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002785/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002786QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002787ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2788 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002789 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002790
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002791 if (Canonical.isNull())
2792 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002793 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002794 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002795 Decl->TypeForDecl = newType;
2796 Types.push_back(newType);
2797 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002798}
2799
Jay Foad4ba2a172011-01-12 09:06:06 +00002800QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002801 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2802
Douglas Gregoref96ee02012-01-14 16:38:05 +00002803 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002804 if (PrevDecl->TypeForDecl)
2805 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2806
John McCallf4c73712011-01-19 06:33:43 +00002807 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2808 Decl->TypeForDecl = newType;
2809 Types.push_back(newType);
2810 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002811}
2812
Jay Foad4ba2a172011-01-12 09:06:06 +00002813QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002814 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2815
Douglas Gregoref96ee02012-01-14 16:38:05 +00002816 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002817 if (PrevDecl->TypeForDecl)
2818 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2819
John McCallf4c73712011-01-19 06:33:43 +00002820 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2821 Decl->TypeForDecl = newType;
2822 Types.push_back(newType);
2823 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002824}
2825
John McCall9d156a72011-01-06 01:58:22 +00002826QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2827 QualType modifiedType,
2828 QualType equivalentType) {
2829 llvm::FoldingSetNodeID id;
2830 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2831
2832 void *insertPos = 0;
2833 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2834 if (type) return QualType(type, 0);
2835
2836 QualType canon = getCanonicalType(equivalentType);
2837 type = new (*this, TypeAlignment)
2838 AttributedType(canon, attrKind, modifiedType, equivalentType);
2839
2840 Types.push_back(type);
2841 AttributedTypes.InsertNode(type, insertPos);
2842
2843 return QualType(type, 0);
2844}
2845
2846
John McCall49a832b2009-10-18 09:09:24 +00002847/// \brief Retrieve a substitution-result type.
2848QualType
2849ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002850 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002851 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002852 && "replacement types must always be canonical");
2853
2854 llvm::FoldingSetNodeID ID;
2855 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2856 void *InsertPos = 0;
2857 SubstTemplateTypeParmType *SubstParm
2858 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2859
2860 if (!SubstParm) {
2861 SubstParm = new (*this, TypeAlignment)
2862 SubstTemplateTypeParmType(Parm, Replacement);
2863 Types.push_back(SubstParm);
2864 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2865 }
2866
2867 return QualType(SubstParm, 0);
2868}
2869
Douglas Gregorc3069d62011-01-14 02:55:32 +00002870/// \brief Retrieve a
2871QualType ASTContext::getSubstTemplateTypeParmPackType(
2872 const TemplateTypeParmType *Parm,
2873 const TemplateArgument &ArgPack) {
2874#ifndef NDEBUG
2875 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2876 PEnd = ArgPack.pack_end();
2877 P != PEnd; ++P) {
2878 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2879 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2880 }
2881#endif
2882
2883 llvm::FoldingSetNodeID ID;
2884 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2885 void *InsertPos = 0;
2886 if (SubstTemplateTypeParmPackType *SubstParm
2887 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2888 return QualType(SubstParm, 0);
2889
2890 QualType Canon;
2891 if (!Parm->isCanonicalUnqualified()) {
2892 Canon = getCanonicalType(QualType(Parm, 0));
2893 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2894 ArgPack);
2895 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2896 }
2897
2898 SubstTemplateTypeParmPackType *SubstParm
2899 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2900 ArgPack);
2901 Types.push_back(SubstParm);
2902 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2903 return QualType(SubstParm, 0);
2904}
2905
Douglas Gregorfab9d672009-02-05 23:33:38 +00002906/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002907/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002908/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002909QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002910 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002911 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00002912 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002913 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002914 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002915 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002916 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2917
2918 if (TypeParm)
2919 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002920
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002921 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002922 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002923 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002924
2925 TemplateTypeParmType *TypeCheck
2926 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2927 assert(!TypeCheck && "Template type parameter canonical type broken");
2928 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002929 } else
John McCall6b304a02009-09-24 23:30:46 +00002930 TypeParm = new (*this, TypeAlignment)
2931 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002932
2933 Types.push_back(TypeParm);
2934 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2935
2936 return QualType(TypeParm, 0);
2937}
2938
John McCall3cb0ebd2010-03-10 03:28:59 +00002939TypeSourceInfo *
2940ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2941 SourceLocation NameLoc,
2942 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002943 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002944 assert(!Name.getAsDependentTemplateName() &&
2945 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002946 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00002947
2948 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2949 TemplateSpecializationTypeLoc TL
2950 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002951 TL.setTemplateKeywordLoc(SourceLocation());
John McCall3cb0ebd2010-03-10 03:28:59 +00002952 TL.setTemplateNameLoc(NameLoc);
2953 TL.setLAngleLoc(Args.getLAngleLoc());
2954 TL.setRAngleLoc(Args.getRAngleLoc());
2955 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2956 TL.setArgLocInfo(i, Args[i].getLocInfo());
2957 return DI;
2958}
2959
Mike Stump1eb44332009-09-09 15:08:12 +00002960QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002961ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002962 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002963 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002964 assert(!Template.getAsDependentTemplateName() &&
2965 "No dependent template names here!");
2966
John McCalld5532b62009-11-23 01:53:49 +00002967 unsigned NumArgs = Args.size();
2968
Chris Lattner5f9e2722011-07-23 10:55:15 +00002969 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00002970 ArgVec.reserve(NumArgs);
2971 for (unsigned i = 0; i != NumArgs; ++i)
2972 ArgVec.push_back(Args[i].getArgument());
2973
John McCall31f17ec2010-04-27 00:57:59 +00002974 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002975 Underlying);
John McCall833ca992009-10-29 08:12:44 +00002976}
2977
Douglas Gregorb70126a2012-02-03 17:16:23 +00002978#ifndef NDEBUG
2979static bool hasAnyPackExpansions(const TemplateArgument *Args,
2980 unsigned NumArgs) {
2981 for (unsigned I = 0; I != NumArgs; ++I)
2982 if (Args[I].isPackExpansion())
2983 return true;
2984
2985 return true;
2986}
2987#endif
2988
John McCall833ca992009-10-29 08:12:44 +00002989QualType
2990ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002991 const TemplateArgument *Args,
2992 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002993 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002994 assert(!Template.getAsDependentTemplateName() &&
2995 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002996 // Look through qualified template names.
2997 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2998 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002999
Douglas Gregorb70126a2012-02-03 17:16:23 +00003000 bool IsTypeAlias =
Richard Smith3e4c6c42011-05-05 21:57:07 +00003001 Template.getAsTemplateDecl() &&
3002 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00003003 QualType CanonType;
3004 if (!Underlying.isNull())
3005 CanonType = getCanonicalType(Underlying);
3006 else {
Douglas Gregorb70126a2012-02-03 17:16:23 +00003007 // We can get here with an alias template when the specialization contains
3008 // a pack expansion that does not match up with a parameter pack.
3009 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3010 "Caller must compute aliased type");
3011 IsTypeAlias = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00003012 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3013 NumArgs);
3014 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00003015
Douglas Gregor1275ae02009-07-28 23:00:59 +00003016 // Allocate the (non-canonical) template specialization type, but don't
3017 // try to unique it: these types typically have location information that
3018 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00003019 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3020 sizeof(TemplateArgument) * NumArgs +
Douglas Gregorb70126a2012-02-03 17:16:23 +00003021 (IsTypeAlias? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00003022 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00003023 TemplateSpecializationType *Spec
Douglas Gregorb70126a2012-02-03 17:16:23 +00003024 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3025 IsTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00003026
Douglas Gregor55f6b142009-02-09 18:46:07 +00003027 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00003028 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00003029}
3030
Mike Stump1eb44332009-09-09 15:08:12 +00003031QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003032ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3033 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00003034 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003035 assert(!Template.getAsDependentTemplateName() &&
3036 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00003037
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003038 // Look through qualified template names.
3039 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3040 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003041
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003042 // Build the canonical template specialization type.
3043 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003044 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003045 CanonArgs.reserve(NumArgs);
3046 for (unsigned I = 0; I != NumArgs; ++I)
3047 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3048
3049 // Determine whether this canonical template specialization type already
3050 // exists.
3051 llvm::FoldingSetNodeID ID;
3052 TemplateSpecializationType::Profile(ID, CanonTemplate,
3053 CanonArgs.data(), NumArgs, *this);
3054
3055 void *InsertPos = 0;
3056 TemplateSpecializationType *Spec
3057 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3058
3059 if (!Spec) {
3060 // Allocate a new canonical template specialization type.
3061 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3062 sizeof(TemplateArgument) * NumArgs),
3063 TypeAlignment);
3064 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3065 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003066 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003067 Types.push_back(Spec);
3068 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3069 }
3070
3071 assert(Spec->isDependentType() &&
3072 "Non-dependent template-id type must have a canonical type");
3073 return QualType(Spec, 0);
3074}
3075
3076QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003077ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3078 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00003079 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00003080 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003081 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003082
3083 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003084 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003085 if (T)
3086 return QualType(T, 0);
3087
Douglas Gregor789b1f62010-02-04 18:10:26 +00003088 QualType Canon = NamedType;
3089 if (!Canon.isCanonical()) {
3090 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003091 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3092 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00003093 (void)CheckT;
3094 }
3095
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003096 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003097 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003098 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003099 return QualType(T, 0);
3100}
3101
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003102QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00003103ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003104 llvm::FoldingSetNodeID ID;
3105 ParenType::Profile(ID, InnerType);
3106
3107 void *InsertPos = 0;
3108 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3109 if (T)
3110 return QualType(T, 0);
3111
3112 QualType Canon = InnerType;
3113 if (!Canon.isCanonical()) {
3114 Canon = getCanonicalType(InnerType);
3115 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3116 assert(!CheckT && "Paren canonical type broken");
3117 (void)CheckT;
3118 }
3119
3120 T = new (*this) ParenType(InnerType, Canon);
3121 Types.push_back(T);
3122 ParenTypes.InsertNode(T, InsertPos);
3123 return QualType(T, 0);
3124}
3125
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003126QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3127 NestedNameSpecifier *NNS,
3128 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003129 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00003130 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3131
3132 if (Canon.isNull()) {
3133 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003134 ElaboratedTypeKeyword CanonKeyword = Keyword;
3135 if (Keyword == ETK_None)
3136 CanonKeyword = ETK_Typename;
3137
3138 if (CanonNNS != NNS || CanonKeyword != Keyword)
3139 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003140 }
3141
3142 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003143 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003144
3145 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00003146 DependentNameType *T
3147 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00003148 if (T)
3149 return QualType(T, 0);
3150
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003151 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00003152 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00003153 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003154 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00003155}
3156
Mike Stump1eb44332009-09-09 15:08:12 +00003157QualType
John McCall33500952010-06-11 00:33:02 +00003158ASTContext::getDependentTemplateSpecializationType(
3159 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003160 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00003161 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003162 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00003163 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00003164 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00003165 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3166 ArgCopy.push_back(Args[I].getArgument());
3167 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3168 ArgCopy.size(),
3169 ArgCopy.data());
3170}
3171
3172QualType
3173ASTContext::getDependentTemplateSpecializationType(
3174 ElaboratedTypeKeyword Keyword,
3175 NestedNameSpecifier *NNS,
3176 const IdentifierInfo *Name,
3177 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00003178 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003179 assert((!NNS || NNS->isDependent()) &&
3180 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00003181
Douglas Gregor789b1f62010-02-04 18:10:26 +00003182 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00003183 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3184 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003185
3186 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00003187 DependentTemplateSpecializationType *T
3188 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003189 if (T)
3190 return QualType(T, 0);
3191
John McCall33500952010-06-11 00:33:02 +00003192 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003193
John McCall33500952010-06-11 00:33:02 +00003194 ElaboratedTypeKeyword CanonKeyword = Keyword;
3195 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3196
3197 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003198 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00003199 for (unsigned I = 0; I != NumArgs; ++I) {
3200 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3201 if (!CanonArgs[I].structurallyEquals(Args[I]))
3202 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00003203 }
3204
John McCall33500952010-06-11 00:33:02 +00003205 QualType Canon;
3206 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3207 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3208 Name, NumArgs,
3209 CanonArgs.data());
3210
3211 // Find the insert position again.
3212 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3213 }
3214
3215 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3216 sizeof(TemplateArgument) * NumArgs),
3217 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00003218 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00003219 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00003220 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00003221 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003222 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00003223}
3224
Douglas Gregorcded4f62011-01-14 17:04:44 +00003225QualType ASTContext::getPackExpansionType(QualType Pattern,
3226 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00003227 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00003228 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003229
3230 assert(Pattern->containsUnexpandedParameterPack() &&
3231 "Pack expansions must expand one or more parameter packs");
3232 void *InsertPos = 0;
3233 PackExpansionType *T
3234 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3235 if (T)
3236 return QualType(T, 0);
3237
3238 QualType Canon;
3239 if (!Pattern.isCanonical()) {
Richard Smithd8672ef2012-07-16 00:20:35 +00003240 Canon = getCanonicalType(Pattern);
3241 // The canonical type might not contain an unexpanded parameter pack, if it
3242 // contains an alias template specialization which ignores one of its
3243 // parameters.
3244 if (Canon->containsUnexpandedParameterPack()) {
3245 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003246
Richard Smithd8672ef2012-07-16 00:20:35 +00003247 // Find the insert position again, in case we inserted an element into
3248 // PackExpansionTypes and invalidated our insert position.
3249 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3250 }
Douglas Gregor7536dd52010-12-20 02:24:11 +00003251 }
3252
Douglas Gregorcded4f62011-01-14 17:04:44 +00003253 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003254 Types.push_back(T);
3255 PackExpansionTypes.InsertNode(T, InsertPos);
3256 return QualType(T, 0);
3257}
3258
Chris Lattner88cb27a2008-04-07 04:56:42 +00003259/// CmpProtocolNames - Comparison predicate for sorting protocols
3260/// alphabetically.
3261static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3262 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003263 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00003264}
3265
John McCallc12c5bb2010-05-15 11:32:37 +00003266static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00003267 unsigned NumProtocols) {
3268 if (NumProtocols == 0) return true;
3269
Douglas Gregor61cc2962012-01-02 02:00:30 +00003270 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3271 return false;
3272
John McCall54e14c42009-10-22 22:37:11 +00003273 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregor61cc2962012-01-02 02:00:30 +00003274 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3275 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCall54e14c42009-10-22 22:37:11 +00003276 return false;
3277 return true;
3278}
3279
3280static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00003281 unsigned &NumProtocols) {
3282 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00003283
Chris Lattner88cb27a2008-04-07 04:56:42 +00003284 // Sort protocols, keyed by name.
3285 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3286
Douglas Gregor61cc2962012-01-02 02:00:30 +00003287 // Canonicalize.
3288 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3289 Protocols[I] = Protocols[I]->getCanonicalDecl();
3290
Chris Lattner88cb27a2008-04-07 04:56:42 +00003291 // Remove duplicates.
3292 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3293 NumProtocols = ProtocolsEnd-Protocols;
3294}
3295
John McCallc12c5bb2010-05-15 11:32:37 +00003296QualType ASTContext::getObjCObjectType(QualType BaseType,
3297 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00003298 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003299 // If the base type is an interface and there aren't any protocols
3300 // to add, then the interface type will do just fine.
3301 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3302 return BaseType;
3303
3304 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003305 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00003306 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003307 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00003308 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3309 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003310
John McCallc12c5bb2010-05-15 11:32:37 +00003311 // Build the canonical type, which has the canonical base type and
3312 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00003313 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00003314 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3315 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3316 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003317 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00003318 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003319 unsigned UniqueCount = NumProtocols;
3320
John McCall54e14c42009-10-22 22:37:11 +00003321 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00003322 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3323 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00003324 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00003325 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3326 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003327 }
3328
3329 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00003330 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3331 }
3332
3333 unsigned Size = sizeof(ObjCObjectTypeImpl);
3334 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3335 void *Mem = Allocate(Size, TypeAlignment);
3336 ObjCObjectTypeImpl *T =
3337 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3338
3339 Types.push_back(T);
3340 ObjCObjectTypes.InsertNode(T, InsertPos);
3341 return QualType(T, 0);
3342}
3343
3344/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3345/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003346QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003347 llvm::FoldingSetNodeID ID;
3348 ObjCObjectPointerType::Profile(ID, ObjectT);
3349
3350 void *InsertPos = 0;
3351 if (ObjCObjectPointerType *QT =
3352 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3353 return QualType(QT, 0);
3354
3355 // Find the canonical object type.
3356 QualType Canonical;
3357 if (!ObjectT.isCanonical()) {
3358 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3359
3360 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00003361 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3362 }
3363
Douglas Gregorfd6a0882010-02-08 22:59:26 +00003364 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00003365 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3366 ObjCObjectPointerType *QType =
3367 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00003368
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003369 Types.push_back(QType);
3370 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00003371 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003372}
Chris Lattner88cb27a2008-04-07 04:56:42 +00003373
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003374/// getObjCInterfaceType - Return the unique reference to the type for the
3375/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00003376QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3377 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003378 if (Decl->TypeForDecl)
3379 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003380
Douglas Gregor0af55012011-12-16 03:12:41 +00003381 if (PrevDecl) {
3382 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3383 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3384 return QualType(PrevDecl->TypeForDecl, 0);
3385 }
3386
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00003387 // Prefer the definition, if there is one.
3388 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3389 Decl = Def;
3390
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003391 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3392 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3393 Decl->TypeForDecl = T;
3394 Types.push_back(T);
3395 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00003396}
3397
Douglas Gregor72564e72009-02-26 23:50:07 +00003398/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3399/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00003400/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00003401/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003402/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003403QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003404 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00003405 if (tofExpr->isTypeDependent()) {
3406 llvm::FoldingSetNodeID ID;
3407 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00003408
Douglas Gregorb1975722009-07-30 23:18:24 +00003409 void *InsertPos = 0;
3410 DependentTypeOfExprType *Canon
3411 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3412 if (Canon) {
3413 // We already have a "canonical" version of an identical, dependent
3414 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00003415 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00003416 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003417 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00003418 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003419 Canon
3420 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00003421 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3422 toe = Canon;
3423 }
3424 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003425 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00003426 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00003427 }
Steve Naroff9752f252007-08-01 18:02:17 +00003428 Types.push_back(toe);
3429 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003430}
3431
Steve Naroff9752f252007-08-01 18:02:17 +00003432/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3433/// TypeOfType AST's. The only motivation to unique these nodes would be
3434/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003435/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003436/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003437QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00003438 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00003439 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00003440 Types.push_back(tot);
3441 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003442}
3443
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00003444
Anders Carlsson395b4752009-06-24 19:06:50 +00003445/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3446/// DecltypeType AST's. The only motivation to unique these nodes would be
3447/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003448/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00003449/// on canonical types (which are always unique).
Douglas Gregorf8af9822012-02-12 18:42:33 +00003450QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003451 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00003452
3453 // C++0x [temp.type]p2:
3454 // If an expression e involves a template parameter, decltype(e) denotes a
3455 // unique dependent type. Two such decltype-specifiers refer to the same
3456 // type only if their expressions are equivalent (14.5.6.1).
3457 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003458 llvm::FoldingSetNodeID ID;
3459 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00003460
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003461 void *InsertPos = 0;
3462 DependentDecltypeType *Canon
3463 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3464 if (Canon) {
3465 // We already have a "canonical" version of an equivalent, dependent
3466 // decltype type. Use that as our canonical type.
Richard Smith0d729102012-08-13 20:08:14 +00003467 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003468 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003469 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003470 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003471 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003472 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3473 dt = Canon;
3474 }
3475 } else {
Douglas Gregorf8af9822012-02-12 18:42:33 +00003476 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3477 getCanonicalType(UnderlyingType));
Douglas Gregordd0257c2009-07-08 00:03:05 +00003478 }
Anders Carlsson395b4752009-06-24 19:06:50 +00003479 Types.push_back(dt);
3480 return QualType(dt, 0);
3481}
3482
Sean Huntca63c202011-05-24 22:41:36 +00003483/// getUnaryTransformationType - We don't unique these, since the memory
3484/// savings are minimal and these are rare.
3485QualType ASTContext::getUnaryTransformType(QualType BaseType,
3486 QualType UnderlyingType,
3487 UnaryTransformType::UTTKind Kind)
3488 const {
3489 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00003490 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3491 Kind,
3492 UnderlyingType->isDependentType() ?
Peter Collingbourne12fc4b02012-03-05 16:02:06 +00003493 QualType() : getCanonicalType(UnderlyingType));
Sean Huntca63c202011-05-24 22:41:36 +00003494 Types.push_back(Ty);
3495 return QualType(Ty, 0);
3496}
3497
Richard Smith483b9f32011-02-21 20:05:19 +00003498/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith34b41d92011-02-20 03:19:35 +00003499QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smith483b9f32011-02-21 20:05:19 +00003500 void *InsertPos = 0;
3501 if (!DeducedType.isNull()) {
3502 // Look in the folding set for an existing type.
3503 llvm::FoldingSetNodeID ID;
3504 AutoType::Profile(ID, DeducedType);
3505 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3506 return QualType(AT, 0);
3507 }
3508
3509 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3510 Types.push_back(AT);
3511 if (InsertPos)
3512 AutoTypes.InsertNode(AT, InsertPos);
3513 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00003514}
3515
Eli Friedmanb001de72011-10-06 23:00:33 +00003516/// getAtomicType - Return the uniqued reference to the atomic type for
3517/// the given value type.
3518QualType ASTContext::getAtomicType(QualType T) const {
3519 // Unique pointers, to guarantee there is only one pointer of a particular
3520 // structure.
3521 llvm::FoldingSetNodeID ID;
3522 AtomicType::Profile(ID, T);
3523
3524 void *InsertPos = 0;
3525 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3526 return QualType(AT, 0);
3527
3528 // If the atomic value type isn't canonical, this won't be a canonical type
3529 // either, so fill in the canonical type field.
3530 QualType Canonical;
3531 if (!T.isCanonical()) {
3532 Canonical = getAtomicType(getCanonicalType(T));
3533
3534 // Get the new insert position for the node we care about.
3535 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3536 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3537 }
3538 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3539 Types.push_back(New);
3540 AtomicTypes.InsertNode(New, InsertPos);
3541 return QualType(New, 0);
3542}
3543
Richard Smithad762fc2011-04-14 22:09:26 +00003544/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3545QualType ASTContext::getAutoDeductType() const {
3546 if (AutoDeductTy.isNull())
3547 AutoDeductTy = getAutoType(QualType());
3548 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3549 return AutoDeductTy;
3550}
3551
3552/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3553QualType ASTContext::getAutoRRefDeductType() const {
3554 if (AutoRRefDeductTy.isNull())
3555 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3556 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3557 return AutoRRefDeductTy;
3558}
3559
Reid Spencer5f016e22007-07-11 17:01:13 +00003560/// getTagDeclType - Return the unique reference to the type for the
3561/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003562QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003563 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003564 // FIXME: What is the design on getTagDeclType when it requires casting
3565 // away const? mutable?
3566 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003567}
3568
Mike Stump1eb44332009-09-09 15:08:12 +00003569/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3570/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3571/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003572CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003573 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003574}
3575
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003576/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3577CanQualType ASTContext::getIntMaxType() const {
3578 return getFromTargetType(Target->getIntMaxType());
3579}
3580
3581/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3582CanQualType ASTContext::getUIntMaxType() const {
3583 return getFromTargetType(Target->getUIntMaxType());
3584}
3585
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003586/// getSignedWCharType - Return the type of "signed wchar_t".
3587/// Used when in C++, as a GCC extension.
3588QualType ASTContext::getSignedWCharType() const {
3589 // FIXME: derive from "Target" ?
3590 return WCharTy;
3591}
3592
3593/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3594/// Used when in C++, as a GCC extension.
3595QualType ASTContext::getUnsignedWCharType() const {
3596 // FIXME: derive from "Target" ?
3597 return UnsignedIntTy;
3598}
3599
Enea Zaffanella9677eb82013-01-26 17:08:37 +00003600QualType ASTContext::getIntPtrType() const {
3601 return getFromTargetType(Target->getIntPtrType());
3602}
3603
3604QualType ASTContext::getUIntPtrType() const {
3605 return getCorrespondingUnsignedType(getIntPtrType());
3606}
3607
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003608/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003609/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3610QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003611 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003612}
3613
Eli Friedman6902e412012-11-27 02:58:24 +00003614/// \brief Return the unique type for "pid_t" defined in
3615/// <sys/types.h>. We need this to compute the correct type for vfork().
3616QualType ASTContext::getProcessIDType() const {
3617 return getFromTargetType(Target->getProcessIDType());
3618}
3619
Chris Lattnere6327742008-04-02 05:18:44 +00003620//===----------------------------------------------------------------------===//
3621// Type Operators
3622//===----------------------------------------------------------------------===//
3623
Jay Foad4ba2a172011-01-12 09:06:06 +00003624CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003625 // Push qualifiers into arrays, and then discard any remaining
3626 // qualifiers.
3627 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003628 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003629 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003630 QualType Result;
3631 if (isa<ArrayType>(Ty)) {
3632 Result = getArrayDecayedType(QualType(Ty,0));
3633 } else if (isa<FunctionType>(Ty)) {
3634 Result = getPointerType(QualType(Ty, 0));
3635 } else {
3636 Result = QualType(Ty, 0);
3637 }
3638
3639 return CanQualType::CreateUnsafe(Result);
3640}
3641
John McCall62c28c82011-01-18 07:41:22 +00003642QualType ASTContext::getUnqualifiedArrayType(QualType type,
3643 Qualifiers &quals) {
3644 SplitQualType splitType = type.getSplitUnqualifiedType();
3645
3646 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3647 // the unqualified desugared type and then drops it on the floor.
3648 // We then have to strip that sugar back off with
3649 // getUnqualifiedDesugaredType(), which is silly.
3650 const ArrayType *AT =
John McCall200fa532012-02-08 00:46:36 +00003651 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall62c28c82011-01-18 07:41:22 +00003652
3653 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003654 if (!AT) {
John McCall200fa532012-02-08 00:46:36 +00003655 quals = splitType.Quals;
3656 return QualType(splitType.Ty, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003657 }
3658
John McCall62c28c82011-01-18 07:41:22 +00003659 // Otherwise, recurse on the array's element type.
3660 QualType elementType = AT->getElementType();
3661 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3662
3663 // If that didn't change the element type, AT has no qualifiers, so we
3664 // can just use the results in splitType.
3665 if (elementType == unqualElementType) {
3666 assert(quals.empty()); // from the recursive call
John McCall200fa532012-02-08 00:46:36 +00003667 quals = splitType.Quals;
3668 return QualType(splitType.Ty, 0);
John McCall62c28c82011-01-18 07:41:22 +00003669 }
3670
3671 // Otherwise, add in the qualifiers from the outermost type, then
3672 // build the type back up.
John McCall200fa532012-02-08 00:46:36 +00003673 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003674
Douglas Gregor9dadd942010-05-17 18:45:21 +00003675 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003676 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003677 CAT->getSizeModifier(), 0);
3678 }
3679
Douglas Gregor9dadd942010-05-17 18:45:21 +00003680 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003681 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003682 }
3683
Douglas Gregor9dadd942010-05-17 18:45:21 +00003684 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003685 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003686 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003687 VAT->getSizeModifier(),
3688 VAT->getIndexTypeCVRQualifiers(),
3689 VAT->getBracketsRange());
3690 }
3691
3692 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003693 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003694 DSAT->getSizeModifier(), 0,
3695 SourceRange());
3696}
3697
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003698/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3699/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3700/// they point to and return true. If T1 and T2 aren't pointer types
3701/// or pointer-to-member types, or if they are not similar at this
3702/// level, returns false and leaves T1 and T2 unchanged. Top-level
3703/// qualifiers on T1 and T2 are ignored. This function will typically
3704/// be called in a loop that successively "unwraps" pointer and
3705/// pointer-to-member types to compare them at each level.
3706bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3707 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3708 *T2PtrType = T2->getAs<PointerType>();
3709 if (T1PtrType && T2PtrType) {
3710 T1 = T1PtrType->getPointeeType();
3711 T2 = T2PtrType->getPointeeType();
3712 return true;
3713 }
3714
3715 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3716 *T2MPType = T2->getAs<MemberPointerType>();
3717 if (T1MPType && T2MPType &&
3718 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3719 QualType(T2MPType->getClass(), 0))) {
3720 T1 = T1MPType->getPointeeType();
3721 T2 = T2MPType->getPointeeType();
3722 return true;
3723 }
3724
David Blaikie4e4d0842012-03-11 07:00:24 +00003725 if (getLangOpts().ObjC1) {
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003726 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3727 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3728 if (T1OPType && T2OPType) {
3729 T1 = T1OPType->getPointeeType();
3730 T2 = T2OPType->getPointeeType();
3731 return true;
3732 }
3733 }
3734
3735 // FIXME: Block pointers, too?
3736
3737 return false;
3738}
3739
Jay Foad4ba2a172011-01-12 09:06:06 +00003740DeclarationNameInfo
3741ASTContext::getNameForTemplate(TemplateName Name,
3742 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003743 switch (Name.getKind()) {
3744 case TemplateName::QualifiedTemplate:
3745 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003746 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003747 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3748 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003749
John McCall14606042011-06-30 08:33:18 +00003750 case TemplateName::OverloadedTemplate: {
3751 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3752 // DNInfo work in progress: CHECKME: what about DNLoc?
3753 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3754 }
3755
3756 case TemplateName::DependentTemplate: {
3757 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003758 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003759 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003760 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3761 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003762 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003763 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3764 // DNInfo work in progress: FIXME: source locations?
3765 DeclarationNameLoc DNLoc;
3766 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3767 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3768 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003769 }
3770 }
3771
John McCall14606042011-06-30 08:33:18 +00003772 case TemplateName::SubstTemplateTemplateParm: {
3773 SubstTemplateTemplateParmStorage *subst
3774 = Name.getAsSubstTemplateTemplateParm();
3775 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3776 NameLoc);
3777 }
3778
3779 case TemplateName::SubstTemplateTemplateParmPack: {
3780 SubstTemplateTemplateParmPackStorage *subst
3781 = Name.getAsSubstTemplateTemplateParmPack();
3782 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3783 NameLoc);
3784 }
3785 }
3786
3787 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003788}
3789
Jay Foad4ba2a172011-01-12 09:06:06 +00003790TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003791 switch (Name.getKind()) {
3792 case TemplateName::QualifiedTemplate:
3793 case TemplateName::Template: {
3794 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003795 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003796 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003797 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3798
3799 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003800 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003801 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003802
John McCall14606042011-06-30 08:33:18 +00003803 case TemplateName::OverloadedTemplate:
3804 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003805
John McCall14606042011-06-30 08:33:18 +00003806 case TemplateName::DependentTemplate: {
3807 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3808 assert(DTN && "Non-dependent template names must refer to template decls.");
3809 return DTN->CanonicalTemplateName;
3810 }
3811
3812 case TemplateName::SubstTemplateTemplateParm: {
3813 SubstTemplateTemplateParmStorage *subst
3814 = Name.getAsSubstTemplateTemplateParm();
3815 return getCanonicalTemplateName(subst->getReplacement());
3816 }
3817
3818 case TemplateName::SubstTemplateTemplateParmPack: {
3819 SubstTemplateTemplateParmPackStorage *subst
3820 = Name.getAsSubstTemplateTemplateParmPack();
3821 TemplateTemplateParmDecl *canonParameter
3822 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3823 TemplateArgument canonArgPack
3824 = getCanonicalTemplateArgument(subst->getArgumentPack());
3825 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3826 }
3827 }
3828
3829 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003830}
3831
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003832bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3833 X = getCanonicalTemplateName(X);
3834 Y = getCanonicalTemplateName(Y);
3835 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3836}
3837
Mike Stump1eb44332009-09-09 15:08:12 +00003838TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003839ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003840 switch (Arg.getKind()) {
3841 case TemplateArgument::Null:
3842 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003843
Douglas Gregor1275ae02009-07-28 23:00:59 +00003844 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003845 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003846
Douglas Gregord2008e22012-04-06 22:40:38 +00003847 case TemplateArgument::Declaration: {
Eli Friedmand7a6b162012-09-26 02:36:12 +00003848 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
3849 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregord2008e22012-04-06 22:40:38 +00003850 }
Mike Stump1eb44332009-09-09 15:08:12 +00003851
Eli Friedmand7a6b162012-09-26 02:36:12 +00003852 case TemplateArgument::NullPtr:
3853 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
3854 /*isNullPtr*/true);
3855
Douglas Gregor788cd062009-11-11 01:00:40 +00003856 case TemplateArgument::Template:
3857 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003858
3859 case TemplateArgument::TemplateExpansion:
3860 return TemplateArgument(getCanonicalTemplateName(
3861 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00003862 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00003863
Douglas Gregor1275ae02009-07-28 23:00:59 +00003864 case TemplateArgument::Integral:
Benjamin Kramer85524372012-06-07 15:09:51 +00003865 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003866
Douglas Gregor1275ae02009-07-28 23:00:59 +00003867 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00003868 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003869
Douglas Gregor1275ae02009-07-28 23:00:59 +00003870 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00003871 if (Arg.pack_size() == 0)
3872 return Arg;
3873
Douglas Gregor910f8002010-11-07 23:05:16 +00003874 TemplateArgument *CanonArgs
3875 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00003876 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003877 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003878 AEnd = Arg.pack_end();
3879 A != AEnd; (void)++A, ++Idx)
3880 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00003881
Douglas Gregor910f8002010-11-07 23:05:16 +00003882 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00003883 }
3884 }
3885
3886 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00003887 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00003888}
3889
Douglas Gregord57959a2009-03-27 23:10:48 +00003890NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00003891ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00003892 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00003893 return 0;
3894
3895 switch (NNS->getKind()) {
3896 case NestedNameSpecifier::Identifier:
3897 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00003898 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00003899 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3900 NNS->getAsIdentifier());
3901
3902 case NestedNameSpecifier::Namespace:
3903 // A namespace is canonical; build a nested-name-specifier with
3904 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00003905 return NestedNameSpecifier::Create(*this, 0,
3906 NNS->getAsNamespace()->getOriginalNamespace());
3907
3908 case NestedNameSpecifier::NamespaceAlias:
3909 // A namespace is canonical; build a nested-name-specifier with
3910 // this namespace and no prefix.
3911 return NestedNameSpecifier::Create(*this, 0,
3912 NNS->getAsNamespaceAlias()->getNamespace()
3913 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00003914
3915 case NestedNameSpecifier::TypeSpec:
3916 case NestedNameSpecifier::TypeSpecWithTemplate: {
3917 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00003918
3919 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3920 // break it apart into its prefix and identifier, then reconsititute those
3921 // as the canonical nested-name-specifier. This is required to canonicalize
3922 // a dependent nested-name-specifier involving typedefs of dependent-name
3923 // types, e.g.,
3924 // typedef typename T::type T1;
3925 // typedef typename T1::type T2;
Eli Friedman16412ef2012-03-03 04:09:56 +00003926 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3927 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor264bf662010-11-04 00:09:33 +00003928 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor264bf662010-11-04 00:09:33 +00003929
Eli Friedman16412ef2012-03-03 04:09:56 +00003930 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3931 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3932 // first place?
John McCall3b657512011-01-19 10:06:00 +00003933 return NestedNameSpecifier::Create(*this, 0, false,
3934 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00003935 }
3936
3937 case NestedNameSpecifier::Global:
3938 // The global specifier is canonical and unique.
3939 return NNS;
3940 }
3941
David Blaikie7530c032012-01-17 06:56:22 +00003942 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregord57959a2009-03-27 23:10:48 +00003943}
3944
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003945
Jay Foad4ba2a172011-01-12 09:06:06 +00003946const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003947 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003948 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003949 // Handle the common positive case fast.
3950 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3951 return AT;
3952 }
Mike Stump1eb44332009-09-09 15:08:12 +00003953
John McCall0953e762009-09-24 19:53:00 +00003954 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003955 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003956 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003957
John McCall0953e762009-09-24 19:53:00 +00003958 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003959 // implements C99 6.7.3p8: "If the specification of an array type includes
3960 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00003961
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003962 // If we get here, we either have type qualifiers on the type, or we have
3963 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00003964 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003965
John McCall3b657512011-01-19 10:06:00 +00003966 SplitQualType split = T.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00003967 Qualifiers qs = split.Quals;
Mike Stump1eb44332009-09-09 15:08:12 +00003968
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003969 // If we have a simple case, just return now.
John McCall200fa532012-02-08 00:46:36 +00003970 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall3b657512011-01-19 10:06:00 +00003971 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003972 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003973
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003974 // Otherwise, we have an array and we have qualifiers on it. Push the
3975 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00003976 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003977
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003978 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3979 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3980 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003981 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003982 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3983 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3984 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003985 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00003986
Mike Stump1eb44332009-09-09 15:08:12 +00003987 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00003988 = dyn_cast<DependentSizedArrayType>(ATy))
3989 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00003990 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003991 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00003992 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003993 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003994 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00003995
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003996 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003997 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003998 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003999 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004000 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004001 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00004002}
4003
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004004QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004005 // C99 6.7.5.3p7:
4006 // A declaration of a parameter as "array of type" shall be
4007 // adjusted to "qualified pointer to type", where the type
4008 // qualifiers (if any) are those specified within the [ and ] of
4009 // the array type derivation.
4010 if (T->isArrayType())
4011 return getArrayDecayedType(T);
4012
4013 // C99 6.7.5.3p8:
4014 // A declaration of a parameter as "function returning type"
4015 // shall be adjusted to "pointer to function returning type", as
4016 // in 6.3.2.1.
4017 if (T->isFunctionType())
4018 return getPointerType(T);
4019
4020 return T;
4021}
4022
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004023QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004024 T = getVariableArrayDecayedType(T);
4025 T = getAdjustedParameterType(T);
4026 return T.getUnqualifiedType();
4027}
4028
Chris Lattnere6327742008-04-02 05:18:44 +00004029/// getArrayDecayedType - Return the properly qualified result of decaying the
4030/// specified array type to a pointer. This operation is non-trivial when
4031/// handling typedefs etc. The canonical type of "T" must be an array type,
4032/// this returns a pointer to a properly qualified element of the array.
4033///
4034/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00004035QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004036 // Get the element type with 'getAsArrayType' so that we don't lose any
4037 // typedefs in the element type of the array. This also handles propagation
4038 // of type qualifiers from the array type into the element type if present
4039 // (C99 6.7.3p8).
4040 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4041 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00004042
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004043 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00004044
4045 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00004046 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00004047}
4048
John McCall3b657512011-01-19 10:06:00 +00004049QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4050 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00004051}
4052
John McCall3b657512011-01-19 10:06:00 +00004053QualType ASTContext::getBaseElementType(QualType type) const {
4054 Qualifiers qs;
4055 while (true) {
4056 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004057 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall3b657512011-01-19 10:06:00 +00004058 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00004059
John McCall3b657512011-01-19 10:06:00 +00004060 type = array->getElementType();
John McCall200fa532012-02-08 00:46:36 +00004061 qs.addConsistentQualifiers(split.Quals);
John McCall3b657512011-01-19 10:06:00 +00004062 }
Mike Stump1eb44332009-09-09 15:08:12 +00004063
John McCall3b657512011-01-19 10:06:00 +00004064 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00004065}
4066
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004067/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00004068uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004069ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4070 uint64_t ElementCount = 1;
4071 do {
4072 ElementCount *= CA->getSize().getZExtValue();
Richard Smithd5e83942012-12-06 03:04:50 +00004073 CA = dyn_cast_or_null<ConstantArrayType>(
4074 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004075 } while (CA);
4076 return ElementCount;
4077}
4078
Reid Spencer5f016e22007-07-11 17:01:13 +00004079/// getFloatingRank - Return a relative rank for floating point types.
4080/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00004081static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00004082 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00004083 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00004084
John McCall183700f2009-09-21 23:43:11 +00004085 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4086 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004087 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00004088 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00004089 case BuiltinType::Float: return FloatRank;
4090 case BuiltinType::Double: return DoubleRank;
4091 case BuiltinType::LongDouble: return LongDoubleRank;
4092 }
4093}
4094
Mike Stump1eb44332009-09-09 15:08:12 +00004095/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4096/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00004097/// 'typeDomain' is a real floating point or complex type.
4098/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00004099QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4100 QualType Domain) const {
4101 FloatingRank EltRank = getFloatingRank(Size);
4102 if (Domain->isComplexType()) {
4103 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00004104 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Narofff1448a02007-08-27 01:27:54 +00004105 case FloatRank: return FloatComplexTy;
4106 case DoubleRank: return DoubleComplexTy;
4107 case LongDoubleRank: return LongDoubleComplexTy;
4108 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004109 }
Chris Lattner1361b112008-04-06 23:58:54 +00004110
4111 assert(Domain->isRealFloatingType() && "Unknown domain!");
4112 switch (EltRank) {
Joey Gouly19dbb202013-01-23 11:56:20 +00004113 case HalfRank: return HalfTy;
Chris Lattner1361b112008-04-06 23:58:54 +00004114 case FloatRank: return FloatTy;
4115 case DoubleRank: return DoubleTy;
4116 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00004117 }
David Blaikie561d3ab2012-01-17 02:30:50 +00004118 llvm_unreachable("getFloatingRank(): illegal value for rank");
Reid Spencer5f016e22007-07-11 17:01:13 +00004119}
4120
Chris Lattner7cfeb082008-04-06 23:55:33 +00004121/// getFloatingTypeOrder - Compare the rank of the two specified floating
4122/// point types, ignoring the domain of the type (i.e. 'double' ==
4123/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004124/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004125int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00004126 FloatingRank LHSR = getFloatingRank(LHS);
4127 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004128
Chris Lattnera75cea32008-04-06 23:38:49 +00004129 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004130 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00004131 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004132 return 1;
4133 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004134}
4135
Chris Lattnerf52ab252008-04-06 22:59:24 +00004136/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4137/// routine will assert if passed a built-in type that isn't an integer or enum,
4138/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00004139unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00004140 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00004141
Chris Lattnerf52ab252008-04-06 22:59:24 +00004142 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004143 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00004144 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004145 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004146 case BuiltinType::Char_S:
4147 case BuiltinType::Char_U:
4148 case BuiltinType::SChar:
4149 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004150 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004151 case BuiltinType::Short:
4152 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004153 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004154 case BuiltinType::Int:
4155 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004156 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004157 case BuiltinType::Long:
4158 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004159 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004160 case BuiltinType::LongLong:
4161 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004162 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00004163 case BuiltinType::Int128:
4164 case BuiltinType::UInt128:
4165 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00004166 }
4167}
4168
Eli Friedman04e83572009-08-20 04:21:42 +00004169/// \brief Whether this is a promotable bitfield reference according
4170/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4171///
4172/// \returns the type this bit-field will promote to, or NULL if no
4173/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00004174QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00004175 if (E->isTypeDependent() || E->isValueDependent())
4176 return QualType();
4177
Eli Friedman04e83572009-08-20 04:21:42 +00004178 FieldDecl *Field = E->getBitField();
4179 if (!Field)
4180 return QualType();
4181
4182 QualType FT = Field->getType();
4183
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004184 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00004185 uint64_t IntSize = getTypeSize(IntTy);
4186 // GCC extension compatibility: if the bit-field size is less than or equal
4187 // to the size of int, it gets promoted no matter what its type is.
4188 // For instance, unsigned long bf : 4 gets promoted to signed int.
4189 if (BitWidth < IntSize)
4190 return IntTy;
4191
4192 if (BitWidth == IntSize)
4193 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4194
4195 // Types bigger than int are not subject to promotions, and therefore act
4196 // like the base type.
4197 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4198 // is ridiculous.
4199 return QualType();
4200}
4201
Eli Friedmana95d7572009-08-19 07:44:53 +00004202/// getPromotedIntegerType - Returns the type that Promotable will
4203/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4204/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00004205QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00004206 assert(!Promotable.isNull());
4207 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00004208 if (const EnumType *ET = Promotable->getAs<EnumType>())
4209 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00004210
4211 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4212 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4213 // (3.9.1) can be converted to a prvalue of the first of the following
4214 // types that can represent all the values of its underlying type:
4215 // int, unsigned int, long int, unsigned long int, long long int, or
4216 // unsigned long long int [...]
4217 // FIXME: Is there some better way to compute this?
4218 if (BT->getKind() == BuiltinType::WChar_S ||
4219 BT->getKind() == BuiltinType::WChar_U ||
4220 BT->getKind() == BuiltinType::Char16 ||
4221 BT->getKind() == BuiltinType::Char32) {
4222 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4223 uint64_t FromSize = getTypeSize(BT);
4224 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4225 LongLongTy, UnsignedLongLongTy };
4226 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4227 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4228 if (FromSize < ToSize ||
4229 (FromSize == ToSize &&
4230 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4231 return PromoteTypes[Idx];
4232 }
4233 llvm_unreachable("char type should fit into long long");
4234 }
4235 }
4236
4237 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00004238 if (Promotable->isSignedIntegerType())
4239 return IntTy;
Eli Friedman5b64e772012-11-15 01:21:59 +00004240 uint64_t PromotableSize = getIntWidth(Promotable);
4241 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedmana95d7572009-08-19 07:44:53 +00004242 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4243 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4244}
4245
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004246/// \brief Recurses in pointer/array types until it finds an objc retainable
4247/// type and returns its ownership.
4248Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4249 while (!T.isNull()) {
4250 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4251 return T.getObjCLifetime();
4252 if (T->isArrayType())
4253 T = getBaseElementType(T);
4254 else if (const PointerType *PT = T->getAs<PointerType>())
4255 T = PT->getPointeeType();
4256 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00004257 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004258 else
4259 break;
4260 }
4261
4262 return Qualifiers::OCL_None;
4263}
4264
Mike Stump1eb44332009-09-09 15:08:12 +00004265/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00004266/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004267/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004268int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00004269 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4270 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00004271 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004272
Chris Lattnerf52ab252008-04-06 22:59:24 +00004273 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4274 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00004275
Chris Lattner7cfeb082008-04-06 23:55:33 +00004276 unsigned LHSRank = getIntegerRank(LHSC);
4277 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00004278
Chris Lattner7cfeb082008-04-06 23:55:33 +00004279 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4280 if (LHSRank == RHSRank) return 0;
4281 return LHSRank > RHSRank ? 1 : -1;
4282 }
Mike Stump1eb44332009-09-09 15:08:12 +00004283
Chris Lattner7cfeb082008-04-06 23:55:33 +00004284 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4285 if (LHSUnsigned) {
4286 // If the unsigned [LHS] type is larger, return it.
4287 if (LHSRank >= RHSRank)
4288 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004289
Chris Lattner7cfeb082008-04-06 23:55:33 +00004290 // If the signed type can represent all values of the unsigned type, it
4291 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004292 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004293 return -1;
4294 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00004295
Chris Lattner7cfeb082008-04-06 23:55:33 +00004296 // If the unsigned [RHS] type is larger, return it.
4297 if (RHSRank >= LHSRank)
4298 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00004299
Chris Lattner7cfeb082008-04-06 23:55:33 +00004300 // If the signed type can represent all values of the unsigned type, it
4301 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004302 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004303 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004304}
Anders Carlsson71993dd2007-08-17 05:31:46 +00004305
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004306static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004307CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4308 DeclContext *DC, IdentifierInfo *Id) {
4309 SourceLocation Loc;
David Blaikie4e4d0842012-03-11 07:00:24 +00004310 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004311 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004312 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004313 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004314}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004315
Mike Stump1eb44332009-09-09 15:08:12 +00004316// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00004317QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00004318 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004319 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004320 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004321 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00004322 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004323
Anders Carlssonf06273f2007-11-19 00:25:30 +00004324 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00004325
Anders Carlsson71993dd2007-08-17 05:31:46 +00004326 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00004327 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00004328 // int flags;
4329 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00004330 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00004331 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00004332 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00004333 FieldTypes[3] = LongTy;
4334
Anders Carlsson71993dd2007-08-17 05:31:46 +00004335 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00004336 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00004337 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004338 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00004339 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00004340 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00004341 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004342 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004343 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004344 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004345 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00004346 }
4347
Douglas Gregor838db382010-02-11 01:19:42 +00004348 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00004349 }
Mike Stump1eb44332009-09-09 15:08:12 +00004350
Anders Carlsson71993dd2007-08-17 05:31:46 +00004351 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00004352}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004353
Fariborz Jahanianf7992132013-01-04 18:45:40 +00004354QualType ASTContext::getObjCSuperType() const {
4355 if (ObjCSuperType.isNull()) {
4356 RecordDecl *ObjCSuperTypeDecl =
4357 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4358 TUDecl->addDecl(ObjCSuperTypeDecl);
4359 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4360 }
4361 return ObjCSuperType;
4362}
4363
Douglas Gregor319ac892009-04-23 22:29:11 +00004364void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004365 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00004366 assert(Rec && "Invalid CFConstantStringType");
4367 CFConstantStringTypeDecl = Rec->getDecl();
4368}
4369
Jay Foad4ba2a172011-01-12 09:06:06 +00004370QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00004371 if (BlockDescriptorType)
4372 return getTagDeclType(BlockDescriptorType);
4373
4374 RecordDecl *T;
4375 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004376 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004377 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00004378 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004379
4380 QualType FieldTypes[] = {
4381 UnsignedLongTy,
4382 UnsignedLongTy,
4383 };
4384
4385 const char *FieldNames[] = {
4386 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00004387 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00004388 };
4389
4390 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004391 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00004392 SourceLocation(),
4393 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004394 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00004395 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004396 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004397 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004398 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00004399 T->addDecl(Field);
4400 }
4401
Douglas Gregor838db382010-02-11 01:19:42 +00004402 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004403
4404 BlockDescriptorType = T;
4405
4406 return getTagDeclType(BlockDescriptorType);
4407}
4408
Jay Foad4ba2a172011-01-12 09:06:06 +00004409QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00004410 if (BlockDescriptorExtendedType)
4411 return getTagDeclType(BlockDescriptorExtendedType);
4412
4413 RecordDecl *T;
4414 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004415 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004416 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00004417 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004418
4419 QualType FieldTypes[] = {
4420 UnsignedLongTy,
4421 UnsignedLongTy,
4422 getPointerType(VoidPtrTy),
4423 getPointerType(VoidPtrTy)
4424 };
4425
4426 const char *FieldNames[] = {
4427 "reserved",
4428 "Size",
4429 "CopyFuncPtr",
4430 "DestroyFuncPtr"
4431 };
4432
4433 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004434 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00004435 SourceLocation(),
4436 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004437 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00004438 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004439 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004440 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004441 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00004442 T->addDecl(Field);
4443 }
4444
Douglas Gregor838db382010-02-11 01:19:42 +00004445 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004446
4447 BlockDescriptorExtendedType = T;
4448
4449 return getTagDeclType(BlockDescriptorExtendedType);
4450}
4451
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004452/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4453/// requires copy/dispose. Note that this must match the logic
4454/// in buildByrefHelpers.
4455bool ASTContext::BlockRequiresCopying(QualType Ty,
4456 const VarDecl *D) {
4457 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4458 const Expr *copyExpr = getBlockVarCopyInits(D);
4459 if (!copyExpr && record->hasTrivialDestructor()) return false;
4460
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004461 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00004462 }
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004463
4464 if (!Ty->isObjCRetainableType()) return false;
4465
4466 Qualifiers qs = Ty.getQualifiers();
4467
4468 // If we have lifetime, that dominates.
4469 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4470 assert(getLangOpts().ObjCAutoRefCount);
4471
4472 switch (lifetime) {
4473 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4474
4475 // These are just bits as far as the runtime is concerned.
4476 case Qualifiers::OCL_ExplicitNone:
4477 case Qualifiers::OCL_Autoreleasing:
4478 return false;
4479
4480 // Tell the runtime that this is ARC __weak, called by the
4481 // byref routines.
4482 case Qualifiers::OCL_Weak:
4483 // ARC __strong __block variables need to be retained.
4484 case Qualifiers::OCL_Strong:
4485 return true;
4486 }
4487 llvm_unreachable("fell out of lifetime switch!");
4488 }
4489 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4490 Ty->isObjCObjectPointerType());
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004491}
4492
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004493bool ASTContext::getByrefLifetime(QualType Ty,
4494 Qualifiers::ObjCLifetime &LifeTime,
4495 bool &HasByrefExtendedLayout) const {
4496
4497 if (!getLangOpts().ObjC1 ||
4498 getLangOpts().getGC() != LangOptions::NonGC)
4499 return false;
4500
4501 HasByrefExtendedLayout = false;
Fariborz Jahanian34db84f2012-12-11 19:58:01 +00004502 if (Ty->isRecordType()) {
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004503 HasByrefExtendedLayout = true;
4504 LifeTime = Qualifiers::OCL_None;
4505 }
4506 else if (getLangOpts().ObjCAutoRefCount)
4507 LifeTime = Ty.getObjCLifetime();
4508 // MRR.
4509 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4510 LifeTime = Qualifiers::OCL_ExplicitNone;
4511 else
4512 LifeTime = Qualifiers::OCL_None;
4513 return true;
4514}
4515
Douglas Gregore97179c2011-09-08 01:46:34 +00004516TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4517 if (!ObjCInstanceTypeDecl)
4518 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4519 getTranslationUnitDecl(),
4520 SourceLocation(),
4521 SourceLocation(),
4522 &Idents.get("instancetype"),
4523 getTrivialTypeSourceInfo(getObjCIdType()));
4524 return ObjCInstanceTypeDecl;
4525}
4526
Anders Carlssone8c49532007-10-29 06:33:42 +00004527// This returns true if a type has been typedefed to BOOL:
4528// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00004529static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00004530 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00004531 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4532 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00004533
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004534 return false;
4535}
4536
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004537/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004538/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00004539CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00004540 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4541 return CharUnits::Zero();
4542
Ken Dyck199c3d62010-01-11 17:06:35 +00004543 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004544
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004545 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004546 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004547 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004548 // Treat arrays as pointers, since that's how they're passed in.
4549 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004550 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004551 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004552}
4553
4554static inline
4555std::string charUnitsToString(const CharUnits &CU) {
4556 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004557}
4558
John McCall6b5a61b2011-02-07 10:33:21 +00004559/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004560/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004561std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4562 std::string S;
4563
David Chisnall5e530af2009-11-17 19:33:30 +00004564 const BlockDecl *Decl = Expr->getBlockDecl();
4565 QualType BlockTy =
4566 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4567 // Encode result type.
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004568 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004569 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4570 BlockTy->getAs<FunctionType>()->getResultType(),
4571 S, true /*Extended*/);
4572 else
4573 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4574 S);
David Chisnall5e530af2009-11-17 19:33:30 +00004575 // Compute size of all parameters.
4576 // Start with computing size of a pointer in number of bytes.
4577 // FIXME: There might(should) be a better way of doing this computation!
4578 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004579 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4580 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004581 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004582 E = Decl->param_end(); PI != E; ++PI) {
4583 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004584 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahanian075a5432012-06-30 00:48:59 +00004585 if (sz.isZero())
4586 continue;
Ken Dyck199c3d62010-01-11 17:06:35 +00004587 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004588 ParmOffset += sz;
4589 }
4590 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004591 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004592 // Block pointer and offset.
4593 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004594
4595 // Argument types.
4596 ParmOffset = PtrSize;
4597 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4598 Decl->param_end(); PI != E; ++PI) {
4599 ParmVarDecl *PVDecl = *PI;
4600 QualType PType = PVDecl->getOriginalType();
4601 if (const ArrayType *AT =
4602 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4603 // Use array's original type only if it has known number of
4604 // elements.
4605 if (!isa<ConstantArrayType>(AT))
4606 PType = PVDecl->getType();
4607 } else if (PType->isFunctionType())
4608 PType = PVDecl->getType();
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004609 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004610 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4611 S, true /*Extended*/);
4612 else
4613 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004614 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004615 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004616 }
John McCall6b5a61b2011-02-07 10:33:21 +00004617
4618 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004619}
4620
Douglas Gregorf968d832011-05-27 01:19:52 +00004621bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004622 std::string& S) {
4623 // Encode result type.
4624 getObjCEncodingForType(Decl->getResultType(), S);
4625 CharUnits ParmOffset;
4626 // Compute size of all parameters.
4627 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4628 E = Decl->param_end(); PI != E; ++PI) {
4629 QualType PType = (*PI)->getType();
4630 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004631 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004632 continue;
4633
David Chisnall5389f482010-12-30 14:05:53 +00004634 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004635 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004636 ParmOffset += sz;
4637 }
4638 S += charUnitsToString(ParmOffset);
4639 ParmOffset = CharUnits::Zero();
4640
4641 // Argument types.
4642 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4643 E = Decl->param_end(); PI != E; ++PI) {
4644 ParmVarDecl *PVDecl = *PI;
4645 QualType PType = PVDecl->getOriginalType();
4646 if (const ArrayType *AT =
4647 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4648 // Use array's original type only if it has known number of
4649 // elements.
4650 if (!isa<ConstantArrayType>(AT))
4651 PType = PVDecl->getType();
4652 } else if (PType->isFunctionType())
4653 PType = PVDecl->getType();
4654 getObjCEncodingForType(PType, S);
4655 S += charUnitsToString(ParmOffset);
4656 ParmOffset += getObjCEncodingTypeSize(PType);
4657 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004658
4659 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004660}
4661
Bob Wilsondc8dab62011-11-30 01:57:58 +00004662/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4663/// method parameter or return type. If Extended, include class names and
4664/// block object types.
4665void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4666 QualType T, std::string& S,
4667 bool Extended) const {
4668 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4669 getObjCEncodingForTypeQualifier(QT, S);
4670 // Encode parameter type.
4671 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4672 true /*OutermostType*/,
4673 false /*EncodingProperty*/,
4674 false /*StructField*/,
4675 Extended /*EncodeBlockParameters*/,
4676 Extended /*EncodeClassNames*/);
4677}
4678
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004679/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004680/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004681bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004682 std::string& S,
4683 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004684 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004685 // Encode return type.
4686 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4687 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004688 // Compute size of all parameters.
4689 // Start with computing size of a pointer in number of bytes.
4690 // FIXME: There might(should) be a better way of doing this computation!
4691 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004692 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004693 // The first two arguments (self and _cmd) are pointers; account for
4694 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004695 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004696 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004697 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004698 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004699 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004700 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004701 continue;
4702
Ken Dyck199c3d62010-01-11 17:06:35 +00004703 assert (sz.isPositive() &&
4704 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004705 ParmOffset += sz;
4706 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004707 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004708 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004709 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004710
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004711 // Argument types.
4712 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004713 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004714 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004715 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004716 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004717 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004718 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4719 // Use array's original type only if it has known number of
4720 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004721 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004722 PType = PVDecl->getType();
4723 } else if (PType->isFunctionType())
4724 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004725 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4726 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004727 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004728 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004729 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004730
4731 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004732}
4733
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004734/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004735/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004736/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4737/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004738/// Property attributes are stored as a comma-delimited C string. The simple
4739/// attributes readonly and bycopy are encoded as single characters. The
4740/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4741/// encoded as single characters, followed by an identifier. Property types
4742/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004743/// these attributes are defined by the following enumeration:
4744/// @code
4745/// enum PropertyAttributes {
4746/// kPropertyReadOnly = 'R', // property is read-only.
4747/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4748/// kPropertyByref = '&', // property is a reference to the value last assigned
4749/// kPropertyDynamic = 'D', // property is dynamic
4750/// kPropertyGetter = 'G', // followed by getter selector name
4751/// kPropertySetter = 'S', // followed by setter selector name
4752/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson0d4cb852012-03-22 17:48:02 +00004753/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004754/// kPropertyWeak = 'W' // 'weak' property
4755/// kPropertyStrong = 'P' // property GC'able
4756/// kPropertyNonAtomic = 'N' // property non-atomic
4757/// };
4758/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004759void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004760 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004761 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004762 // Collect information from the property implementation decl(s).
4763 bool Dynamic = false;
4764 ObjCPropertyImplDecl *SynthesizePID = 0;
4765
4766 // FIXME: Duplicated code due to poor abstraction.
4767 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004768 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004769 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4770 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004771 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004772 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004773 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004774 if (PID->getPropertyDecl() == PD) {
4775 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4776 Dynamic = true;
4777 } else {
4778 SynthesizePID = PID;
4779 }
4780 }
4781 }
4782 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004783 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004784 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004785 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004786 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004787 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004788 if (PID->getPropertyDecl() == PD) {
4789 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4790 Dynamic = true;
4791 } else {
4792 SynthesizePID = PID;
4793 }
4794 }
Mike Stump1eb44332009-09-09 15:08:12 +00004795 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004796 }
4797 }
4798
4799 // FIXME: This is not very efficient.
4800 S = "T";
4801
4802 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004803 // GCC has some special rules regarding encoding of properties which
4804 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004805 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004806 true /* outermost type */,
4807 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004808
4809 if (PD->isReadOnly()) {
4810 S += ",R";
4811 } else {
4812 switch (PD->getSetterKind()) {
4813 case ObjCPropertyDecl::Assign: break;
4814 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004815 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004816 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004817 }
4818 }
4819
4820 // It really isn't clear at all what this means, since properties
4821 // are "dynamic by default".
4822 if (Dynamic)
4823 S += ",D";
4824
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004825 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4826 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004827
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004828 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4829 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004830 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004831 }
4832
4833 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4834 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004835 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004836 }
4837
4838 if (SynthesizePID) {
4839 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4840 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004841 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004842 }
4843
4844 // FIXME: OBJCGC: weak & strong
4845}
4846
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004847/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004848/// Another legacy compatibility encoding: 32-bit longs are encoded as
4849/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004850/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4851///
4852void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004853 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004854 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004855 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004856 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004857 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004858 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004859 PointeeTy = IntTy;
4860 }
4861 }
4862}
4863
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004864void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00004865 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004866 // We follow the behavior of gcc, expanding structures which are
4867 // directly pointed to, and expanding embedded structures. Note that
4868 // these rules are sufficient to prevent recursive encoding of the
4869 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00004870 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00004871 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004872}
4873
John McCall3624e9e2012-12-20 02:45:14 +00004874static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
4875 BuiltinType::Kind kind) {
4876 switch (kind) {
David Chisnall64fd7e82010-06-04 01:10:52 +00004877 case BuiltinType::Void: return 'v';
4878 case BuiltinType::Bool: return 'B';
4879 case BuiltinType::Char_U:
4880 case BuiltinType::UChar: return 'C';
John McCall3624e9e2012-12-20 02:45:14 +00004881 case BuiltinType::Char16:
David Chisnall64fd7e82010-06-04 01:10:52 +00004882 case BuiltinType::UShort: return 'S';
John McCall3624e9e2012-12-20 02:45:14 +00004883 case BuiltinType::Char32:
David Chisnall64fd7e82010-06-04 01:10:52 +00004884 case BuiltinType::UInt: return 'I';
4885 case BuiltinType::ULong:
John McCall3624e9e2012-12-20 02:45:14 +00004886 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004887 case BuiltinType::UInt128: return 'T';
4888 case BuiltinType::ULongLong: return 'Q';
4889 case BuiltinType::Char_S:
4890 case BuiltinType::SChar: return 'c';
4891 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00004892 case BuiltinType::WChar_S:
4893 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00004894 case BuiltinType::Int: return 'i';
4895 case BuiltinType::Long:
John McCall3624e9e2012-12-20 02:45:14 +00004896 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004897 case BuiltinType::LongLong: return 'q';
4898 case BuiltinType::Int128: return 't';
4899 case BuiltinType::Float: return 'f';
4900 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00004901 case BuiltinType::LongDouble: return 'D';
John McCall3624e9e2012-12-20 02:45:14 +00004902 case BuiltinType::NullPtr: return '*'; // like char*
4903
4904 case BuiltinType::Half:
4905 // FIXME: potentially need @encodes for these!
4906 return ' ';
4907
4908 case BuiltinType::ObjCId:
4909 case BuiltinType::ObjCClass:
4910 case BuiltinType::ObjCSel:
4911 llvm_unreachable("@encoding ObjC primitive type");
4912
4913 // OpenCL and placeholder types don't need @encodings.
4914 case BuiltinType::OCLImage1d:
4915 case BuiltinType::OCLImage1dArray:
4916 case BuiltinType::OCLImage1dBuffer:
4917 case BuiltinType::OCLImage2d:
4918 case BuiltinType::OCLImage2dArray:
4919 case BuiltinType::OCLImage3d:
Guy Benyeie6b9d802013-01-20 12:31:11 +00004920 case BuiltinType::OCLEvent:
John McCall3624e9e2012-12-20 02:45:14 +00004921 case BuiltinType::Dependent:
4922#define BUILTIN_TYPE(KIND, ID)
4923#define PLACEHOLDER_TYPE(KIND, ID) \
4924 case BuiltinType::KIND:
4925#include "clang/AST/BuiltinTypes.def"
4926 llvm_unreachable("invalid builtin type for @encode");
David Chisnall64fd7e82010-06-04 01:10:52 +00004927 }
David Blaikie719e53f2013-01-09 17:48:41 +00004928 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnall64fd7e82010-06-04 01:10:52 +00004929}
4930
Douglas Gregor5471bc82011-09-08 17:18:35 +00004931static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4932 EnumDecl *Enum = ET->getDecl();
4933
4934 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4935 if (!Enum->isFixed())
4936 return 'i';
4937
4938 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall3624e9e2012-12-20 02:45:14 +00004939 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
4940 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor5471bc82011-09-08 17:18:35 +00004941}
4942
Jay Foad4ba2a172011-01-12 09:06:06 +00004943static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00004944 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004945 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004946 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00004947 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4948 // The GNU runtime requires more information; bitfields are encoded as b,
4949 // then the offset (in bits) of the first element, then the type of the
4950 // bitfield, then the size in bits. For example, in this structure:
4951 //
4952 // struct
4953 // {
4954 // int integer;
4955 // int flags:2;
4956 // };
4957 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4958 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4959 // information is not especially sensible, but we're stuck with it for
4960 // compatibility with GCC, although providing it breaks anything that
4961 // actually uses runtime introspection and wants to work on both runtimes...
John McCall260611a2012-06-20 06:18:46 +00004962 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnall64fd7e82010-06-04 01:10:52 +00004963 const RecordDecl *RD = FD->getParent();
4964 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00004965 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00004966 if (const EnumType *ET = T->getAs<EnumType>())
4967 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall3624e9e2012-12-20 02:45:14 +00004968 else {
4969 const BuiltinType *BT = T->castAs<BuiltinType>();
4970 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
4971 }
David Chisnall64fd7e82010-06-04 01:10:52 +00004972 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004973 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004974}
4975
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004976// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004977void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4978 bool ExpandPointedToStructures,
4979 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004980 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004981 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004982 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004983 bool StructField,
4984 bool EncodeBlockParameters,
4985 bool EncodeClassNames) const {
John McCall3624e9e2012-12-20 02:45:14 +00004986 CanQualType CT = getCanonicalType(T);
4987 switch (CT->getTypeClass()) {
4988 case Type::Builtin:
4989 case Type::Enum:
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004990 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004991 return EncodeBitField(this, S, T, FD);
John McCall3624e9e2012-12-20 02:45:14 +00004992 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
4993 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
4994 else
4995 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004996 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004997
John McCall3624e9e2012-12-20 02:45:14 +00004998 case Type::Complex: {
4999 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005000 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00005001 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005002 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005003 return;
5004 }
John McCall3624e9e2012-12-20 02:45:14 +00005005
5006 case Type::Atomic: {
5007 const AtomicType *AT = T->castAs<AtomicType>();
5008 S += 'A';
5009 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5010 false, false);
5011 return;
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00005012 }
John McCall3624e9e2012-12-20 02:45:14 +00005013
5014 // encoding for pointer or reference types.
5015 case Type::Pointer:
5016 case Type::LValueReference:
5017 case Type::RValueReference: {
5018 QualType PointeeTy;
5019 if (isa<PointerType>(CT)) {
5020 const PointerType *PT = T->castAs<PointerType>();
5021 if (PT->isObjCSelType()) {
5022 S += ':';
5023 return;
5024 }
5025 PointeeTy = PT->getPointeeType();
5026 } else {
5027 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5028 }
5029
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005030 bool isReadOnly = false;
5031 // For historical/compatibility reasons, the read-only qualifier of the
5032 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5033 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00005034 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00005035 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005036 if (OutermostType && T.isConstQualified()) {
5037 isReadOnly = true;
5038 S += 'r';
5039 }
Mike Stump9fdbab32009-07-31 02:02:20 +00005040 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005041 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00005042 while (P->getAs<PointerType>())
5043 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005044 if (P.isConstQualified()) {
5045 isReadOnly = true;
5046 S += 'r';
5047 }
5048 }
5049 if (isReadOnly) {
5050 // Another legacy compatibility encoding. Some ObjC qualifier and type
5051 // combinations need to be rearranged.
5052 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00005053 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00005054 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005055 }
Mike Stump1eb44332009-09-09 15:08:12 +00005056
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005057 if (PointeeTy->isCharType()) {
5058 // char pointer types should be encoded as '*' unless it is a
5059 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00005060 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005061 S += '*';
5062 return;
5063 }
Ted Kremenek6217b802009-07-29 21:53:49 +00005064 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00005065 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5066 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5067 S += '#';
5068 return;
5069 }
5070 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5071 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5072 S += '@';
5073 return;
5074 }
5075 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005076 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005077 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005078 getLegacyIntegralTypeEncoding(PointeeTy);
5079
Mike Stump1eb44332009-09-09 15:08:12 +00005080 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005081 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005082 return;
5083 }
John McCall3624e9e2012-12-20 02:45:14 +00005084
5085 case Type::ConstantArray:
5086 case Type::IncompleteArray:
5087 case Type::VariableArray: {
5088 const ArrayType *AT = cast<ArrayType>(CT);
5089
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005090 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00005091 // Incomplete arrays are encoded as a pointer to the array element.
5092 S += '^';
5093
Mike Stump1eb44332009-09-09 15:08:12 +00005094 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005095 false, ExpandStructures, FD);
5096 } else {
5097 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00005098
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005099 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
5100 if (getTypeSize(CAT->getElementType()) == 0)
5101 S += '0';
5102 else
5103 S += llvm::utostr(CAT->getSize().getZExtValue());
5104 } else {
Anders Carlsson559a8332009-02-22 01:38:57 +00005105 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005106 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5107 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00005108 S += '0';
5109 }
Mike Stump1eb44332009-09-09 15:08:12 +00005110
5111 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005112 false, ExpandStructures, FD);
5113 S += ']';
5114 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005115 return;
5116 }
Mike Stump1eb44332009-09-09 15:08:12 +00005117
John McCall3624e9e2012-12-20 02:45:14 +00005118 case Type::FunctionNoProto:
5119 case Type::FunctionProto:
Anders Carlssonc0a87b72007-10-30 00:06:20 +00005120 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005121 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005122
John McCall3624e9e2012-12-20 02:45:14 +00005123 case Type::Record: {
5124 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005125 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005126 // Anonymous structures print as '?'
5127 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5128 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005129 if (ClassTemplateSpecializationDecl *Spec
5130 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5131 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
5132 std::string TemplateArgsStr
5133 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00005134 TemplateArgs.data(),
5135 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00005136 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005137
5138 S += TemplateArgsStr;
5139 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005140 } else {
5141 S += '?';
5142 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00005143 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005144 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005145 if (!RDecl->isUnion()) {
5146 getObjCEncodingForStructureImpl(RDecl, S, FD);
5147 } else {
5148 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5149 FieldEnd = RDecl->field_end();
5150 Field != FieldEnd; ++Field) {
5151 if (FD) {
5152 S += '"';
5153 S += Field->getNameAsString();
5154 S += '"';
5155 }
Mike Stump1eb44332009-09-09 15:08:12 +00005156
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005157 // Special case bit-fields.
5158 if (Field->isBitField()) {
5159 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie581deb32012-06-06 20:45:41 +00005160 *Field);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005161 } else {
5162 QualType qt = Field->getType();
5163 getLegacyIntegralTypeEncoding(qt);
5164 getObjCEncodingForTypeImpl(qt, S, false, true,
5165 FD, /*OutermostType*/false,
5166 /*EncodingProperty*/false,
5167 /*StructField*/true);
5168 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005169 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005170 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00005171 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005172 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005173 return;
5174 }
Mike Stump1eb44332009-09-09 15:08:12 +00005175
John McCall3624e9e2012-12-20 02:45:14 +00005176 case Type::BlockPointer: {
5177 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff21a98b12009-02-02 18:24:29 +00005178 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00005179 if (EncodeBlockParameters) {
John McCall3624e9e2012-12-20 02:45:14 +00005180 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilsondc8dab62011-11-30 01:57:58 +00005181
5182 S += '<';
5183 // Block return type
5184 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5185 ExpandPointedToStructures, ExpandStructures,
5186 FD,
5187 false /* OutermostType */,
5188 EncodingProperty,
5189 false /* StructField */,
5190 EncodeBlockParameters,
5191 EncodeClassNames);
5192 // Block self
5193 S += "@?";
5194 // Block parameters
5195 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5196 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5197 E = FPT->arg_type_end(); I && (I != E); ++I) {
5198 getObjCEncodingForTypeImpl(*I, S,
5199 ExpandPointedToStructures,
5200 ExpandStructures,
5201 FD,
5202 false /* OutermostType */,
5203 EncodingProperty,
5204 false /* StructField */,
5205 EncodeBlockParameters,
5206 EncodeClassNames);
5207 }
5208 }
5209 S += '>';
5210 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005211 return;
5212 }
Mike Stump1eb44332009-09-09 15:08:12 +00005213
John McCall3624e9e2012-12-20 02:45:14 +00005214 case Type::ObjCObject:
5215 case Type::ObjCInterface: {
5216 // Ignore protocol qualifiers when mangling at this level.
5217 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCallc12c5bb2010-05-15 11:32:37 +00005218
John McCall3624e9e2012-12-20 02:45:14 +00005219 // The assumption seems to be that this assert will succeed
5220 // because nested levels will have filtered out 'id' and 'Class'.
5221 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005222 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00005223 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005224 S += '{';
5225 const IdentifierInfo *II = OI->getIdentifier();
5226 S += II->getName();
5227 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00005228 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005229 DeepCollectObjCIvars(OI, true, Ivars);
5230 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00005231 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005232 if (Field->isBitField())
5233 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005234 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005235 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005236 }
5237 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005238 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005239 }
Mike Stump1eb44332009-09-09 15:08:12 +00005240
John McCall3624e9e2012-12-20 02:45:14 +00005241 case Type::ObjCObjectPointer: {
5242 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00005243 if (OPT->isObjCIdType()) {
5244 S += '@';
5245 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005246 }
Mike Stump1eb44332009-09-09 15:08:12 +00005247
Steve Naroff27d20a22009-10-28 22:03:49 +00005248 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5249 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5250 // Since this is a binary compatibility issue, need to consult with runtime
5251 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00005252 S += '#';
5253 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005254 }
Mike Stump1eb44332009-09-09 15:08:12 +00005255
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005256 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005257 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00005258 ExpandPointedToStructures,
5259 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00005260 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00005261 // Note that we do extended encoding of protocol qualifer list
5262 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00005263 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005264 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5265 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00005266 S += '<';
5267 S += (*I)->getNameAsString();
5268 S += '>';
5269 }
5270 S += '"';
5271 }
5272 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005273 }
Mike Stump1eb44332009-09-09 15:08:12 +00005274
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005275 QualType PointeeTy = OPT->getPointeeType();
5276 if (!EncodingProperty &&
5277 isa<TypedefType>(PointeeTy.getTypePtr())) {
5278 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00005279 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005280 // {...};
5281 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00005282 getObjCEncodingForTypeImpl(PointeeTy, S,
5283 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005284 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00005285 return;
5286 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005287
5288 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00005289 if (OPT->getInterfaceDecl() &&
5290 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005291 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00005292 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005293 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5294 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005295 S += '<';
5296 S += (*I)->getNameAsString();
5297 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00005298 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005299 S += '"';
5300 }
5301 return;
5302 }
Mike Stump1eb44332009-09-09 15:08:12 +00005303
John McCall532ec7b2010-05-17 23:56:34 +00005304 // gcc just blithely ignores member pointers.
John McCall3624e9e2012-12-20 02:45:14 +00005305 // FIXME: we shoul do better than that. 'M' is available.
5306 case Type::MemberPointer:
John McCall532ec7b2010-05-17 23:56:34 +00005307 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005308
John McCall3624e9e2012-12-20 02:45:14 +00005309 case Type::Vector:
5310 case Type::ExtVector:
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005311 // This matches gcc's encoding, even though technically it is
5312 // insufficient.
5313 // FIXME. We should do a better job than gcc.
5314 return;
John McCall3624e9e2012-12-20 02:45:14 +00005315
5316#define ABSTRACT_TYPE(KIND, BASE)
5317#define TYPE(KIND, BASE)
5318#define DEPENDENT_TYPE(KIND, BASE) \
5319 case Type::KIND:
5320#define NON_CANONICAL_TYPE(KIND, BASE) \
5321 case Type::KIND:
5322#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5323 case Type::KIND:
5324#include "clang/AST/TypeNodes.def"
5325 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005326 }
John McCall3624e9e2012-12-20 02:45:14 +00005327 llvm_unreachable("bad type kind!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005328}
5329
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005330void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5331 std::string &S,
5332 const FieldDecl *FD,
5333 bool includeVBases) const {
5334 assert(RDecl && "Expected non-null RecordDecl");
5335 assert(!RDecl->isUnion() && "Should not be called for unions");
5336 if (!RDecl->getDefinition())
5337 return;
5338
5339 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5340 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5341 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5342
5343 if (CXXRec) {
5344 for (CXXRecordDecl::base_class_iterator
5345 BI = CXXRec->bases_begin(),
5346 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5347 if (!BI->isVirtual()) {
5348 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005349 if (base->isEmpty())
5350 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005351 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005352 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5353 std::make_pair(offs, base));
5354 }
5355 }
5356 }
5357
5358 unsigned i = 0;
5359 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5360 FieldEnd = RDecl->field_end();
5361 Field != FieldEnd; ++Field, ++i) {
5362 uint64_t offs = layout.getFieldOffset(i);
5363 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie581deb32012-06-06 20:45:41 +00005364 std::make_pair(offs, *Field));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005365 }
5366
5367 if (CXXRec && includeVBases) {
5368 for (CXXRecordDecl::base_class_iterator
5369 BI = CXXRec->vbases_begin(),
5370 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5371 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005372 if (base->isEmpty())
5373 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005374 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00005375 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5376 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5377 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005378 }
5379 }
5380
5381 CharUnits size;
5382 if (CXXRec) {
5383 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5384 } else {
5385 size = layout.getSize();
5386 }
5387
5388 uint64_t CurOffs = 0;
5389 std::multimap<uint64_t, NamedDecl *>::iterator
5390 CurLayObj = FieldOrBaseOffsets.begin();
5391
Douglas Gregor58db7a52012-04-27 22:30:01 +00005392 if (CXXRec && CXXRec->isDynamicClass() &&
5393 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005394 if (FD) {
5395 S += "\"_vptr$";
5396 std::string recname = CXXRec->getNameAsString();
5397 if (recname.empty()) recname = "?";
5398 S += recname;
5399 S += '"';
5400 }
5401 S += "^^?";
5402 CurOffs += getTypeSize(VoidPtrTy);
5403 }
5404
5405 if (!RDecl->hasFlexibleArrayMember()) {
5406 // Mark the end of the structure.
5407 uint64_t offs = toBits(size);
5408 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5409 std::make_pair(offs, (NamedDecl*)0));
5410 }
5411
5412 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5413 assert(CurOffs <= CurLayObj->first);
5414
5415 if (CurOffs < CurLayObj->first) {
5416 uint64_t padding = CurLayObj->first - CurOffs;
5417 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5418 // packing/alignment of members is different that normal, in which case
5419 // the encoding will be out-of-sync with the real layout.
5420 // If the runtime switches to just consider the size of types without
5421 // taking into account alignment, we could make padding explicit in the
5422 // encoding (e.g. using arrays of chars). The encoding strings would be
5423 // longer then though.
5424 CurOffs += padding;
5425 }
5426
5427 NamedDecl *dcl = CurLayObj->second;
5428 if (dcl == 0)
5429 break; // reached end of structure.
5430
5431 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5432 // We expand the bases without their virtual bases since those are going
5433 // in the initial structure. Note that this differs from gcc which
5434 // expands virtual bases each time one is encountered in the hierarchy,
5435 // making the encoding type bigger than it really is.
5436 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005437 assert(!base->isEmpty());
5438 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005439 } else {
5440 FieldDecl *field = cast<FieldDecl>(dcl);
5441 if (FD) {
5442 S += '"';
5443 S += field->getNameAsString();
5444 S += '"';
5445 }
5446
5447 if (field->isBitField()) {
5448 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005449 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005450 } else {
5451 QualType qt = field->getType();
5452 getLegacyIntegralTypeEncoding(qt);
5453 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5454 /*OutermostType*/false,
5455 /*EncodingProperty*/false,
5456 /*StructField*/true);
5457 CurOffs += getTypeSize(field->getType());
5458 }
5459 }
5460 }
5461}
5462
Mike Stump1eb44332009-09-09 15:08:12 +00005463void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00005464 std::string& S) const {
5465 if (QT & Decl::OBJC_TQ_In)
5466 S += 'n';
5467 if (QT & Decl::OBJC_TQ_Inout)
5468 S += 'N';
5469 if (QT & Decl::OBJC_TQ_Out)
5470 S += 'o';
5471 if (QT & Decl::OBJC_TQ_Bycopy)
5472 S += 'O';
5473 if (QT & Decl::OBJC_TQ_Byref)
5474 S += 'R';
5475 if (QT & Decl::OBJC_TQ_Oneway)
5476 S += 'V';
5477}
5478
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00005479TypedefDecl *ASTContext::getObjCIdDecl() const {
5480 if (!ObjCIdDecl) {
5481 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5482 T = getObjCObjectPointerType(T);
5483 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5484 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5485 getTranslationUnitDecl(),
5486 SourceLocation(), SourceLocation(),
5487 &Idents.get("id"), IdInfo);
5488 }
5489
5490 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00005491}
5492
Douglas Gregor7a27ea52011-08-12 06:17:30 +00005493TypedefDecl *ASTContext::getObjCSelDecl() const {
5494 if (!ObjCSelDecl) {
5495 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5496 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5497 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5498 getTranslationUnitDecl(),
5499 SourceLocation(), SourceLocation(),
5500 &Idents.get("SEL"), SelInfo);
5501 }
5502 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00005503}
5504
Douglas Gregor79d67262011-08-12 05:59:41 +00005505TypedefDecl *ASTContext::getObjCClassDecl() const {
5506 if (!ObjCClassDecl) {
5507 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5508 T = getObjCObjectPointerType(T);
5509 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5510 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5511 getTranslationUnitDecl(),
5512 SourceLocation(), SourceLocation(),
5513 &Idents.get("Class"), ClassInfo);
5514 }
5515
5516 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00005517}
5518
Douglas Gregora6ea10e2012-01-17 18:09:05 +00005519ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5520 if (!ObjCProtocolClassDecl) {
5521 ObjCProtocolClassDecl
5522 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5523 SourceLocation(),
5524 &Idents.get("Protocol"),
5525 /*PrevDecl=*/0,
5526 SourceLocation(), true);
5527 }
5528
5529 return ObjCProtocolClassDecl;
5530}
5531
Meador Ingec5613b22012-06-16 03:34:49 +00005532//===----------------------------------------------------------------------===//
5533// __builtin_va_list Construction Functions
5534//===----------------------------------------------------------------------===//
5535
5536static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5537 // typedef char* __builtin_va_list;
5538 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5539 TypeSourceInfo *TInfo
5540 = Context->getTrivialTypeSourceInfo(CharPtrType);
5541
5542 TypedefDecl *VaListTypeDecl
5543 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5544 Context->getTranslationUnitDecl(),
5545 SourceLocation(), SourceLocation(),
5546 &Context->Idents.get("__builtin_va_list"),
5547 TInfo);
5548 return VaListTypeDecl;
5549}
5550
5551static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5552 // typedef void* __builtin_va_list;
5553 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5554 TypeSourceInfo *TInfo
5555 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5556
5557 TypedefDecl *VaListTypeDecl
5558 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5559 Context->getTranslationUnitDecl(),
5560 SourceLocation(), SourceLocation(),
5561 &Context->Idents.get("__builtin_va_list"),
5562 TInfo);
5563 return VaListTypeDecl;
5564}
5565
5566static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5567 // typedef struct __va_list_tag {
5568 RecordDecl *VaListTagDecl;
5569
5570 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5571 Context->getTranslationUnitDecl(),
5572 &Context->Idents.get("__va_list_tag"));
5573 VaListTagDecl->startDefinition();
5574
5575 const size_t NumFields = 5;
5576 QualType FieldTypes[NumFields];
5577 const char *FieldNames[NumFields];
5578
5579 // unsigned char gpr;
5580 FieldTypes[0] = Context->UnsignedCharTy;
5581 FieldNames[0] = "gpr";
5582
5583 // unsigned char fpr;
5584 FieldTypes[1] = Context->UnsignedCharTy;
5585 FieldNames[1] = "fpr";
5586
5587 // unsigned short reserved;
5588 FieldTypes[2] = Context->UnsignedShortTy;
5589 FieldNames[2] = "reserved";
5590
5591 // void* overflow_arg_area;
5592 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5593 FieldNames[3] = "overflow_arg_area";
5594
5595 // void* reg_save_area;
5596 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5597 FieldNames[4] = "reg_save_area";
5598
5599 // Create fields
5600 for (unsigned i = 0; i < NumFields; ++i) {
5601 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5602 SourceLocation(),
5603 SourceLocation(),
5604 &Context->Idents.get(FieldNames[i]),
5605 FieldTypes[i], /*TInfo=*/0,
5606 /*BitWidth=*/0,
5607 /*Mutable=*/false,
5608 ICIS_NoInit);
5609 Field->setAccess(AS_public);
5610 VaListTagDecl->addDecl(Field);
5611 }
5612 VaListTagDecl->completeDefinition();
5613 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005614 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005615
5616 // } __va_list_tag;
5617 TypedefDecl *VaListTagTypedefDecl
5618 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5619 Context->getTranslationUnitDecl(),
5620 SourceLocation(), SourceLocation(),
5621 &Context->Idents.get("__va_list_tag"),
5622 Context->getTrivialTypeSourceInfo(VaListTagType));
5623 QualType VaListTagTypedefType =
5624 Context->getTypedefType(VaListTagTypedefDecl);
5625
5626 // typedef __va_list_tag __builtin_va_list[1];
5627 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5628 QualType VaListTagArrayType
5629 = Context->getConstantArrayType(VaListTagTypedefType,
5630 Size, ArrayType::Normal, 0);
5631 TypeSourceInfo *TInfo
5632 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5633 TypedefDecl *VaListTypedefDecl
5634 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5635 Context->getTranslationUnitDecl(),
5636 SourceLocation(), SourceLocation(),
5637 &Context->Idents.get("__builtin_va_list"),
5638 TInfo);
5639
5640 return VaListTypedefDecl;
5641}
5642
5643static TypedefDecl *
5644CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5645 // typedef struct __va_list_tag {
5646 RecordDecl *VaListTagDecl;
5647 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5648 Context->getTranslationUnitDecl(),
5649 &Context->Idents.get("__va_list_tag"));
5650 VaListTagDecl->startDefinition();
5651
5652 const size_t NumFields = 4;
5653 QualType FieldTypes[NumFields];
5654 const char *FieldNames[NumFields];
5655
5656 // unsigned gp_offset;
5657 FieldTypes[0] = Context->UnsignedIntTy;
5658 FieldNames[0] = "gp_offset";
5659
5660 // unsigned fp_offset;
5661 FieldTypes[1] = Context->UnsignedIntTy;
5662 FieldNames[1] = "fp_offset";
5663
5664 // void* overflow_arg_area;
5665 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5666 FieldNames[2] = "overflow_arg_area";
5667
5668 // void* reg_save_area;
5669 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5670 FieldNames[3] = "reg_save_area";
5671
5672 // Create fields
5673 for (unsigned i = 0; i < NumFields; ++i) {
5674 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5675 VaListTagDecl,
5676 SourceLocation(),
5677 SourceLocation(),
5678 &Context->Idents.get(FieldNames[i]),
5679 FieldTypes[i], /*TInfo=*/0,
5680 /*BitWidth=*/0,
5681 /*Mutable=*/false,
5682 ICIS_NoInit);
5683 Field->setAccess(AS_public);
5684 VaListTagDecl->addDecl(Field);
5685 }
5686 VaListTagDecl->completeDefinition();
5687 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005688 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005689
5690 // } __va_list_tag;
5691 TypedefDecl *VaListTagTypedefDecl
5692 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5693 Context->getTranslationUnitDecl(),
5694 SourceLocation(), SourceLocation(),
5695 &Context->Idents.get("__va_list_tag"),
5696 Context->getTrivialTypeSourceInfo(VaListTagType));
5697 QualType VaListTagTypedefType =
5698 Context->getTypedefType(VaListTagTypedefDecl);
5699
5700 // typedef __va_list_tag __builtin_va_list[1];
5701 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5702 QualType VaListTagArrayType
5703 = Context->getConstantArrayType(VaListTagTypedefType,
5704 Size, ArrayType::Normal,0);
5705 TypeSourceInfo *TInfo
5706 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5707 TypedefDecl *VaListTypedefDecl
5708 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5709 Context->getTranslationUnitDecl(),
5710 SourceLocation(), SourceLocation(),
5711 &Context->Idents.get("__builtin_va_list"),
5712 TInfo);
5713
5714 return VaListTypedefDecl;
5715}
5716
5717static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5718 // typedef int __builtin_va_list[4];
5719 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5720 QualType IntArrayType
5721 = Context->getConstantArrayType(Context->IntTy,
5722 Size, ArrayType::Normal, 0);
5723 TypedefDecl *VaListTypedefDecl
5724 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5725 Context->getTranslationUnitDecl(),
5726 SourceLocation(), SourceLocation(),
5727 &Context->Idents.get("__builtin_va_list"),
5728 Context->getTrivialTypeSourceInfo(IntArrayType));
5729
5730 return VaListTypedefDecl;
5731}
5732
Logan Chieneae5a8202012-10-10 06:56:20 +00005733static TypedefDecl *
5734CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5735 RecordDecl *VaListDecl;
5736 if (Context->getLangOpts().CPlusPlus) {
5737 // namespace std { struct __va_list {
5738 NamespaceDecl *NS;
5739 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5740 Context->getTranslationUnitDecl(),
5741 /*Inline*/false, SourceLocation(),
5742 SourceLocation(), &Context->Idents.get("std"),
5743 /*PrevDecl*/0);
5744
5745 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5746 Context->getTranslationUnitDecl(),
5747 SourceLocation(), SourceLocation(),
5748 &Context->Idents.get("__va_list"));
5749
5750 VaListDecl->setDeclContext(NS);
5751
5752 } else {
5753 // struct __va_list {
5754 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
5755 Context->getTranslationUnitDecl(),
5756 &Context->Idents.get("__va_list"));
5757 }
5758
5759 VaListDecl->startDefinition();
5760
5761 // void * __ap;
5762 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5763 VaListDecl,
5764 SourceLocation(),
5765 SourceLocation(),
5766 &Context->Idents.get("__ap"),
5767 Context->getPointerType(Context->VoidTy),
5768 /*TInfo=*/0,
5769 /*BitWidth=*/0,
5770 /*Mutable=*/false,
5771 ICIS_NoInit);
5772 Field->setAccess(AS_public);
5773 VaListDecl->addDecl(Field);
5774
5775 // };
5776 VaListDecl->completeDefinition();
5777
5778 // typedef struct __va_list __builtin_va_list;
5779 TypeSourceInfo *TInfo
5780 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
5781
5782 TypedefDecl *VaListTypeDecl
5783 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5784 Context->getTranslationUnitDecl(),
5785 SourceLocation(), SourceLocation(),
5786 &Context->Idents.get("__builtin_va_list"),
5787 TInfo);
5788
5789 return VaListTypeDecl;
5790}
5791
Meador Ingec5613b22012-06-16 03:34:49 +00005792static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5793 TargetInfo::BuiltinVaListKind Kind) {
5794 switch (Kind) {
5795 case TargetInfo::CharPtrBuiltinVaList:
5796 return CreateCharPtrBuiltinVaListDecl(Context);
5797 case TargetInfo::VoidPtrBuiltinVaList:
5798 return CreateVoidPtrBuiltinVaListDecl(Context);
5799 case TargetInfo::PowerABIBuiltinVaList:
5800 return CreatePowerABIBuiltinVaListDecl(Context);
5801 case TargetInfo::X86_64ABIBuiltinVaList:
5802 return CreateX86_64ABIBuiltinVaListDecl(Context);
5803 case TargetInfo::PNaClABIBuiltinVaList:
5804 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chieneae5a8202012-10-10 06:56:20 +00005805 case TargetInfo::AAPCSABIBuiltinVaList:
5806 return CreateAAPCSABIBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00005807 }
5808
5809 llvm_unreachable("Unhandled __builtin_va_list type kind");
5810}
5811
5812TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5813 if (!BuiltinVaListDecl)
5814 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5815
5816 return BuiltinVaListDecl;
5817}
5818
Meador Ingefb40e3f2012-07-01 15:57:25 +00005819QualType ASTContext::getVaListTagType() const {
5820 // Force the creation of VaListTagTy by building the __builtin_va_list
5821 // declaration.
5822 if (VaListTagTy.isNull())
5823 (void) getBuiltinVaListDecl();
5824
5825 return VaListTagTy;
5826}
5827
Ted Kremeneka526c5c2008-01-07 19:49:32 +00005828void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00005829 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00005830 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00005831
Ted Kremeneka526c5c2008-01-07 19:49:32 +00005832 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00005833}
5834
John McCall0bd6feb2009-12-02 08:04:21 +00005835/// \brief Retrieve the template name that corresponds to a non-empty
5836/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00005837TemplateName
5838ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5839 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00005840 unsigned size = End - Begin;
5841 assert(size > 1 && "set is not overloaded!");
5842
5843 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5844 size * sizeof(FunctionTemplateDecl*));
5845 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5846
5847 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00005848 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00005849 NamedDecl *D = *I;
5850 assert(isa<FunctionTemplateDecl>(D) ||
5851 (isa<UsingShadowDecl>(D) &&
5852 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5853 *Storage++ = D;
5854 }
5855
5856 return TemplateName(OT);
5857}
5858
Douglas Gregor7532dc62009-03-30 22:58:21 +00005859/// \brief Retrieve the template name that represents a qualified
5860/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00005861TemplateName
5862ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5863 bool TemplateKeyword,
5864 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00005865 assert(NNS && "Missing nested-name-specifier in qualified template name");
5866
Douglas Gregor789b1f62010-02-04 18:10:26 +00005867 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00005868 llvm::FoldingSetNodeID ID;
5869 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5870
5871 void *InsertPos = 0;
5872 QualifiedTemplateName *QTN =
5873 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5874 if (!QTN) {
Richard Smith2f47cab2012-08-16 01:19:31 +00005875 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
5876 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregor7532dc62009-03-30 22:58:21 +00005877 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5878 }
5879
5880 return TemplateName(QTN);
5881}
5882
5883/// \brief Retrieve the template name that represents a dependent
5884/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00005885TemplateName
5886ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5887 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00005888 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00005889 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00005890
5891 llvm::FoldingSetNodeID ID;
5892 DependentTemplateName::Profile(ID, NNS, Name);
5893
5894 void *InsertPos = 0;
5895 DependentTemplateName *QTN =
5896 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5897
5898 if (QTN)
5899 return TemplateName(QTN);
5900
5901 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5902 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00005903 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5904 DependentTemplateName(NNS, Name);
Douglas Gregor7532dc62009-03-30 22:58:21 +00005905 } else {
5906 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smith2f47cab2012-08-16 01:19:31 +00005907 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5908 DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005909 DependentTemplateName *CheckQTN =
5910 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5911 assert(!CheckQTN && "Dependent type name canonicalization broken");
5912 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00005913 }
5914
5915 DependentTemplateNames.InsertNode(QTN, InsertPos);
5916 return TemplateName(QTN);
5917}
5918
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005919/// \brief Retrieve the template name that represents a dependent
5920/// template name such as \c MetaFun::template operator+.
5921TemplateName
5922ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00005923 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005924 assert((!NNS || NNS->isDependent()) &&
5925 "Nested name specifier must be dependent");
5926
5927 llvm::FoldingSetNodeID ID;
5928 DependentTemplateName::Profile(ID, NNS, Operator);
5929
5930 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00005931 DependentTemplateName *QTN
5932 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005933
5934 if (QTN)
5935 return TemplateName(QTN);
5936
5937 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5938 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00005939 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5940 DependentTemplateName(NNS, Operator);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005941 } else {
5942 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smith2f47cab2012-08-16 01:19:31 +00005943 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5944 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005945
5946 DependentTemplateName *CheckQTN
5947 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5948 assert(!CheckQTN && "Dependent template name canonicalization broken");
5949 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005950 }
5951
5952 DependentTemplateNames.InsertNode(QTN, InsertPos);
5953 return TemplateName(QTN);
5954}
5955
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005956TemplateName
John McCall14606042011-06-30 08:33:18 +00005957ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5958 TemplateName replacement) const {
5959 llvm::FoldingSetNodeID ID;
5960 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5961
5962 void *insertPos = 0;
5963 SubstTemplateTemplateParmStorage *subst
5964 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5965
5966 if (!subst) {
5967 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5968 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5969 }
5970
5971 return TemplateName(subst);
5972}
5973
5974TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005975ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5976 const TemplateArgument &ArgPack) const {
5977 ASTContext &Self = const_cast<ASTContext &>(*this);
5978 llvm::FoldingSetNodeID ID;
5979 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5980
5981 void *InsertPos = 0;
5982 SubstTemplateTemplateParmPackStorage *Subst
5983 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5984
5985 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00005986 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005987 ArgPack.pack_size(),
5988 ArgPack.pack_begin());
5989 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5990 }
5991
5992 return TemplateName(Subst);
5993}
5994
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005995/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00005996/// TargetInfo, produce the corresponding type. The unsigned @p Type
5997/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00005998CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005999 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00006000 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006001 case TargetInfo::SignedShort: return ShortTy;
6002 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6003 case TargetInfo::SignedInt: return IntTy;
6004 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6005 case TargetInfo::SignedLong: return LongTy;
6006 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6007 case TargetInfo::SignedLongLong: return LongLongTy;
6008 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6009 }
6010
David Blaikieb219cfc2011-09-23 05:06:16 +00006011 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006012}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00006013
6014//===----------------------------------------------------------------------===//
6015// Type Predicates.
6016//===----------------------------------------------------------------------===//
6017
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006018/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6019/// garbage collection attribute.
6020///
John McCallae278a32011-01-12 00:34:59 +00006021Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006022 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00006023 return Qualifiers::GCNone;
6024
David Blaikie4e4d0842012-03-11 07:00:24 +00006025 assert(getLangOpts().ObjC1);
John McCallae278a32011-01-12 00:34:59 +00006026 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6027
6028 // Default behaviour under objective-C's gc is for ObjC pointers
6029 // (or pointers to them) be treated as though they were declared
6030 // as __strong.
6031 if (GCAttrs == Qualifiers::GCNone) {
6032 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6033 return Qualifiers::Strong;
6034 else if (Ty->isPointerType())
6035 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6036 } else {
6037 // It's not valid to set GC attributes on anything that isn't a
6038 // pointer.
6039#ifndef NDEBUG
6040 QualType CT = Ty->getCanonicalTypeInternal();
6041 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6042 CT = AT->getElementType();
6043 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6044#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006045 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00006046 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006047}
6048
Chris Lattner6ac46a42008-04-07 06:51:04 +00006049//===----------------------------------------------------------------------===//
6050// Type Compatibility Testing
6051//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00006052
Mike Stump1eb44332009-09-09 15:08:12 +00006053/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006054/// compatible.
6055static bool areCompatVectorTypes(const VectorType *LHS,
6056 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00006057 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00006058 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00006059 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00006060}
6061
Douglas Gregor255210e2010-08-06 10:14:59 +00006062bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6063 QualType SecondVec) {
6064 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6065 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6066
6067 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6068 return true;
6069
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006070 // Treat Neon vector types and most AltiVec vector types as if they are the
6071 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00006072 const VectorType *First = FirstVec->getAs<VectorType>();
6073 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006074 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00006075 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006076 First->getVectorKind() != VectorType::AltiVecPixel &&
6077 First->getVectorKind() != VectorType::AltiVecBool &&
6078 Second->getVectorKind() != VectorType::AltiVecPixel &&
6079 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00006080 return true;
6081
6082 return false;
6083}
6084
Steve Naroff4084c302009-07-23 01:01:38 +00006085//===----------------------------------------------------------------------===//
6086// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6087//===----------------------------------------------------------------------===//
6088
6089/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6090/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00006091bool
6092ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6093 ObjCProtocolDecl *rProto) const {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00006094 if (declaresSameEntity(lProto, rProto))
Steve Naroff4084c302009-07-23 01:01:38 +00006095 return true;
6096 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6097 E = rProto->protocol_end(); PI != E; ++PI)
6098 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6099 return true;
6100 return false;
6101}
6102
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00006103/// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
Steve Naroff4084c302009-07-23 01:01:38 +00006104/// return true if lhs's protocols conform to rhs's protocol; false
6105/// otherwise.
6106bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
6107 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
6108 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
6109 return false;
6110}
6111
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00006112/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6113/// Class<pr1, ...>.
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006114bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6115 QualType rhs) {
6116 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6117 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6118 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6119
6120 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6121 E = lhsQID->qual_end(); I != E; ++I) {
6122 bool match = false;
6123 ObjCProtocolDecl *lhsProto = *I;
6124 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6125 E = rhsOPT->qual_end(); J != E; ++J) {
6126 ObjCProtocolDecl *rhsProto = *J;
6127 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6128 match = true;
6129 break;
6130 }
6131 }
6132 if (!match)
6133 return false;
6134 }
6135 return true;
6136}
6137
Steve Naroff4084c302009-07-23 01:01:38 +00006138/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6139/// ObjCQualifiedIDType.
6140bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6141 bool compare) {
6142 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00006143 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006144 lhs->isObjCIdType() || lhs->isObjCClassType())
6145 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006146 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006147 rhs->isObjCIdType() || rhs->isObjCClassType())
6148 return true;
6149
6150 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00006151 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006152
Steve Naroff4084c302009-07-23 01:01:38 +00006153 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006154
Steve Naroff4084c302009-07-23 01:01:38 +00006155 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006156 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00006157 // make sure we check the class hierarchy.
6158 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6159 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6160 E = lhsQID->qual_end(); I != E; ++I) {
6161 // when comparing an id<P> on lhs with a static type on rhs,
6162 // see if static class implements all of id's protocols, directly or
6163 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006164 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00006165 return false;
6166 }
6167 }
6168 // If there are no qualifiers and no interface, we have an 'id'.
6169 return true;
6170 }
Mike Stump1eb44332009-09-09 15:08:12 +00006171 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006172 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6173 E = lhsQID->qual_end(); I != E; ++I) {
6174 ObjCProtocolDecl *lhsProto = *I;
6175 bool match = false;
6176
6177 // when comparing an id<P> on lhs with a static type on rhs,
6178 // see if static class implements all of id's protocols, directly or
6179 // through its super class and categories.
6180 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6181 E = rhsOPT->qual_end(); J != E; ++J) {
6182 ObjCProtocolDecl *rhsProto = *J;
6183 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6184 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6185 match = true;
6186 break;
6187 }
6188 }
Mike Stump1eb44332009-09-09 15:08:12 +00006189 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00006190 // make sure we check the class hierarchy.
6191 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6192 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6193 E = lhsQID->qual_end(); I != E; ++I) {
6194 // when comparing an id<P> on lhs with a static type on rhs,
6195 // see if static class implements all of id's protocols, directly or
6196 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006197 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00006198 match = true;
6199 break;
6200 }
6201 }
6202 }
6203 if (!match)
6204 return false;
6205 }
Mike Stump1eb44332009-09-09 15:08:12 +00006206
Steve Naroff4084c302009-07-23 01:01:38 +00006207 return true;
6208 }
Mike Stump1eb44332009-09-09 15:08:12 +00006209
Steve Naroff4084c302009-07-23 01:01:38 +00006210 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6211 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6212
Mike Stump1eb44332009-09-09 15:08:12 +00006213 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00006214 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006215 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006216 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6217 E = lhsOPT->qual_end(); I != E; ++I) {
6218 ObjCProtocolDecl *lhsProto = *I;
6219 bool match = false;
6220
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006221 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00006222 // see if static class implements all of id's protocols, directly or
6223 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006224 // First, lhs protocols in the qualifier list must be found, direct
6225 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00006226 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6227 E = rhsQID->qual_end(); J != E; ++J) {
6228 ObjCProtocolDecl *rhsProto = *J;
6229 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6230 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6231 match = true;
6232 break;
6233 }
6234 }
6235 if (!match)
6236 return false;
6237 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006238
6239 // Static class's protocols, or its super class or category protocols
6240 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6241 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6242 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6243 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6244 // This is rather dubious but matches gcc's behavior. If lhs has
6245 // no type qualifier and its class has no static protocol(s)
6246 // assume that it is mismatch.
6247 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6248 return false;
6249 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6250 LHSInheritedProtocols.begin(),
6251 E = LHSInheritedProtocols.end(); I != E; ++I) {
6252 bool match = false;
6253 ObjCProtocolDecl *lhsProto = (*I);
6254 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6255 E = rhsQID->qual_end(); J != E; ++J) {
6256 ObjCProtocolDecl *rhsProto = *J;
6257 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6258 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6259 match = true;
6260 break;
6261 }
6262 }
6263 if (!match)
6264 return false;
6265 }
6266 }
Steve Naroff4084c302009-07-23 01:01:38 +00006267 return true;
6268 }
6269 return false;
6270}
6271
Eli Friedman3d815e72008-08-22 00:56:42 +00006272/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006273/// compatible for assignment from RHS to LHS. This handles validation of any
6274/// protocol qualifiers on the LHS or RHS.
6275///
Steve Naroff14108da2009-07-10 23:34:53 +00006276bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6277 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00006278 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6279 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6280
Steve Naroffde2e22d2009-07-15 18:40:39 +00006281 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00006282 if (LHS->isObjCUnqualifiedIdOrClass() ||
6283 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00006284 return true;
6285
John McCallc12c5bb2010-05-15 11:32:37 +00006286 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00006287 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6288 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00006289 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006290
6291 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6292 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6293 QualType(RHSOPT,0));
6294
John McCallc12c5bb2010-05-15 11:32:37 +00006295 // If we have 2 user-defined types, fall into that path.
6296 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00006297 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006298
Steve Naroff4084c302009-07-23 01:01:38 +00006299 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006300}
6301
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006302/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00006303/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006304/// arguments in block literals. When passed as arguments, passing 'A*' where
6305/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6306/// not OK. For the return type, the opposite is not OK.
6307bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6308 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006309 const ObjCObjectPointerType *RHSOPT,
6310 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006311 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006312 return true;
6313
6314 if (LHSOPT->isObjCBuiltinType()) {
6315 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6316 }
6317
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006318 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006319 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6320 QualType(RHSOPT,0),
6321 false);
6322
6323 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6324 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6325 if (LHS && RHS) { // We have 2 user-defined types.
6326 if (LHS != RHS) {
6327 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006328 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006329 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006330 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006331 }
6332 else
6333 return true;
6334 }
6335 return false;
6336}
6337
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006338/// getIntersectionOfProtocols - This routine finds the intersection of set
6339/// of protocols inherited from two distinct objective-c pointer objects.
6340/// It is used to build composite qualifier list of the composite type of
6341/// the conditional expression involving two objective-c pointer objects.
6342static
6343void getIntersectionOfProtocols(ASTContext &Context,
6344 const ObjCObjectPointerType *LHSOPT,
6345 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006346 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006347
John McCallc12c5bb2010-05-15 11:32:37 +00006348 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6349 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6350 assert(LHS->getInterface() && "LHS must have an interface base");
6351 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006352
6353 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6354 unsigned LHSNumProtocols = LHS->getNumProtocols();
6355 if (LHSNumProtocols > 0)
6356 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6357 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006358 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006359 Context.CollectInheritedProtocols(LHS->getInterface(),
6360 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006361 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6362 LHSInheritedProtocols.end());
6363 }
6364
6365 unsigned RHSNumProtocols = RHS->getNumProtocols();
6366 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00006367 ObjCProtocolDecl **RHSProtocols =
6368 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006369 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6370 if (InheritedProtocolSet.count(RHSProtocols[i]))
6371 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00006372 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006373 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006374 Context.CollectInheritedProtocols(RHS->getInterface(),
6375 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006376 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6377 RHSInheritedProtocols.begin(),
6378 E = RHSInheritedProtocols.end(); I != E; ++I)
6379 if (InheritedProtocolSet.count((*I)))
6380 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006381 }
6382}
6383
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006384/// areCommonBaseCompatible - Returns common base class of the two classes if
6385/// one found. Note that this is O'2 algorithm. But it will be called as the
6386/// last type comparison in a ?-exp of ObjC pointer types before a
6387/// warning is issued. So, its invokation is extremely rare.
6388QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00006389 const ObjCObjectPointerType *Lptr,
6390 const ObjCObjectPointerType *Rptr) {
6391 const ObjCObjectType *LHS = Lptr->getObjectType();
6392 const ObjCObjectType *RHS = Rptr->getObjectType();
6393 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6394 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor60ef3082011-12-15 00:29:59 +00006395 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006396 return QualType();
6397
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006398 do {
John McCallc12c5bb2010-05-15 11:32:37 +00006399 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006400 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006401 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006402 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6403
6404 QualType Result = QualType(LHS, 0);
6405 if (!Protocols.empty())
6406 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6407 Result = getObjCObjectPointerType(Result);
6408 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006409 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006410 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006411
6412 return QualType();
6413}
6414
John McCallc12c5bb2010-05-15 11:32:37 +00006415bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6416 const ObjCObjectType *RHS) {
6417 assert(LHS->getInterface() && "LHS is not an interface type");
6418 assert(RHS->getInterface() && "RHS is not an interface type");
6419
Chris Lattner6ac46a42008-04-07 06:51:04 +00006420 // Verify that the base decls are compatible: the RHS must be a subclass of
6421 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00006422 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00006423 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006424
Chris Lattner6ac46a42008-04-07 06:51:04 +00006425 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6426 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00006427 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00006428 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006429
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006430 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6431 // more detailed analysis is required.
6432 if (RHS->getNumProtocols() == 0) {
6433 // OK, if LHS is a superclass of RHS *and*
6434 // this superclass is assignment compatible with LHS.
6435 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006436 bool IsSuperClass =
6437 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6438 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006439 // OK if conversion of LHS to SuperClass results in narrowing of types
6440 // ; i.e., SuperClass may implement at least one of the protocols
6441 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6442 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6443 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006444 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006445 // If super class has no protocols, it is not a match.
6446 if (SuperClassInheritedProtocols.empty())
6447 return false;
6448
6449 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6450 LHSPE = LHS->qual_end();
6451 LHSPI != LHSPE; LHSPI++) {
6452 bool SuperImplementsProtocol = false;
6453 ObjCProtocolDecl *LHSProto = (*LHSPI);
6454
6455 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6456 SuperClassInheritedProtocols.begin(),
6457 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6458 ObjCProtocolDecl *SuperClassProto = (*I);
6459 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6460 SuperImplementsProtocol = true;
6461 break;
6462 }
6463 }
6464 if (!SuperImplementsProtocol)
6465 return false;
6466 }
6467 return true;
6468 }
6469 return false;
6470 }
Mike Stump1eb44332009-09-09 15:08:12 +00006471
John McCallc12c5bb2010-05-15 11:32:37 +00006472 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6473 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006474 LHSPI != LHSPE; LHSPI++) {
6475 bool RHSImplementsProtocol = false;
6476
6477 // If the RHS doesn't implement the protocol on the left, the types
6478 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00006479 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6480 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00006481 RHSPI != RHSPE; RHSPI++) {
6482 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006483 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00006484 break;
6485 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006486 }
6487 // FIXME: For better diagnostics, consider passing back the protocol name.
6488 if (!RHSImplementsProtocol)
6489 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006490 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006491 // The RHS implements all protocols listed on the LHS.
6492 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006493}
6494
Steve Naroff389bf462009-02-12 17:52:19 +00006495bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6496 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00006497 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6498 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006499
Steve Naroff14108da2009-07-10 23:34:53 +00006500 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00006501 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006502
6503 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6504 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00006505}
6506
Douglas Gregor569c3162010-08-07 11:51:51 +00006507bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6508 return canAssignObjCInterfaces(
6509 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6510 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6511}
6512
Mike Stump1eb44332009-09-09 15:08:12 +00006513/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00006514/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00006515/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00006516/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00006517bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6518 bool CompareUnqualified) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006519 if (getLangOpts().CPlusPlus)
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006520 return hasSameType(LHS, RHS);
6521
Douglas Gregor447234d2010-07-29 15:18:02 +00006522 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00006523}
6524
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006525bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00006526 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006527}
6528
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006529bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6530 return !mergeTypes(LHS, RHS, true).isNull();
6531}
6532
Peter Collingbourne48466752010-10-24 18:30:18 +00006533/// mergeTransparentUnionType - if T is a transparent union type and a member
6534/// of T is compatible with SubType, return the merged type, else return
6535/// QualType()
6536QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6537 bool OfBlockPointer,
6538 bool Unqualified) {
6539 if (const RecordType *UT = T->getAsUnionType()) {
6540 RecordDecl *UD = UT->getDecl();
6541 if (UD->hasAttr<TransparentUnionAttr>()) {
6542 for (RecordDecl::field_iterator it = UD->field_begin(),
6543 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00006544 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006545 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6546 if (!MT.isNull())
6547 return MT;
6548 }
6549 }
6550 }
6551
6552 return QualType();
6553}
6554
6555/// mergeFunctionArgumentTypes - merge two types which appear as function
6556/// argument types
6557QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6558 bool OfBlockPointer,
6559 bool Unqualified) {
6560 // GNU extension: two types are compatible if they appear as a function
6561 // argument, one of the types is a transparent union type and the other
6562 // type is compatible with a union member
6563 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6564 Unqualified);
6565 if (!lmerge.isNull())
6566 return lmerge;
6567
6568 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6569 Unqualified);
6570 if (!rmerge.isNull())
6571 return rmerge;
6572
6573 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6574}
6575
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006576QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00006577 bool OfBlockPointer,
6578 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00006579 const FunctionType *lbase = lhs->getAs<FunctionType>();
6580 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00006581 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6582 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00006583 bool allLTypes = true;
6584 bool allRTypes = true;
6585
6586 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006587 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006588 if (OfBlockPointer) {
6589 QualType RHS = rbase->getResultType();
6590 QualType LHS = lbase->getResultType();
6591 bool UnqualifiedResult = Unqualified;
6592 if (!UnqualifiedResult)
6593 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006594 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006595 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006596 else
John McCall8cc246c2010-12-15 01:06:38 +00006597 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6598 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006599 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006600
6601 if (Unqualified)
6602 retType = retType.getUnqualifiedType();
6603
6604 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6605 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6606 if (Unqualified) {
6607 LRetType = LRetType.getUnqualifiedType();
6608 RRetType = RRetType.getUnqualifiedType();
6609 }
6610
6611 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006612 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00006613 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006614 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00006615
Daniel Dunbar6a15c852010-04-28 16:20:58 +00006616 // FIXME: double check this
6617 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6618 // rbase->getRegParmAttr() != 0 &&
6619 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00006620 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6621 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00006622
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006623 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00006624 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006625 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006626
John McCall8cc246c2010-12-15 01:06:38 +00006627 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00006628 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6629 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00006630 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6631 return QualType();
6632
John McCallf85e1932011-06-15 23:02:42 +00006633 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6634 return QualType();
6635
John McCall8cc246c2010-12-15 01:06:38 +00006636 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6637 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00006638
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00006639 if (lbaseInfo.getNoReturn() != NoReturn)
6640 allLTypes = false;
6641 if (rbaseInfo.getNoReturn() != NoReturn)
6642 allRTypes = false;
6643
John McCallf85e1932011-06-15 23:02:42 +00006644 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00006645
Eli Friedman3d815e72008-08-22 00:56:42 +00006646 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00006647 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6648 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006649 unsigned lproto_nargs = lproto->getNumArgs();
6650 unsigned rproto_nargs = rproto->getNumArgs();
6651
6652 // Compatible functions must have the same number of arguments
6653 if (lproto_nargs != rproto_nargs)
6654 return QualType();
6655
6656 // Variadic and non-variadic functions aren't compatible
6657 if (lproto->isVariadic() != rproto->isVariadic())
6658 return QualType();
6659
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00006660 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6661 return QualType();
6662
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006663 if (LangOpts.ObjCAutoRefCount &&
6664 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6665 return QualType();
6666
Eli Friedman3d815e72008-08-22 00:56:42 +00006667 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00006668 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00006669 for (unsigned i = 0; i < lproto_nargs; i++) {
6670 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6671 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006672 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6673 OfBlockPointer,
6674 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006675 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006676
6677 if (Unqualified)
6678 argtype = argtype.getUnqualifiedType();
6679
Eli Friedman3d815e72008-08-22 00:56:42 +00006680 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00006681 if (Unqualified) {
6682 largtype = largtype.getUnqualifiedType();
6683 rargtype = rargtype.getUnqualifiedType();
6684 }
6685
Chris Lattner61710852008-10-05 17:34:18 +00006686 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6687 allLTypes = false;
6688 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6689 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00006690 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006691
Eli Friedman3d815e72008-08-22 00:56:42 +00006692 if (allLTypes) return lhs;
6693 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00006694
6695 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6696 EPI.ExtInfo = einfo;
6697 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00006698 }
6699
6700 if (lproto) allRTypes = false;
6701 if (rproto) allLTypes = false;
6702
Douglas Gregor72564e72009-02-26 23:50:07 +00006703 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00006704 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00006705 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006706 if (proto->isVariadic()) return QualType();
6707 // Check that the types are compatible with the types that
6708 // would result from default argument promotions (C99 6.7.5.3p15).
6709 // The only types actually affected are promotable integer
6710 // types and floats, which would be passed as a different
6711 // type depending on whether the prototype is visible.
6712 unsigned proto_nargs = proto->getNumArgs();
6713 for (unsigned i = 0; i < proto_nargs; ++i) {
6714 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00006715
Eli Friedmanc586d5d2012-08-30 00:44:15 +00006716 // Look at the converted type of enum types, since that is the type used
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00006717 // to pass enum values.
Eli Friedmanc586d5d2012-08-30 00:44:15 +00006718 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
6719 argTy = Enum->getDecl()->getIntegerType();
6720 if (argTy.isNull())
6721 return QualType();
6722 }
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00006723
Eli Friedman3d815e72008-08-22 00:56:42 +00006724 if (argTy->isPromotableIntegerType() ||
6725 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6726 return QualType();
6727 }
6728
6729 if (allLTypes) return lhs;
6730 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00006731
6732 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6733 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00006734 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00006735 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00006736 }
6737
6738 if (allLTypes) return lhs;
6739 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00006740 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00006741}
6742
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006743QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00006744 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006745 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00006746 // C++ [expr]: If an expression initially has the type "reference to T", the
6747 // type is adjusted to "T" prior to any further analysis, the expression
6748 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00006749 // expression is an lvalue unless the reference is an rvalue reference and
6750 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006751 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6752 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00006753
6754 if (Unqualified) {
6755 LHS = LHS.getUnqualifiedType();
6756 RHS = RHS.getUnqualifiedType();
6757 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006758
Eli Friedman3d815e72008-08-22 00:56:42 +00006759 QualType LHSCan = getCanonicalType(LHS),
6760 RHSCan = getCanonicalType(RHS);
6761
6762 // If two types are identical, they are compatible.
6763 if (LHSCan == RHSCan)
6764 return LHS;
6765
John McCall0953e762009-09-24 19:53:00 +00006766 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006767 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6768 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00006769 if (LQuals != RQuals) {
6770 // If any of these qualifiers are different, we have a type
6771 // mismatch.
6772 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00006773 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6774 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00006775 return QualType();
6776
6777 // Exactly one GC qualifier difference is allowed: __strong is
6778 // okay if the other type has no GC qualifier but is an Objective
6779 // C object pointer (i.e. implicitly strong by default). We fix
6780 // this by pretending that the unqualified type was actually
6781 // qualified __strong.
6782 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6783 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6784 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6785
6786 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6787 return QualType();
6788
6789 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6790 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6791 }
6792 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6793 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6794 }
Eli Friedman3d815e72008-08-22 00:56:42 +00006795 return QualType();
John McCall0953e762009-09-24 19:53:00 +00006796 }
6797
6798 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00006799
Eli Friedman852d63b2009-06-01 01:22:52 +00006800 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6801 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00006802
Chris Lattner1adb8832008-01-14 05:45:46 +00006803 // We want to consider the two function types to be the same for these
6804 // comparisons, just force one to the other.
6805 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6806 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00006807
6808 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00006809 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6810 LHSClass = Type::ConstantArray;
6811 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6812 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00006813
John McCallc12c5bb2010-05-15 11:32:37 +00006814 // ObjCInterfaces are just specialized ObjCObjects.
6815 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6816 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6817
Nate Begeman213541a2008-04-18 23:10:10 +00006818 // Canonicalize ExtVector -> Vector.
6819 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6820 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00006821
Chris Lattnera36a61f2008-04-07 05:43:21 +00006822 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00006823 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00006824 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00006825 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00006826 // Compatibility is based on the underlying type, not the promotion
6827 // type.
John McCall183700f2009-09-21 23:43:11 +00006828 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianb918d6b2012-02-06 19:06:20 +00006829 QualType TINT = ETy->getDecl()->getIntegerType();
6830 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006831 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00006832 }
John McCall183700f2009-09-21 23:43:11 +00006833 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianb918d6b2012-02-06 19:06:20 +00006834 QualType TINT = ETy->getDecl()->getIntegerType();
6835 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006836 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00006837 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00006838 // allow block pointer type to match an 'id' type.
Fariborz Jahanian41963632012-01-26 17:08:50 +00006839 if (OfBlockPointer && !BlockReturnType) {
6840 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6841 return LHS;
6842 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6843 return RHS;
6844 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00006845
Eli Friedman3d815e72008-08-22 00:56:42 +00006846 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00006847 }
Eli Friedman3d815e72008-08-22 00:56:42 +00006848
Steve Naroff4a746782008-01-09 22:43:08 +00006849 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00006850 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00006851#define TYPE(Class, Base)
6852#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00006853#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00006854#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6855#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6856#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00006857 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00006858
Sebastian Redl7c80bd62009-03-16 23:22:08 +00006859 case Type::LValueReference:
6860 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00006861 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00006862 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00006863
John McCallc12c5bb2010-05-15 11:32:37 +00006864 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00006865 case Type::IncompleteArray:
6866 case Type::VariableArray:
6867 case Type::FunctionProto:
6868 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00006869 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00006870
Chris Lattner1adb8832008-01-14 05:45:46 +00006871 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00006872 {
6873 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00006874 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6875 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006876 if (Unqualified) {
6877 LHSPointee = LHSPointee.getUnqualifiedType();
6878 RHSPointee = RHSPointee.getUnqualifiedType();
6879 }
6880 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6881 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006882 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00006883 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00006884 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00006885 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00006886 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00006887 return getPointerType(ResultType);
6888 }
Steve Naroffc0febd52008-12-10 17:49:55 +00006889 case Type::BlockPointer:
6890 {
6891 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00006892 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6893 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006894 if (Unqualified) {
6895 LHSPointee = LHSPointee.getUnqualifiedType();
6896 RHSPointee = RHSPointee.getUnqualifiedType();
6897 }
6898 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6899 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00006900 if (ResultType.isNull()) return QualType();
6901 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6902 return LHS;
6903 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6904 return RHS;
6905 return getBlockPointerType(ResultType);
6906 }
Eli Friedmanb001de72011-10-06 23:00:33 +00006907 case Type::Atomic:
6908 {
6909 // Merge two pointer types, while trying to preserve typedef info
6910 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6911 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6912 if (Unqualified) {
6913 LHSValue = LHSValue.getUnqualifiedType();
6914 RHSValue = RHSValue.getUnqualifiedType();
6915 }
6916 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6917 Unqualified);
6918 if (ResultType.isNull()) return QualType();
6919 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6920 return LHS;
6921 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6922 return RHS;
6923 return getAtomicType(ResultType);
6924 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006925 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00006926 {
6927 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6928 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6929 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6930 return QualType();
6931
6932 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6933 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006934 if (Unqualified) {
6935 LHSElem = LHSElem.getUnqualifiedType();
6936 RHSElem = RHSElem.getUnqualifiedType();
6937 }
6938
6939 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006940 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00006941 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6942 return LHS;
6943 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6944 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00006945 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6946 ArrayType::ArraySizeModifier(), 0);
6947 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6948 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006949 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6950 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00006951 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6952 return LHS;
6953 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6954 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00006955 if (LVAT) {
6956 // FIXME: This isn't correct! But tricky to implement because
6957 // the array's size has to be the size of LHS, but the type
6958 // has to be different.
6959 return LHS;
6960 }
6961 if (RVAT) {
6962 // FIXME: This isn't correct! But tricky to implement because
6963 // the array's size has to be the size of RHS, but the type
6964 // has to be different.
6965 return RHS;
6966 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00006967 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6968 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00006969 return getIncompleteArrayType(ResultType,
6970 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006971 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006972 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00006973 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00006974 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00006975 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00006976 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00006977 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006978 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00006979 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00006980 case Type::Complex:
6981 // Distinct complex types are incompatible.
6982 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006983 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006984 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00006985 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6986 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006987 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00006988 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00006989 case Type::ObjCObject: {
6990 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006991 // FIXME: This should be type compatibility, e.g. whether
6992 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00006993 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6994 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6995 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00006996 return LHS;
6997
Eli Friedman3d815e72008-08-22 00:56:42 +00006998 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00006999 }
Steve Naroff14108da2009-07-10 23:34:53 +00007000 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007001 if (OfBlockPointer) {
7002 if (canAssignObjCInterfacesInBlockPointer(
7003 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00007004 RHS->getAs<ObjCObjectPointerType>(),
7005 BlockReturnType))
David Blaikie7530c032012-01-17 06:56:22 +00007006 return LHS;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007007 return QualType();
7008 }
John McCall183700f2009-09-21 23:43:11 +00007009 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7010 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00007011 return LHS;
7012
Steve Naroffbc76dd02008-12-10 22:14:21 +00007013 return QualType();
David Blaikie7530c032012-01-17 06:56:22 +00007014 }
Steve Naroffec0550f2007-10-15 20:41:53 +00007015 }
Douglas Gregor72564e72009-02-26 23:50:07 +00007016
David Blaikie7530c032012-01-17 06:56:22 +00007017 llvm_unreachable("Invalid Type::Class!");
Steve Naroffec0550f2007-10-15 20:41:53 +00007018}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00007019
Fariborz Jahanian78213e42011-09-28 21:52:05 +00007020bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7021 const FunctionProtoType *FromFunctionType,
7022 const FunctionProtoType *ToFunctionType) {
7023 if (FromFunctionType->hasAnyConsumedArgs() !=
7024 ToFunctionType->hasAnyConsumedArgs())
7025 return false;
7026 FunctionProtoType::ExtProtoInfo FromEPI =
7027 FromFunctionType->getExtProtoInfo();
7028 FunctionProtoType::ExtProtoInfo ToEPI =
7029 ToFunctionType->getExtProtoInfo();
7030 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
7031 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
7032 ArgIdx != NumArgs; ++ArgIdx) {
7033 if (FromEPI.ConsumedArguments[ArgIdx] !=
7034 ToEPI.ConsumedArguments[ArgIdx])
7035 return false;
7036 }
7037 return true;
7038}
7039
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007040/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7041/// 'RHS' attributes and returns the merged version; including for function
7042/// return types.
7043QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7044 QualType LHSCan = getCanonicalType(LHS),
7045 RHSCan = getCanonicalType(RHS);
7046 // If two types are identical, they are compatible.
7047 if (LHSCan == RHSCan)
7048 return LHS;
7049 if (RHSCan->isFunctionType()) {
7050 if (!LHSCan->isFunctionType())
7051 return QualType();
7052 QualType OldReturnType =
7053 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7054 QualType NewReturnType =
7055 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7056 QualType ResReturnType =
7057 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7058 if (ResReturnType.isNull())
7059 return QualType();
7060 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7061 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7062 // In either case, use OldReturnType to build the new function type.
7063 const FunctionType *F = LHS->getAs<FunctionType>();
7064 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00007065 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7066 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007067 QualType ResultType
7068 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00007069 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007070 return ResultType;
7071 }
7072 }
7073 return QualType();
7074 }
7075
7076 // If the qualifiers are different, the types can still be merged.
7077 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7078 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7079 if (LQuals != RQuals) {
7080 // If any of these qualifiers are different, we have a type mismatch.
7081 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7082 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7083 return QualType();
7084
7085 // Exactly one GC qualifier difference is allowed: __strong is
7086 // okay if the other type has no GC qualifier but is an Objective
7087 // C object pointer (i.e. implicitly strong by default). We fix
7088 // this by pretending that the unqualified type was actually
7089 // qualified __strong.
7090 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7091 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7092 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7093
7094 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7095 return QualType();
7096
7097 if (GC_L == Qualifiers::Strong)
7098 return LHS;
7099 if (GC_R == Qualifiers::Strong)
7100 return RHS;
7101 return QualType();
7102 }
7103
7104 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7105 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7106 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7107 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7108 if (ResQT == LHSBaseQT)
7109 return LHS;
7110 if (ResQT == RHSBaseQT)
7111 return RHS;
7112 }
7113 return QualType();
7114}
7115
Chris Lattner5426bf62008-04-07 07:01:58 +00007116//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00007117// Integer Predicates
7118//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00007119
Jay Foad4ba2a172011-01-12 09:06:06 +00007120unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00007121 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00007122 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007123 if (T->isBooleanType())
7124 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00007125 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00007126 return (unsigned)getTypeSize(T);
7127}
7128
Abramo Bagnara762f1592012-09-09 10:21:24 +00007129QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregorf6094622010-07-23 15:58:24 +00007130 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00007131
7132 // Turn <4 x signed int> -> <4 x unsigned int>
7133 if (const VectorType *VTy = T->getAs<VectorType>())
7134 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00007135 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00007136
7137 // For enums, we return the unsigned version of the base type.
7138 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00007139 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00007140
7141 const BuiltinType *BTy = T->getAs<BuiltinType>();
7142 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007143 switch (BTy->getKind()) {
7144 case BuiltinType::Char_S:
7145 case BuiltinType::SChar:
7146 return UnsignedCharTy;
7147 case BuiltinType::Short:
7148 return UnsignedShortTy;
7149 case BuiltinType::Int:
7150 return UnsignedIntTy;
7151 case BuiltinType::Long:
7152 return UnsignedLongTy;
7153 case BuiltinType::LongLong:
7154 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00007155 case BuiltinType::Int128:
7156 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00007157 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00007158 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007159 }
7160}
7161
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00007162ASTMutationListener::~ASTMutationListener() { }
7163
Chris Lattner86df27b2009-06-14 00:45:47 +00007164
7165//===----------------------------------------------------------------------===//
7166// Builtin Type Computation
7167//===----------------------------------------------------------------------===//
7168
7169/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00007170/// pointer over the consumed characters. This returns the resultant type. If
7171/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7172/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7173/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00007174///
7175/// RequiresICE is filled in on return to indicate whether the value is required
7176/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00007177static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00007178 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00007179 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00007180 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00007181 // Modifiers.
7182 int HowLong = 0;
7183 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00007184 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007185
Chris Lattner33daae62010-10-01 22:42:38 +00007186 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00007187 bool Done = false;
7188 while (!Done) {
7189 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00007190 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007191 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00007192 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007193 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007194 case 'S':
7195 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7196 assert(!Signed && "Can't use 'S' modifier multiple times!");
7197 Signed = true;
7198 break;
7199 case 'U':
7200 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7201 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7202 Unsigned = true;
7203 break;
7204 case 'L':
7205 assert(HowLong <= 2 && "Can't have LLLL modifier");
7206 ++HowLong;
7207 break;
7208 }
7209 }
7210
7211 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00007212
Chris Lattner86df27b2009-06-14 00:45:47 +00007213 // Read the base type.
7214 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00007215 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00007216 case 'v':
7217 assert(HowLong == 0 && !Signed && !Unsigned &&
7218 "Bad modifiers used with 'v'!");
7219 Type = Context.VoidTy;
7220 break;
7221 case 'f':
7222 assert(HowLong == 0 && !Signed && !Unsigned &&
7223 "Bad modifiers used with 'f'!");
7224 Type = Context.FloatTy;
7225 break;
7226 case 'd':
7227 assert(HowLong < 2 && !Signed && !Unsigned &&
7228 "Bad modifiers used with 'd'!");
7229 if (HowLong)
7230 Type = Context.LongDoubleTy;
7231 else
7232 Type = Context.DoubleTy;
7233 break;
7234 case 's':
7235 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7236 if (Unsigned)
7237 Type = Context.UnsignedShortTy;
7238 else
7239 Type = Context.ShortTy;
7240 break;
7241 case 'i':
7242 if (HowLong == 3)
7243 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7244 else if (HowLong == 2)
7245 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7246 else if (HowLong == 1)
7247 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7248 else
7249 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7250 break;
7251 case 'c':
7252 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7253 if (Signed)
7254 Type = Context.SignedCharTy;
7255 else if (Unsigned)
7256 Type = Context.UnsignedCharTy;
7257 else
7258 Type = Context.CharTy;
7259 break;
7260 case 'b': // boolean
7261 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7262 Type = Context.BoolTy;
7263 break;
7264 case 'z': // size_t.
7265 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7266 Type = Context.getSizeType();
7267 break;
7268 case 'F':
7269 Type = Context.getCFConstantStringType();
7270 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00007271 case 'G':
7272 Type = Context.getObjCIdType();
7273 break;
7274 case 'H':
7275 Type = Context.getObjCSelType();
7276 break;
Fariborz Jahanianf7992132013-01-04 18:45:40 +00007277 case 'M':
7278 Type = Context.getObjCSuperType();
7279 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007280 case 'a':
7281 Type = Context.getBuiltinVaListType();
7282 assert(!Type.isNull() && "builtin va list type not initialized!");
7283 break;
7284 case 'A':
7285 // This is a "reference" to a va_list; however, what exactly
7286 // this means depends on how va_list is defined. There are two
7287 // different kinds of va_list: ones passed by value, and ones
7288 // passed by reference. An example of a by-value va_list is
7289 // x86, where va_list is a char*. An example of by-ref va_list
7290 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7291 // we want this argument to be a char*&; for x86-64, we want
7292 // it to be a __va_list_tag*.
7293 Type = Context.getBuiltinVaListType();
7294 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00007295 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00007296 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00007297 else
Chris Lattner86df27b2009-06-14 00:45:47 +00007298 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00007299 break;
7300 case 'V': {
7301 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00007302 unsigned NumElements = strtoul(Str, &End, 10);
7303 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00007304 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00007305
Chris Lattner14e0e742010-10-01 22:53:11 +00007306 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7307 RequiresICE, false);
7308 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00007309
7310 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00007311 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00007312 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00007313 break;
7314 }
Douglas Gregorb4bc99b2012-06-07 18:08:25 +00007315 case 'E': {
7316 char *End;
7317
7318 unsigned NumElements = strtoul(Str, &End, 10);
7319 assert(End != Str && "Missing vector size");
7320
7321 Str = End;
7322
7323 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7324 false);
7325 Type = Context.getExtVectorType(ElementType, NumElements);
7326 break;
7327 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00007328 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00007329 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7330 false);
7331 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00007332 Type = Context.getComplexType(ElementType);
7333 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00007334 }
7335 case 'Y' : {
7336 Type = Context.getPointerDiffType();
7337 break;
7338 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007339 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00007340 Type = Context.getFILEType();
7341 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007342 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00007343 return QualType();
7344 }
Mike Stumpfd612db2009-07-28 23:47:15 +00007345 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007346 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00007347 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00007348 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00007349 else
7350 Type = Context.getjmp_bufType();
7351
Mike Stumpfd612db2009-07-28 23:47:15 +00007352 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007353 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00007354 return QualType();
7355 }
7356 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00007357 case 'K':
7358 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7359 Type = Context.getucontext_tType();
7360
7361 if (Type.isNull()) {
7362 Error = ASTContext::GE_Missing_ucontext;
7363 return QualType();
7364 }
7365 break;
Eli Friedman6902e412012-11-27 02:58:24 +00007366 case 'p':
7367 Type = Context.getProcessIDType();
7368 break;
Mike Stump782fa302009-07-28 02:25:19 +00007369 }
Mike Stump1eb44332009-09-09 15:08:12 +00007370
Chris Lattner33daae62010-10-01 22:42:38 +00007371 // If there are modifiers and if we're allowed to parse them, go for it.
7372 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00007373 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00007374 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00007375 default: Done = true; --Str; break;
7376 case '*':
7377 case '&': {
7378 // Both pointers and references can have their pointee types
7379 // qualified with an address space.
7380 char *End;
7381 unsigned AddrSpace = strtoul(Str, &End, 10);
7382 if (End != Str && AddrSpace != 0) {
7383 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7384 Str = End;
7385 }
7386 if (c == '*')
7387 Type = Context.getPointerType(Type);
7388 else
7389 Type = Context.getLValueReferenceType(Type);
7390 break;
7391 }
7392 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7393 case 'C':
7394 Type = Type.withConst();
7395 break;
7396 case 'D':
7397 Type = Context.getVolatileType(Type);
7398 break;
Ted Kremenek18932a02012-01-20 21:40:12 +00007399 case 'R':
7400 Type = Type.withRestrict();
7401 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007402 }
7403 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00007404
Chris Lattner14e0e742010-10-01 22:53:11 +00007405 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00007406 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00007407
Chris Lattner86df27b2009-06-14 00:45:47 +00007408 return Type;
7409}
7410
7411/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00007412QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00007413 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00007414 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00007415 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00007416
Chris Lattner5f9e2722011-07-23 10:55:15 +00007417 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00007418
Chris Lattner14e0e742010-10-01 22:53:11 +00007419 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00007420 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00007421 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7422 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007423 if (Error != GE_None)
7424 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00007425
7426 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7427
Chris Lattner86df27b2009-06-14 00:45:47 +00007428 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00007429 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007430 if (Error != GE_None)
7431 return QualType();
7432
Chris Lattner14e0e742010-10-01 22:53:11 +00007433 // If this argument is required to be an IntegerConstantExpression and the
7434 // caller cares, fill in the bitmask we return.
7435 if (RequiresICE && IntegerConstantArgs)
7436 *IntegerConstantArgs |= 1 << ArgTypes.size();
7437
Chris Lattner86df27b2009-06-14 00:45:47 +00007438 // Do array -> pointer decay. The builtin should use the decayed type.
7439 if (Ty->isArrayType())
7440 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00007441
Chris Lattner86df27b2009-06-14 00:45:47 +00007442 ArgTypes.push_back(Ty);
7443 }
7444
7445 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7446 "'.' should only occur at end of builtin type list!");
7447
John McCall00ccbef2010-12-21 00:44:39 +00007448 FunctionType::ExtInfo EI;
7449 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7450
7451 bool Variadic = (TypeStr[0] == '.');
7452
7453 // We really shouldn't be making a no-proto type here, especially in C++.
7454 if (ArgTypes.empty() && Variadic)
7455 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00007456
John McCalle23cf432010-12-14 08:05:40 +00007457 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00007458 EPI.ExtInfo = EI;
7459 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00007460
7461 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00007462}
Eli Friedmana95d7572009-08-19 07:44:53 +00007463
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007464GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
7465 GVALinkage External = GVA_StrongExternal;
7466
7467 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007468 switch (L) {
7469 case NoLinkage:
7470 case InternalLinkage:
7471 case UniqueExternalLinkage:
7472 return GVA_Internal;
7473
7474 case ExternalLinkage:
7475 switch (FD->getTemplateSpecializationKind()) {
7476 case TSK_Undeclared:
7477 case TSK_ExplicitSpecialization:
7478 External = GVA_StrongExternal;
7479 break;
7480
7481 case TSK_ExplicitInstantiationDefinition:
7482 return GVA_ExplicitTemplateInstantiation;
7483
7484 case TSK_ExplicitInstantiationDeclaration:
7485 case TSK_ImplicitInstantiation:
7486 External = GVA_TemplateInstantiation;
7487 break;
7488 }
7489 }
7490
7491 if (!FD->isInlined())
7492 return External;
7493
David Blaikie4e4d0842012-03-11 07:00:24 +00007494 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007495 // GNU or C99 inline semantics. Determine whether this symbol should be
7496 // externally visible.
7497 if (FD->isInlineDefinitionExternallyVisible())
7498 return External;
7499
7500 // C99 inline semantics, where the symbol is not externally visible.
7501 return GVA_C99Inline;
7502 }
7503
7504 // C++0x [temp.explicit]p9:
7505 // [ Note: The intent is that an inline function that is the subject of
7506 // an explicit instantiation declaration will still be implicitly
7507 // instantiated when used so that the body can be considered for
7508 // inlining, but that no out-of-line copy of the inline function would be
7509 // generated in the translation unit. -- end note ]
7510 if (FD->getTemplateSpecializationKind()
7511 == TSK_ExplicitInstantiationDeclaration)
7512 return GVA_C99Inline;
7513
7514 return GVA_CXXInline;
7515}
7516
7517GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7518 // If this is a static data member, compute the kind of template
7519 // specialization. Otherwise, this variable is not part of a
7520 // template.
7521 TemplateSpecializationKind TSK = TSK_Undeclared;
7522 if (VD->isStaticDataMember())
7523 TSK = VD->getTemplateSpecializationKind();
7524
7525 Linkage L = VD->getLinkage();
Rafael Espindola62a833e2013-01-02 04:19:07 +00007526 assert (!(L == ExternalLinkage && getLangOpts().CPlusPlus &&
7527 VD->getType()->getLinkage() == UniqueExternalLinkage));
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007528
7529 switch (L) {
7530 case NoLinkage:
7531 case InternalLinkage:
7532 case UniqueExternalLinkage:
7533 return GVA_Internal;
7534
7535 case ExternalLinkage:
7536 switch (TSK) {
7537 case TSK_Undeclared:
7538 case TSK_ExplicitSpecialization:
7539 return GVA_StrongExternal;
7540
7541 case TSK_ExplicitInstantiationDeclaration:
7542 llvm_unreachable("Variable should not be instantiated");
7543 // Fall through to treat this like any other instantiation.
7544
7545 case TSK_ExplicitInstantiationDefinition:
7546 return GVA_ExplicitTemplateInstantiation;
7547
7548 case TSK_ImplicitInstantiation:
7549 return GVA_TemplateInstantiation;
7550 }
7551 }
7552
David Blaikie7530c032012-01-17 06:56:22 +00007553 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007554}
7555
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00007556bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007557 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7558 if (!VD->isFileVarDecl())
7559 return false;
Argyrios Kyrtzidis144b38a2011-09-13 21:35:00 +00007560 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007561 return false;
7562
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007563 // Weak references don't produce any output by themselves.
7564 if (D->hasAttr<WeakRefAttr>())
7565 return false;
7566
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007567 // Aliases and used decls are required.
7568 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7569 return true;
7570
7571 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7572 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00007573 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00007574 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007575
7576 // Constructors and destructors are required.
7577 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7578 return true;
7579
John McCalld5617ee2013-01-25 22:31:03 +00007580 // The key function for a class is required. This rule only comes
7581 // into play when inline functions can be key functions, though.
7582 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7583 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7584 const CXXRecordDecl *RD = MD->getParent();
7585 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7586 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7587 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7588 return true;
7589 }
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007590 }
7591 }
7592
7593 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7594
7595 // static, static inline, always_inline, and extern inline functions can
7596 // always be deferred. Normal inline functions can be deferred in C99/C++.
7597 // Implicit template instantiations can also be deferred in C++.
7598 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev3a5aca82012-02-02 06:06:34 +00007599 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007600 return false;
7601 return true;
7602 }
Douglas Gregor94da1582011-09-10 00:22:34 +00007603
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007604 const VarDecl *VD = cast<VarDecl>(D);
7605 assert(VD->isFileVarDecl() && "Expected file scoped var");
7606
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007607 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7608 return false;
7609
Richard Smith5f9a7e32012-11-12 21:38:00 +00007610 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007611 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smith5f9a7e32012-11-12 21:38:00 +00007612 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7613 return true;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007614
Richard Smith5f9a7e32012-11-12 21:38:00 +00007615 // Variables that have destruction with side-effects are required.
7616 if (VD->getType().isDestructedType())
7617 return true;
7618
7619 // Variables that have initialization with side-effects are required.
7620 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7621 return true;
7622
7623 return false;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007624}
Charles Davis071cc7d2010-08-16 03:33:14 +00007625
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007626CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davisee743f92010-11-09 18:04:24 +00007627 // Pass through to the C++ ABI object
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007628 return ABI->getDefaultMethodCallConv(isVariadic);
7629}
7630
7631CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
John McCallb8b2c9d2013-01-25 22:30:49 +00007632 if (CC == CC_C && !LangOpts.MRTD &&
7633 getTargetInfo().getCXXABI().isMemberFunctionCCDefault())
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007634 return CC_Default;
7635 return CC;
Charles Davisee743f92010-11-09 18:04:24 +00007636}
7637
Jay Foad4ba2a172011-01-12 09:06:06 +00007638bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00007639 // Pass through to the C++ ABI object
7640 return ABI->isNearlyEmpty(RD);
7641}
7642
Peter Collingbourne14110472011-01-13 18:57:25 +00007643MangleContext *ASTContext::createMangleContext() {
John McCallb8b2c9d2013-01-25 22:30:49 +00007644 switch (Target->getCXXABI().getKind()) {
7645 case TargetCXXABI::GenericItanium:
7646 case TargetCXXABI::GenericARM:
7647 case TargetCXXABI::iOS:
Peter Collingbourne14110472011-01-13 18:57:25 +00007648 return createItaniumMangleContext(*this, getDiagnostics());
John McCallb8b2c9d2013-01-25 22:30:49 +00007649 case TargetCXXABI::Microsoft:
Peter Collingbourne14110472011-01-13 18:57:25 +00007650 return createMicrosoftMangleContext(*this, getDiagnostics());
7651 }
David Blaikieb219cfc2011-09-23 05:06:16 +00007652 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00007653}
7654
Charles Davis071cc7d2010-08-16 03:33:14 +00007655CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00007656
7657size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00007658 return ASTRecordLayouts.getMemorySize()
7659 + llvm::capacity_in_bytes(ObjCLayouts)
7660 + llvm::capacity_in_bytes(KeyFunctions)
7661 + llvm::capacity_in_bytes(ObjCImpls)
7662 + llvm::capacity_in_bytes(BlockVarCopyInits)
7663 + llvm::capacity_in_bytes(DeclAttrs)
7664 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7665 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7666 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7667 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7668 + llvm::capacity_in_bytes(OverriddenMethods)
7669 + llvm::capacity_in_bytes(Types)
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007670 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet0d95f0d2011-08-14 14:28:49 +00007671 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00007672}
Ted Kremenekd211cb72011-10-06 05:00:56 +00007673
David Blaikie66cff722012-11-14 01:52:05 +00007674void ASTContext::addUnnamedTag(const TagDecl *Tag) {
7675 // FIXME: This mangling should be applied to function local classes too
7676 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl() ||
7677 !isa<CXXRecordDecl>(Tag->getParent()) || Tag->getLinkage() != ExternalLinkage)
7678 return;
7679
7680 std::pair<llvm::DenseMap<const DeclContext *, unsigned>::iterator, bool> P =
7681 UnnamedMangleContexts.insert(std::make_pair(Tag->getParent(), 0));
7682 UnnamedMangleNumbers.insert(std::make_pair(Tag, P.first->second++));
7683}
7684
7685int ASTContext::getUnnamedTagManglingNumber(const TagDecl *Tag) const {
7686 llvm::DenseMap<const TagDecl *, unsigned>::const_iterator I =
7687 UnnamedMangleNumbers.find(Tag);
7688 return I != UnnamedMangleNumbers.end() ? I->second : -1;
7689}
7690
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00007691unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7692 CXXRecordDecl *Lambda = CallOperator->getParent();
7693 return LambdaMangleContexts[Lambda->getDeclContext()]
7694 .getManglingNumber(CallOperator);
7695}
7696
7697
Ted Kremenekd211cb72011-10-06 05:00:56 +00007698void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7699 ParamIndices[D] = index;
7700}
7701
7702unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7703 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7704 assert(I != ParamIndices.end() &&
7705 "ParmIndices lacks entry set by ParmVarDecl");
7706 return I->second;
7707}