blob: eee7ed2fb8862942a585585da31ec0967ea8b899 [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CXXABI.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000018#include "clang/AST/CharUnits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000019#include "clang/AST/Comment.h"
Dmitri Gribenkoca7f80a2012-08-09 00:03:17 +000020#include "clang/AST/CommentCommandTraits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000021#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000022#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000023#include "clang/AST/DeclTemplate.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000024#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000026#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000027#include "clang/AST/Mangle.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000028#include "clang/AST/RecordLayout.h"
29#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000030#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000031#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000032#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000033#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000034#include "llvm/ADT/StringExtras.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000035#include "llvm/Support/Capacity.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000036#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000037#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000038#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000039
Chris Lattnerddc135e2006-11-10 06:34:16 +000040using namespace clang;
41
Douglas Gregor9672f922010-07-03 00:47:00 +000042unsigned ASTContext::NumImplicitDefaultConstructors;
43unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000044unsigned ASTContext::NumImplicitCopyConstructors;
45unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000046unsigned ASTContext::NumImplicitMoveConstructors;
47unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000048unsigned ASTContext::NumImplicitCopyAssignmentOperators;
49unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000050unsigned ASTContext::NumImplicitMoveAssignmentOperators;
51unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000052unsigned ASTContext::NumImplicitDestructors;
53unsigned ASTContext::NumImplicitDestructorsDeclared;
54
Steve Naroff0af91202007-04-27 21:51:21 +000055enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000056 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000057};
58
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000059RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000060 if (!CommentsLoaded && ExternalSource) {
61 ExternalSource->ReadComments();
62 CommentsLoaded = true;
63 }
64
65 assert(D);
66
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000067 // User can not attach documentation to implicit declarations.
68 if (D->isImplicit())
69 return NULL;
70
Dmitri Gribenkob2610882012-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 Gribenkob1ad9932012-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 Gribenko01b06512013-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 Gribenkob1ad9932012-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 Gribenkoaab83832012-06-20 00:34:58 +0000101 // TODO: handle comments for function parameters properly.
102 if (isa<ParmVarDecl>(D))
103 return NULL;
104
Dmitri Gribenko34df2202012-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 Gribenko7dd29d42012-07-06 18:19:34 +0000112 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-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 Gribenkoe7bb9442012-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 Gribenko34df2202012-07-31 22:37:06 +0000126 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000127 isa<RedeclarableTemplateDecl>(D) ||
128 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000129 DeclLoc = D->getLocStart();
130 else
131 DeclLoc = D->getLocation();
132
Dmitri Gribenkoaab83832012-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 Gribenkoaab83832012-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 Gribenko82ea9472012-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 Gribenkoaab83832012-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 Gribenko7dd29d42012-07-06 18:19:34 +0000170 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Dmitri Gribenko44cd7e62012-07-06 23:27:33 +0000171 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000172 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000173 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-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 Gribenko7dd29d42012-07-06 18:19:34 +0000180 return *Comment;
Dmitri Gribenkoaab83832012-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 Gribenko7dd29d42012-07-06 18:19:34 +0000191 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000192 return NULL;
193
194 // Decompose the end of the comment.
195 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000196 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-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 Gribenko7e8729b2012-06-27 23:43:37 +0000214 // There should be no other declarations or preprocessor directives between
215 // comment and declaration.
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000216 if (Text.find_first_of(",;{}#@") != StringRef::npos)
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000217 return NULL;
218
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000219 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000220}
221
Dmitri Gribenkob2610882012-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 Gribenko90631802012-08-22 17:44:32 +0000225/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000226const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000227 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000228 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000229 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-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 Gregor35ceb272012-08-13 16:37:30 +0000246 }
Dmitri Gribenko90631802012-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 Gribenkob2610882012-08-14 17:17:18 +0000291 return D;
292}
293} // unnamed namespace
294
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000295const RawComment *ASTContext::getRawCommentForAnyRedecl(
296 const Decl *D,
297 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000298 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000299
Dmitri Gribenkoa43ec182012-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 Gribenko4ae66a32012-08-16 18:19:43 +0000306 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
307 if (OriginalDecl)
308 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000309 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000310 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000311 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000312 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000313
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000314 // Search for comments attached to declarations in the redeclaration chain.
315 const RawComment *RC = NULL;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000316 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkoa43ec182012-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 Gribenko4ae66a32012-08-16 18:19:43 +0000326 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000327 break;
328 }
329 } else {
330 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000331 OriginalDeclForRC = *I;
Dmitri Gribenkoa43ec182012-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 Gribenko4ae66a32012-08-16 18:19:43 +0000338 Raw.setOriginalDecl(*I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000339 RedeclComments[*I] = Raw;
340 if (RC)
341 break;
342 }
343 }
344
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000345 // If we found a comment, it should be a documentation comment.
346 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000347
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000348 if (OriginalDecl)
349 *OriginalDecl = OriginalDeclForRC;
350
Dmitri Gribenkoa43ec182012-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 Gribenko4ae66a32012-08-16 18:19:43 +0000355 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-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 Gribenkoaab83832012-06-20 00:34:58 +0000365 return RC;
366}
367
Fariborz Jahanian1c883b92012-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 Gregor048fbfa2013-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 Jahanian1c883b92012-10-10 18:34:52 +0000380 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000381 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000382 ObjCMethod->isInstanceMethod()))
383 Redeclared.push_back(RedeclaredMethod);
384 }
385 }
386}
387
Fariborz Jahanian42e31322012-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 Gribenko6743e042012-09-29 11:40:46 +0000402comments::FullComment *ASTContext::getCommentForDecl(
403 const Decl *D,
404 const Preprocessor *PP) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000405 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000406
Dmitri Gribenkob2610882012-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 Jahanian1c883b92012-10-10 18:34:52 +0000410
411 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000412 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000413 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000414 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000415 return CFC;
416 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000417 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000418 }
419
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000420 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000421
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000422 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000423 if (!RC) {
424 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000425 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000426 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-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 Jahanian37494a12013-01-12 00:28:34 +0000431 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000432 addRedeclaredMethods(OMD, Overridden);
433 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-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 Jahanian1c883b92012-10-10 18:34:52 +0000437 }
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000438 else if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000439 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000440 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000441 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-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 Jahanian66024d02013-01-25 23:08:39 +0000445 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000446 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000447 return NULL;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000448 }
449
Dmitri Gribenkobfda9f72012-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 Gribenko4ae66a32012-08-16 18:19:43 +0000454 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000455 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000456
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000457 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000458 ParsedComments[Canonical] = FC;
459 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000460}
461
Douglas Gregor7dbfb462010-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 Gregorf5500772011-01-05 15:48:55 +0000467 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-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 Gregorf5500772011-01-05 15:48:55 +0000482 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000483 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000484 if (NTTP->isExpandedParameterPack()) {
485 ID.AddBoolean(true);
486 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-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 Gregor0231d8d2011-01-19 20:10:05 +0000491 } else
492 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-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 Foad39c79802011-01-12 09:06:06 +0000504 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-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 Lattner0e62c1c2011-07-23 10:55:15 +0000516 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-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 Bagnarab3185b02011-03-06 15:48:19 +0000524 SourceLocation(),
525 SourceLocation(),
526 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000527 TTP->getIndex(), 0, false,
528 TTP->isParameterPack()));
529 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-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 Lattner0e62c1c2011-07-23 10:55:15 +0000535 SmallVector<QualType, 2> ExpandedTypes;
536 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-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 Bagnaradff19302011-03-08 08:55:46 +0000544 SourceLocation(),
545 SourceLocation(),
Douglas Gregor0231d8d2011-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 Bagnaradff19302011-03-08 08:55:46 +0000555 SourceLocation(),
556 SourceLocation(),
Douglas Gregor0231d8d2011-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 Gregor7dbfb462010-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 Gregorf5500772011-01-05 15:48:55 +0000573 TTP->getPosition(),
574 TTP->isParameterPack(),
575 0,
Douglas Gregor7dbfb462010-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 Davis53c59df2010-08-16 03:33:14 +0000593CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000594 if (!LangOpts.CPlusPlus) return 0;
595
John McCall359b8852013-01-25 22:30:49 +0000596 switch (T.getCXXABI().getKind()) {
597 case TargetCXXABI::GenericARM:
598 case TargetCXXABI::iOS:
John McCall86353412010-08-21 22:46:04 +0000599 return CreateARMCXXABI(*this);
Tim Northover9bb857a2013-01-31 12:13:10 +0000600 case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000601 case TargetCXXABI::GenericItanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000602 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000603 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000604 return CreateMicrosoftCXXABI(*this);
605 }
David Blaikie8a40f702012-01-17 06:56:22 +0000606 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000607}
608
Douglas Gregore8bbc122011-09-02 00:18:52 +0000609static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000610 const LangOptions &LOpts) {
611 if (LOpts.FakeAddressSpaceMap) {
612 // The fake address space map must have a distinct entry for each
613 // language-specific address space.
614 static const unsigned FakeAddrSpaceMap[] = {
615 1, // opencl_global
616 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000617 3, // opencl_constant
618 4, // cuda_device
619 5, // cuda_constant
620 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000621 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000622 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000623 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000624 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000625 }
626}
627
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000628ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000629 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000630 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000631 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000632 unsigned size_reserve,
633 bool DelayInitialization)
634 : FunctionProtoTypes(this_()),
635 TemplateSpecializationTypes(this_()),
636 DependentTemplateSpecializationTypes(this_()),
637 SubstTemplateTemplateParmPacks(this_()),
638 GlobalNestedNameSpecifier(0),
639 Int128Decl(0), UInt128Decl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000640 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000641 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanianf2578572012-08-30 18:49:41 +0000642 BOOLDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000643 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000644 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000645 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
646 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
647 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000648 NullTypeSourceInfo(QualType()),
649 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000650 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000651 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000652 Idents(idents), Selectors(sels),
653 BuiltinInfo(builtins),
654 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000655 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000656 Comments(SM), CommentsLoaded(false),
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000657 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000658 LastSDM(0, 0),
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +0000659 UniqueBlockByRefTypeID(0)
Douglas Gregore8bbc122011-09-02 00:18:52 +0000660{
Mike Stump11289f42009-09-09 15:08:12 +0000661 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000662 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000663
664 if (!DelayInitialization) {
665 assert(t && "No target supplied for ASTContext initialization");
666 InitBuiltinTypes(*t);
667 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000668}
669
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000670ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000671 // Release the DenseMaps associated with DeclContext objects.
672 // FIXME: Is this the ideal solution?
673 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000674
Douglas Gregor5b11d492010-07-25 17:53:33 +0000675 // Call all of the deallocation functions.
676 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
677 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000678
Ted Kremenek076baeb2010-06-08 23:00:58 +0000679 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000680 // because they can contain DenseMaps.
681 for (llvm::DenseMap<const ObjCContainerDecl*,
682 const ASTRecordLayout*>::iterator
683 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
684 // Increment in loop to prevent using deallocated memory.
685 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
686 R->Destroy(*this);
687
Ted Kremenek076baeb2010-06-08 23:00:58 +0000688 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
689 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
690 // Increment in loop to prevent using deallocated memory.
691 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
692 R->Destroy(*this);
693 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000694
695 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
696 AEnd = DeclAttrs.end();
697 A != AEnd; ++A)
698 A->second->~AttrVec();
699}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000700
Douglas Gregor1a809332010-05-23 18:26:36 +0000701void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
702 Deallocations.push_back(std::make_pair(Callback, Data));
703}
704
Mike Stump11289f42009-09-09 15:08:12 +0000705void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000706ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000707 ExternalSource.reset(Source.take());
708}
709
Chris Lattner4eb445d2007-01-26 01:27:23 +0000710void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000711 llvm::errs() << "\n*** AST Context Stats:\n";
712 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000713
Douglas Gregora30d0462009-05-26 14:40:08 +0000714 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000715#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000716#define ABSTRACT_TYPE(Name, Parent)
717#include "clang/AST/TypeNodes.def"
718 0 // Extra
719 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000720
Chris Lattner4eb445d2007-01-26 01:27:23 +0000721 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
722 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000723 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000724 }
725
Douglas Gregora30d0462009-05-26 14:40:08 +0000726 unsigned Idx = 0;
727 unsigned TotalBytes = 0;
728#define TYPE(Name, Parent) \
729 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000730 llvm::errs() << " " << counts[Idx] << " " << #Name \
731 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000732 TotalBytes += counts[Idx] * sizeof(Name##Type); \
733 ++Idx;
734#define ABSTRACT_TYPE(Name, Parent)
735#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000736
Chandler Carruth3c147a72011-07-04 05:32:14 +0000737 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
738
Douglas Gregor7454c562010-07-02 20:37:36 +0000739 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000740 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
741 << NumImplicitDefaultConstructors
742 << " implicit default constructors created\n";
743 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
744 << NumImplicitCopyConstructors
745 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000746 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000747 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
748 << NumImplicitMoveConstructors
749 << " implicit move constructors created\n";
750 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
751 << NumImplicitCopyAssignmentOperators
752 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000753 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000754 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
755 << NumImplicitMoveAssignmentOperators
756 << " implicit move assignment operators created\n";
757 llvm::errs() << NumImplicitDestructorsDeclared << "/"
758 << NumImplicitDestructors
759 << " implicit destructors created\n";
760
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000761 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000762 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000763 ExternalSource->PrintStats();
764 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000765
Douglas Gregor5b11d492010-07-25 17:53:33 +0000766 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000767}
768
Douglas Gregor801c99d2011-08-12 06:49:56 +0000769TypedefDecl *ASTContext::getInt128Decl() const {
770 if (!Int128Decl) {
771 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
772 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
773 getTranslationUnitDecl(),
774 SourceLocation(),
775 SourceLocation(),
776 &Idents.get("__int128_t"),
777 TInfo);
778 }
779
780 return Int128Decl;
781}
782
783TypedefDecl *ASTContext::getUInt128Decl() const {
784 if (!UInt128Decl) {
785 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
786 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
787 getTranslationUnitDecl(),
788 SourceLocation(),
789 SourceLocation(),
790 &Idents.get("__uint128_t"),
791 TInfo);
792 }
793
794 return UInt128Decl;
795}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000796
John McCall48f2d582009-10-23 23:03:21 +0000797void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000798 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000799 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000800 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000801}
802
Douglas Gregore8bbc122011-09-02 00:18:52 +0000803void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
804 assert((!this->Target || this->Target == &Target) &&
805 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000806 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000807
Douglas Gregore8bbc122011-09-02 00:18:52 +0000808 this->Target = &Target;
809
810 ABI.reset(createCXXABI(Target));
811 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
812
Chris Lattner970e54e2006-11-12 00:37:36 +0000813 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000814 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000815
Chris Lattner970e54e2006-11-12 00:37:36 +0000816 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000817 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000818 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000819 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000820 InitBuiltinType(CharTy, BuiltinType::Char_S);
821 else
822 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000823 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000824 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
825 InitBuiltinType(ShortTy, BuiltinType::Short);
826 InitBuiltinType(IntTy, BuiltinType::Int);
827 InitBuiltinType(LongTy, BuiltinType::Long);
828 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000829
Chris Lattner970e54e2006-11-12 00:37:36 +0000830 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000831 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
832 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
833 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
834 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
835 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000836
Chris Lattner970e54e2006-11-12 00:37:36 +0000837 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000838 InitBuiltinType(FloatTy, BuiltinType::Float);
839 InitBuiltinType(DoubleTy, BuiltinType::Double);
840 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000841
Chris Lattnerf122cef2009-04-30 02:43:43 +0000842 // GNU extension, 128-bit integers.
843 InitBuiltinType(Int128Ty, BuiltinType::Int128);
844 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
845
Abramo Bagnara06782942012-09-09 10:13:32 +0000846 if (LangOpts.CPlusPlus && LangOpts.WChar) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000847 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000848 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
849 else // -fshort-wchar makes wchar_t be unsigned.
850 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
Abramo Bagnara06782942012-09-09 10:13:32 +0000851 } else // C99 (or C++ using -fno-wchar)
Chris Lattner007cb022009-02-26 23:43:47 +0000852 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000853
James Molloy36365542012-05-04 10:55:22 +0000854 WIntTy = getFromTargetType(Target.getWIntType());
855
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000856 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
857 InitBuiltinType(Char16Ty, BuiltinType::Char16);
858 else // C99
859 Char16Ty = getFromTargetType(Target.getChar16Type());
860
861 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
862 InitBuiltinType(Char32Ty, BuiltinType::Char32);
863 else // C99
864 Char32Ty = getFromTargetType(Target.getChar32Type());
865
Douglas Gregor4619e432008-12-05 23:32:09 +0000866 // Placeholder type for type-dependent expressions whose type is
867 // completely unknown. No code should ever check a type against
868 // DependentTy and users should never see it; however, it is here to
869 // help diagnose failures to properly check for type-dependent
870 // expressions.
871 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000872
John McCall36e7fe32010-10-12 00:20:44 +0000873 // Placeholder type for functions.
874 InitBuiltinType(OverloadTy, BuiltinType::Overload);
875
John McCall0009fcc2011-04-26 20:42:42 +0000876 // Placeholder type for bound members.
877 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
878
John McCall526ab472011-10-25 17:37:35 +0000879 // Placeholder type for pseudo-objects.
880 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
881
John McCall31996342011-04-07 08:22:57 +0000882 // "any" type; useful for debugger-like clients.
883 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
884
John McCall8a6b59a2011-10-17 18:09:15 +0000885 // Placeholder type for unbridged ARC casts.
886 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
887
Eli Friedman34866c72012-08-31 00:14:07 +0000888 // Placeholder type for builtin functions.
889 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
890
Chris Lattner970e54e2006-11-12 00:37:36 +0000891 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000892 FloatComplexTy = getComplexType(FloatTy);
893 DoubleComplexTy = getComplexType(DoubleTy);
894 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000895
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000896 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000897 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
898 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000899 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000900
901 if (LangOpts.OpenCL) {
902 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
903 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
904 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
905 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
906 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
907 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000908
Guy Benyei61054192013-02-07 10:55:47 +0000909 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000910 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000911 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000912
913 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000914 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
915 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000916
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000917 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +0000918
919 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000920
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000921 // void * type
922 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000923
924 // nullptr type (C++0x 2.14.7)
925 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000926
927 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
928 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +0000929
930 // Builtin type used to help define __builtin_va_list.
931 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +0000932}
933
David Blaikie9c902b52011-09-25 23:23:43 +0000934DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000935 return SourceMgr.getDiagnostics();
936}
937
Douglas Gregor561eceb2010-08-30 16:49:28 +0000938AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
939 AttrVec *&Result = DeclAttrs[D];
940 if (!Result) {
941 void *Mem = Allocate(sizeof(AttrVec));
942 Result = new (Mem) AttrVec;
943 }
944
945 return *Result;
946}
947
948/// \brief Erase the attributes corresponding to the given declaration.
949void ASTContext::eraseDeclAttrs(const Decl *D) {
950 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
951 if (Pos != DeclAttrs.end()) {
952 Pos->second->~AttrVec();
953 DeclAttrs.erase(Pos);
954 }
955}
956
Douglas Gregor86d142a2009-10-08 07:24:58 +0000957MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000958ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000959 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000960 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000961 = InstantiatedFromStaticDataMember.find(Var);
962 if (Pos == InstantiatedFromStaticDataMember.end())
963 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000964
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000965 return Pos->second;
966}
967
Mike Stump11289f42009-09-09 15:08:12 +0000968void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000969ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000970 TemplateSpecializationKind TSK,
971 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000972 assert(Inst->isStaticDataMember() && "Not a static data member");
973 assert(Tmpl->isStaticDataMember() && "Not a static data member");
974 assert(!InstantiatedFromStaticDataMember[Inst] &&
975 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000976 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000977 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000978}
979
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000980FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
981 const FunctionDecl *FD){
982 assert(FD && "Specialization is 0");
983 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000984 = ClassScopeSpecializationPattern.find(FD);
985 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000986 return 0;
987
988 return Pos->second;
989}
990
991void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
992 FunctionDecl *Pattern) {
993 assert(FD && "Specialization is 0");
994 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000995 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000996}
997
John McCalle61f2ba2009-11-18 02:36:19 +0000998NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000999ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001000 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001001 = InstantiatedFromUsingDecl.find(UUD);
1002 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001003 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001004
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001005 return Pos->second;
1006}
1007
1008void
John McCallb96ec562009-12-04 22:46:56 +00001009ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1010 assert((isa<UsingDecl>(Pattern) ||
1011 isa<UnresolvedUsingValueDecl>(Pattern) ||
1012 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1013 "pattern decl is not a using decl");
1014 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1015 InstantiatedFromUsingDecl[Inst] = Pattern;
1016}
1017
1018UsingShadowDecl *
1019ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1020 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1021 = InstantiatedFromUsingShadowDecl.find(Inst);
1022 if (Pos == InstantiatedFromUsingShadowDecl.end())
1023 return 0;
1024
1025 return Pos->second;
1026}
1027
1028void
1029ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1030 UsingShadowDecl *Pattern) {
1031 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1032 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001033}
1034
Anders Carlsson5da84842009-09-01 04:26:58 +00001035FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1036 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1037 = InstantiatedFromUnnamedFieldDecl.find(Field);
1038 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1039 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001040
Anders Carlsson5da84842009-09-01 04:26:58 +00001041 return Pos->second;
1042}
1043
1044void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1045 FieldDecl *Tmpl) {
1046 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1047 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1048 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1049 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001050
Anders Carlsson5da84842009-09-01 04:26:58 +00001051 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1052}
1053
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +00001054bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
1055 const FieldDecl *LastFD) const {
1056 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001057 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +00001058}
1059
Fariborz Jahanianeb397412011-05-02 17:20:56 +00001060bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
1061 const FieldDecl *LastFD) const {
1062 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001063 FD->getBitWidthValue(*this) == 0 &&
1064 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +00001065}
1066
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001067bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
1068 const FieldDecl *LastFD) const {
1069 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001070 FD->getBitWidthValue(*this) &&
1071 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001072}
1073
Chad Rosierf01a7dd2011-08-04 23:34:15 +00001074bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001075 const FieldDecl *LastFD) const {
1076 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001077 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001078}
1079
Chad Rosierf01a7dd2011-08-04 23:34:15 +00001080bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001081 const FieldDecl *LastFD) const {
1082 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001083 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001084}
1085
Douglas Gregor832940b2010-03-02 23:58:15 +00001086ASTContext::overridden_cxx_method_iterator
1087ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1088 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001089 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001090 if (Pos == OverriddenMethods.end())
1091 return 0;
1092
1093 return Pos->second.begin();
1094}
1095
1096ASTContext::overridden_cxx_method_iterator
1097ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1098 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001099 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001100 if (Pos == OverriddenMethods.end())
1101 return 0;
1102
1103 return Pos->second.end();
1104}
1105
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001106unsigned
1107ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1108 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001109 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001110 if (Pos == OverriddenMethods.end())
1111 return 0;
1112
1113 return Pos->second.size();
1114}
1115
Douglas Gregor832940b2010-03-02 23:58:15 +00001116void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1117 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001118 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001119 OverriddenMethods[Method].push_back(Overridden);
1120}
1121
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001122void ASTContext::getOverriddenMethods(
1123 const NamedDecl *D,
1124 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001125 assert(D);
1126
1127 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001128 Overridden.append(CXXMethod->begin_overridden_methods(),
1129 CXXMethod->end_overridden_methods());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001130 return;
1131 }
1132
1133 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1134 if (!Method)
1135 return;
1136
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001137 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1138 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001139 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001140}
1141
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001142void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1143 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1144 assert(!Import->isFromASTFile() && "Non-local import declaration");
1145 if (!FirstLocalImport) {
1146 FirstLocalImport = Import;
1147 LastLocalImport = Import;
1148 return;
1149 }
1150
1151 LastLocalImport->NextLocalImport = Import;
1152 LastLocalImport = Import;
1153}
1154
Chris Lattner53cfe802007-07-18 17:52:12 +00001155//===----------------------------------------------------------------------===//
1156// Type Sizing and Analysis
1157//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001158
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001159/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1160/// scalar floating point type.
1161const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001162 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001163 assert(BT && "Not a floating point type!");
1164 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001165 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001166 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001167 case BuiltinType::Float: return Target->getFloatFormat();
1168 case BuiltinType::Double: return Target->getDoubleFormat();
1169 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001170 }
1171}
1172
Ken Dyck160146e2010-01-27 17:10:57 +00001173/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +00001174/// specified decl. Note that bitfields do not have a valid alignment, so
1175/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001176/// If @p RefAsPointee, references are treated like their underlying type
1177/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +00001178CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001179 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001180
John McCall94268702010-10-08 18:24:19 +00001181 bool UseAlignAttrOnly = false;
1182 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1183 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001184
John McCall94268702010-10-08 18:24:19 +00001185 // __attribute__((aligned)) can increase or decrease alignment
1186 // *except* on a struct or struct member, where it only increases
1187 // alignment unless 'packed' is also specified.
1188 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001189 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001190 // ignore that possibility; Sema should diagnose it.
1191 if (isa<FieldDecl>(D)) {
1192 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1193 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1194 } else {
1195 UseAlignAttrOnly = true;
1196 }
1197 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001198 else if (isa<FieldDecl>(D))
1199 UseAlignAttrOnly =
1200 D->hasAttr<PackedAttr>() ||
1201 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001202
John McCall4e819612011-01-20 07:57:12 +00001203 // If we're using the align attribute only, just ignore everything
1204 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001205 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001206 // do nothing
1207
John McCall94268702010-10-08 18:24:19 +00001208 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001209 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001210 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001211 if (RefAsPointee)
1212 T = RT->getPointeeType();
1213 else
1214 T = getPointerType(RT->getPointeeType());
1215 }
1216 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001217 // Adjust alignments of declarations with array type by the
1218 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +00001219 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +00001220 const ArrayType *arrayType;
1221 if (MinWidth && (arrayType = getAsArrayType(T))) {
1222 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001223 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +00001224 else if (isa<ConstantArrayType>(arrayType) &&
1225 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001226 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +00001227
John McCall33ddac02011-01-19 10:06:00 +00001228 // Walk through any array types while we're at it.
1229 T = getBaseElementType(arrayType);
1230 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001231 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +00001232 }
John McCall4e819612011-01-20 07:57:12 +00001233
1234 // Fields can be subject to extra alignment constraints, like if
1235 // the field is packed, the struct is packed, or the struct has a
1236 // a max-field-alignment constraint (#pragma pack). So calculate
1237 // the actual alignment of the field within the struct, and then
1238 // (as we're expected to) constrain that by the alignment of the type.
1239 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1240 // So calculate the alignment of the field.
1241 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1242
1243 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +00001244 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001245
1246 // Use the GCD of that and the offset within the record.
1247 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1248 if (offset > 0) {
1249 // Alignment is always a power of 2, so the GCD will be a power of 2,
1250 // which means we get to do this crazy thing instead of Euclid's.
1251 uint64_t lowBitOfOffset = offset & (~offset + 1);
1252 if (lowBitOfOffset < fieldAlign)
1253 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1254 }
1255
1256 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +00001257 }
Chris Lattner68061312009-01-24 21:53:27 +00001258 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001259
Ken Dyckcc56c542011-01-15 18:38:59 +00001260 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001261}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001262
John McCallf1249922012-08-21 04:10:00 +00001263// getTypeInfoDataSizeInChars - Return the size of a type, in
1264// chars. If the type is a record, its data size is returned. This is
1265// the size of the memcpy that's performed when assigning this type
1266// using a trivial copy/move assignment operator.
1267std::pair<CharUnits, CharUnits>
1268ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1269 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1270
1271 // In C++, objects can sometimes be allocated into the tail padding
1272 // of a base-class subobject. We decide whether that's possible
1273 // during class layout, so here we can just trust the layout results.
1274 if (getLangOpts().CPlusPlus) {
1275 if (const RecordType *RT = T->getAs<RecordType>()) {
1276 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1277 sizeAndAlign.first = layout.getDataSize();
1278 }
1279 }
1280
1281 return sizeAndAlign;
1282}
1283
John McCall87fe5d52010-05-20 01:18:31 +00001284std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001285ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001286 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +00001287 return std::make_pair(toCharUnitsFromBits(Info.first),
1288 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +00001289}
1290
1291std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001292ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001293 return getTypeInfoInChars(T.getTypePtr());
1294}
1295
Daniel Dunbarc6475872012-03-09 04:12:54 +00001296std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1297 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1298 if (it != MemoizedTypeInfo.end())
1299 return it->second;
1300
1301 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1302 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1303 return Info;
1304}
1305
1306/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1307/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001308///
1309/// FIXME: Pointers into different addr spaces could have different sizes and
1310/// alignment requirements: getPointerInfo should take an AddrSpace, this
1311/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001312std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001313ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001314 uint64_t Width=0;
1315 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001316 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001317#define TYPE(Class, Base)
1318#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001319#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001320#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1321#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001322 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001323
Chris Lattner355332d2007-07-13 22:27:08 +00001324 case Type::FunctionNoProto:
1325 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001326 // GCC extension: alignof(function) = 32 bits
1327 Width = 0;
1328 Align = 32;
1329 break;
1330
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001331 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001332 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001333 Width = 0;
1334 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1335 break;
1336
Steve Naroff5c131802007-08-30 01:06:46 +00001337 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001338 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001339
Chris Lattner37e05872008-03-05 18:54:05 +00001340 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001341 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001342 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1343 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001344 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001345 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +00001346 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001347 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001348 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001349 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001350 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001351 const VectorType *VT = cast<VectorType>(T);
1352 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1353 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001354 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001355 // If the alignment is not a power of 2, round up to the next power of 2.
1356 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001357 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001358 Align = llvm::NextPowerOf2(Align);
1359 Width = llvm::RoundUpToAlignment(Width, Align);
1360 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001361 // Adjust the alignment based on the target max.
1362 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1363 if (TargetVectorAlign && TargetVectorAlign < Align)
1364 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001365 break;
1366 }
Chris Lattner647fb222007-07-18 18:26:58 +00001367
Chris Lattner7570e9c2008-03-08 08:52:55 +00001368 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001369 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001370 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001371 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001372 // GCC extension: alignof(void) = 8 bits.
1373 Width = 0;
1374 Align = 8;
1375 break;
1376
Chris Lattner6a4f7452007-12-19 19:23:28 +00001377 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001378 Width = Target->getBoolWidth();
1379 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001380 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001381 case BuiltinType::Char_S:
1382 case BuiltinType::Char_U:
1383 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001384 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001385 Width = Target->getCharWidth();
1386 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001387 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001388 case BuiltinType::WChar_S:
1389 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001390 Width = Target->getWCharWidth();
1391 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001392 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001393 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001394 Width = Target->getChar16Width();
1395 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001396 break;
1397 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001398 Width = Target->getChar32Width();
1399 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001400 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001401 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001402 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001403 Width = Target->getShortWidth();
1404 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001405 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001406 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001407 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001408 Width = Target->getIntWidth();
1409 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001410 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001411 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001412 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001413 Width = Target->getLongWidth();
1414 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001415 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001416 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001417 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001418 Width = Target->getLongLongWidth();
1419 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001420 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001421 case BuiltinType::Int128:
1422 case BuiltinType::UInt128:
1423 Width = 128;
1424 Align = 128; // int128_t is 128-bit aligned on all targets.
1425 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001426 case BuiltinType::Half:
1427 Width = Target->getHalfWidth();
1428 Align = Target->getHalfAlign();
1429 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001430 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001431 Width = Target->getFloatWidth();
1432 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001433 break;
1434 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001435 Width = Target->getDoubleWidth();
1436 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001437 break;
1438 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001439 Width = Target->getLongDoubleWidth();
1440 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001441 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001442 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001443 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1444 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001445 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001446 case BuiltinType::ObjCId:
1447 case BuiltinType::ObjCClass:
1448 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001449 Width = Target->getPointerWidth(0);
1450 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001451 break;
Guy Benyei61054192013-02-07 10:55:47 +00001452 case BuiltinType::OCLSampler:
1453 // Samplers are modeled as integers.
1454 Width = Target->getIntWidth();
1455 Align = Target->getIntAlign();
1456 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001457 case BuiltinType::OCLEvent:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001458 case BuiltinType::OCLImage1d:
1459 case BuiltinType::OCLImage1dArray:
1460 case BuiltinType::OCLImage1dBuffer:
1461 case BuiltinType::OCLImage2d:
1462 case BuiltinType::OCLImage2dArray:
1463 case BuiltinType::OCLImage3d:
1464 // Currently these types are pointers to opaque types.
1465 Width = Target->getPointerWidth(0);
1466 Align = Target->getPointerAlign(0);
1467 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001468 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001469 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001470 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001471 Width = Target->getPointerWidth(0);
1472 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001473 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001474 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001475 unsigned AS = getTargetAddressSpace(
1476 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001477 Width = Target->getPointerWidth(AS);
1478 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001479 break;
1480 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001481 case Type::LValueReference:
1482 case Type::RValueReference: {
1483 // alignof and sizeof should never enter this code path here, so we go
1484 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001485 unsigned AS = getTargetAddressSpace(
1486 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001487 Width = Target->getPointerWidth(AS);
1488 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001489 break;
1490 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001491 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001492 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001493 Width = Target->getPointerWidth(AS);
1494 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001495 break;
1496 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001497 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001498 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001499 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +00001500 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +00001501 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001502 Align = PtrDiffInfo.second;
1503 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001504 }
Chris Lattner647fb222007-07-18 18:26:58 +00001505 case Type::Complex: {
1506 // Complex types have the same alignment as their elements, but twice the
1507 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001508 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001509 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001510 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001511 Align = EltInfo.second;
1512 break;
1513 }
John McCall8b07ec22010-05-15 11:32:37 +00001514 case Type::ObjCObject:
1515 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001516 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001517 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001518 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001519 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001520 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001521 break;
1522 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001523 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001524 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001525 const TagType *TT = cast<TagType>(T);
1526
1527 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001528 Width = 8;
1529 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001530 break;
1531 }
Mike Stump11289f42009-09-09 15:08:12 +00001532
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001533 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001534 return getTypeInfo(ET->getDecl()->getIntegerType());
1535
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001536 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001537 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001538 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001539 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001540 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001541 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001542
Chris Lattner63d2b362009-10-22 05:17:15 +00001543 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001544 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1545 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001546
Richard Smith30482bc2011-02-20 03:19:35 +00001547 case Type::Auto: {
1548 const AutoType *A = cast<AutoType>(T);
1549 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001550 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001551 }
1552
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001553 case Type::Paren:
1554 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1555
Douglas Gregoref462e62009-04-30 17:32:17 +00001556 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001557 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001558 std::pair<uint64_t, unsigned> Info
1559 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001560 // If the typedef has an aligned attribute on it, it overrides any computed
1561 // alignment we have. This violates the GCC documentation (which says that
1562 // attribute(aligned) can only round up) but matches its implementation.
1563 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1564 Align = AttrAlign;
1565 else
1566 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001567 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001568 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001569 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001570
1571 case Type::TypeOfExpr:
1572 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1573 .getTypePtr());
1574
1575 case Type::TypeOf:
1576 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1577
Anders Carlsson81df7b82009-06-24 19:06:50 +00001578 case Type::Decltype:
1579 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1580 .getTypePtr());
1581
Alexis Hunte852b102011-05-24 22:41:36 +00001582 case Type::UnaryTransform:
1583 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1584
Abramo Bagnara6150c882010-05-11 21:36:43 +00001585 case Type::Elaborated:
1586 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001587
John McCall81904512011-01-06 01:58:22 +00001588 case Type::Attributed:
1589 return getTypeInfo(
1590 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1591
Richard Smith3f1b5d02011-05-05 21:57:07 +00001592 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001593 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001594 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001595 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1596 // A type alias template specialization may refer to a typedef with the
1597 // aligned attribute on it.
1598 if (TST->isTypeAlias())
1599 return getTypeInfo(TST->getAliasedType().getTypePtr());
1600 else
1601 return getTypeInfo(getCanonicalType(T));
1602 }
1603
Eli Friedman0dfb8892011-10-06 23:00:33 +00001604 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001605 // Start with the base type information.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001606 std::pair<uint64_t, unsigned> Info
1607 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1608 Width = Info.first;
1609 Align = Info.second;
John McCalla8ec7eb2013-03-07 21:37:17 +00001610
1611 // If the size of the type doesn't exceed the platform's max
1612 // atomic promotion width, make the size and alignment more
1613 // favorable to atomic operations:
1614 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1615 // Round the size up to a power of 2.
1616 if (!llvm::isPowerOf2_64(Width))
1617 Width = llvm::NextPowerOf2(Width);
1618
1619 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001620 Align = static_cast<unsigned>(Width);
1621 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001622 }
1623
Douglas Gregoref462e62009-04-30 17:32:17 +00001624 }
Mike Stump11289f42009-09-09 15:08:12 +00001625
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001626 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001627 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001628}
1629
Ken Dyckcc56c542011-01-15 18:38:59 +00001630/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1631CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1632 return CharUnits::fromQuantity(BitSize / getCharWidth());
1633}
1634
Ken Dyckb0fcc592011-02-11 01:54:29 +00001635/// toBits - Convert a size in characters to a size in characters.
1636int64_t ASTContext::toBits(CharUnits CharSize) const {
1637 return CharSize.getQuantity() * getCharWidth();
1638}
1639
Ken Dyck8c89d592009-12-22 14:23:30 +00001640/// getTypeSizeInChars - Return the size of the specified type, in characters.
1641/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001642CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001643 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001644}
Jay Foad39c79802011-01-12 09:06:06 +00001645CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001646 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001647}
1648
Ken Dycka6046ab2010-01-26 17:25:18 +00001649/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001650/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001651CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001652 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001653}
Jay Foad39c79802011-01-12 09:06:06 +00001654CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001655 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001656}
1657
Chris Lattnera3402cd2009-01-27 18:08:34 +00001658/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1659/// type for the current target in bits. This can be different than the ABI
1660/// alignment in cases where it is beneficial for performance to overalign
1661/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001662unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001663 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001664
1665 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001666 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001667 T = CT->getElementType().getTypePtr();
1668 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001669 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1670 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001671 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1672
Chris Lattnera3402cd2009-01-27 18:08:34 +00001673 return ABIAlign;
1674}
1675
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001676/// DeepCollectObjCIvars -
1677/// This routine first collects all declared, but not synthesized, ivars in
1678/// super class and then collects all ivars, including those synthesized for
1679/// current class. This routine is used for implementation of current class
1680/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001681///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001682void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1683 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001684 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001685 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1686 DeepCollectObjCIvars(SuperClass, false, Ivars);
1687 if (!leafClass) {
1688 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1689 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001690 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001691 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001692 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001693 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001694 Iv= Iv->getNextIvar())
1695 Ivars.push_back(Iv);
1696 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001697}
1698
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001699/// CollectInheritedProtocols - Collect all protocols in current class and
1700/// those inherited by it.
1701void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001702 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001703 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001704 // We can use protocol_iterator here instead of
1705 // all_referenced_protocol_iterator since we are walking all categories.
1706 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1707 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001708 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001709 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001710 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001711 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001712 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001713 CollectInheritedProtocols(*P, Protocols);
1714 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001715 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001716
1717 // Categories of this Interface.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001718 for (ObjCInterfaceDecl::visible_categories_iterator
1719 Cat = OI->visible_categories_begin(),
1720 CatEnd = OI->visible_categories_end();
1721 Cat != CatEnd; ++Cat) {
1722 CollectInheritedProtocols(*Cat, Protocols);
1723 }
1724
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001725 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1726 while (SD) {
1727 CollectInheritedProtocols(SD, Protocols);
1728 SD = SD->getSuperClass();
1729 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001730 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001731 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001732 PE = OC->protocol_end(); P != PE; ++P) {
1733 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001734 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001735 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1736 PE = Proto->protocol_end(); P != PE; ++P)
1737 CollectInheritedProtocols(*P, Protocols);
1738 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001739 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001740 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1741 PE = OP->protocol_end(); P != PE; ++P) {
1742 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001743 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001744 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1745 PE = Proto->protocol_end(); P != PE; ++P)
1746 CollectInheritedProtocols(*P, Protocols);
1747 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001748 }
1749}
1750
Jay Foad39c79802011-01-12 09:06:06 +00001751unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001752 unsigned count = 0;
1753 // Count ivars declared in class extension.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001754 for (ObjCInterfaceDecl::known_extensions_iterator
1755 Ext = OI->known_extensions_begin(),
1756 ExtEnd = OI->known_extensions_end();
1757 Ext != ExtEnd; ++Ext) {
1758 count += Ext->ivar_size();
1759 }
1760
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001761 // Count ivar defined in this class's implementation. This
1762 // includes synthesized ivars.
1763 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001764 count += ImplDecl->ivar_size();
1765
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001766 return count;
1767}
1768
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001769bool ASTContext::isSentinelNullExpr(const Expr *E) {
1770 if (!E)
1771 return false;
1772
1773 // nullptr_t is always treated as null.
1774 if (E->getType()->isNullPtrType()) return true;
1775
1776 if (E->getType()->isAnyPointerType() &&
1777 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1778 Expr::NPC_ValueDependentIsNull))
1779 return true;
1780
1781 // Unfortunately, __null has type 'int'.
1782 if (isa<GNUNullExpr>(E)) return true;
1783
1784 return false;
1785}
1786
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001787/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1788ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1789 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1790 I = ObjCImpls.find(D);
1791 if (I != ObjCImpls.end())
1792 return cast<ObjCImplementationDecl>(I->second);
1793 return 0;
1794}
1795/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1796ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1797 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1798 I = ObjCImpls.find(D);
1799 if (I != ObjCImpls.end())
1800 return cast<ObjCCategoryImplDecl>(I->second);
1801 return 0;
1802}
1803
1804/// \brief Set the implementation of ObjCInterfaceDecl.
1805void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1806 ObjCImplementationDecl *ImplD) {
1807 assert(IFaceD && ImplD && "Passed null params");
1808 ObjCImpls[IFaceD] = ImplD;
1809}
1810/// \brief Set the implementation of ObjCCategoryDecl.
1811void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1812 ObjCCategoryImplDecl *ImplD) {
1813 assert(CatD && ImplD && "Passed null params");
1814 ObjCImpls[CatD] = ImplD;
1815}
1816
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001817const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1818 const NamedDecl *ND) const {
1819 if (const ObjCInterfaceDecl *ID =
1820 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001821 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001822 if (const ObjCCategoryDecl *CD =
1823 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001824 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001825 if (const ObjCImplDecl *IMD =
1826 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001827 return IMD->getClassInterface();
1828
1829 return 0;
1830}
1831
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001832/// \brief Get the copy initialization expression of VarDecl,or NULL if
1833/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001834Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001835 assert(VD && "Passed null params");
1836 assert(VD->hasAttr<BlocksAttr>() &&
1837 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001838 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001839 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001840 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1841}
1842
1843/// \brief Set the copy inialization expression of a block var decl.
1844void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1845 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001846 assert(VD->hasAttr<BlocksAttr>() &&
1847 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001848 BlockVarCopyInits[VD] = Init;
1849}
1850
John McCallbcd03502009-12-07 02:54:59 +00001851TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001852 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001853 if (!DataSize)
1854 DataSize = TypeLoc::getFullDataSizeForType(T);
1855 else
1856 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001857 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001858
John McCallbcd03502009-12-07 02:54:59 +00001859 TypeSourceInfo *TInfo =
1860 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1861 new (TInfo) TypeSourceInfo(T);
1862 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001863}
1864
John McCallbcd03502009-12-07 02:54:59 +00001865TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001866 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001867 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001868 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001869 return DI;
1870}
1871
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001872const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001873ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001874 return getObjCLayout(D, 0);
1875}
1876
1877const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001878ASTContext::getASTObjCImplementationLayout(
1879 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001880 return getObjCLayout(D->getClassInterface(), D);
1881}
1882
Chris Lattner983a8bb2007-07-13 22:13:22 +00001883//===----------------------------------------------------------------------===//
1884// Type creation/memoization methods
1885//===----------------------------------------------------------------------===//
1886
Jay Foad39c79802011-01-12 09:06:06 +00001887QualType
John McCall33ddac02011-01-19 10:06:00 +00001888ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1889 unsigned fastQuals = quals.getFastQualifiers();
1890 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001891
1892 // Check if we've already instantiated this type.
1893 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001894 ExtQuals::Profile(ID, baseType, quals);
1895 void *insertPos = 0;
1896 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1897 assert(eq->getQualifiers() == quals);
1898 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001899 }
1900
John McCall33ddac02011-01-19 10:06:00 +00001901 // If the base type is not canonical, make the appropriate canonical type.
1902 QualType canon;
1903 if (!baseType->isCanonicalUnqualified()) {
1904 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001905 canonSplit.Quals.addConsistentQualifiers(quals);
1906 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001907
1908 // Re-find the insert position.
1909 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1910 }
1911
1912 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1913 ExtQualNodes.InsertNode(eq, insertPos);
1914 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001915}
1916
Jay Foad39c79802011-01-12 09:06:06 +00001917QualType
1918ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001919 QualType CanT = getCanonicalType(T);
1920 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001921 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001922
John McCall8ccfcb52009-09-24 19:53:00 +00001923 // If we are composing extended qualifiers together, merge together
1924 // into one ExtQuals node.
1925 QualifierCollector Quals;
1926 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001927
John McCall8ccfcb52009-09-24 19:53:00 +00001928 // If this type already has an address space specified, it cannot get
1929 // another one.
1930 assert(!Quals.hasAddressSpace() &&
1931 "Type cannot be in multiple addr spaces!");
1932 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001933
John McCall8ccfcb52009-09-24 19:53:00 +00001934 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001935}
1936
Chris Lattnerd60183d2009-02-18 22:53:11 +00001937QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001938 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001939 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001940 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001941 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001942
John McCall53fa7142010-12-24 02:08:15 +00001943 if (const PointerType *ptr = T->getAs<PointerType>()) {
1944 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001945 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001946 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1947 return getPointerType(ResultType);
1948 }
1949 }
Mike Stump11289f42009-09-09 15:08:12 +00001950
John McCall8ccfcb52009-09-24 19:53:00 +00001951 // If we are composing extended qualifiers together, merge together
1952 // into one ExtQuals node.
1953 QualifierCollector Quals;
1954 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001955
John McCall8ccfcb52009-09-24 19:53:00 +00001956 // If this type already has an ObjCGC specified, it cannot get
1957 // another one.
1958 assert(!Quals.hasObjCGCAttr() &&
1959 "Type cannot have multiple ObjCGCs!");
1960 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001961
John McCall8ccfcb52009-09-24 19:53:00 +00001962 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001963}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001964
John McCall4f5019e2010-12-19 02:44:49 +00001965const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1966 FunctionType::ExtInfo Info) {
1967 if (T->getExtInfo() == Info)
1968 return T;
1969
1970 QualType Result;
1971 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1972 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1973 } else {
1974 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1975 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1976 EPI.ExtInfo = Info;
Jordan Rose5c382722013-03-08 21:51:21 +00001977 Result = getFunctionType(FPT->getResultType(),
1978 ArrayRef<QualType>(FPT->arg_type_begin(),
1979 FPT->getNumArgs()),
1980 EPI);
John McCall4f5019e2010-12-19 02:44:49 +00001981 }
1982
1983 return cast<FunctionType>(Result.getTypePtr());
1984}
1985
Chris Lattnerc6395932007-06-22 20:56:16 +00001986/// getComplexType - Return the uniqued reference to the type for a complex
1987/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001988QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001989 // Unique pointers, to guarantee there is only one pointer of a particular
1990 // structure.
1991 llvm::FoldingSetNodeID ID;
1992 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001993
Chris Lattnerc6395932007-06-22 20:56:16 +00001994 void *InsertPos = 0;
1995 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1996 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001997
Chris Lattnerc6395932007-06-22 20:56:16 +00001998 // If the pointee type isn't canonical, this won't be a canonical type either,
1999 // so fill in the canonical type field.
2000 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002001 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002002 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002003
Chris Lattnerc6395932007-06-22 20:56:16 +00002004 // Get the new insert position for the node we care about.
2005 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002006 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002007 }
John McCall90d1c2d2009-09-24 23:30:46 +00002008 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002009 Types.push_back(New);
2010 ComplexTypes.InsertNode(New, InsertPos);
2011 return QualType(New, 0);
2012}
2013
Chris Lattner970e54e2006-11-12 00:37:36 +00002014/// getPointerType - Return the uniqued reference to the type for a pointer to
2015/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002016QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002017 // Unique pointers, to guarantee there is only one pointer of a particular
2018 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002019 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002020 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002021
Chris Lattner67521df2007-01-27 01:29:36 +00002022 void *InsertPos = 0;
2023 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002024 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002025
Chris Lattner7ccecb92006-11-12 08:50:50 +00002026 // If the pointee type isn't canonical, this won't be a canonical type either,
2027 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002028 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002029 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002030 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002031
Bob Wilsonc8541f22013-03-15 17:12:43 +00002032 // Get the new insert position for the node we care about.
2033 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2034 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2035 }
John McCall90d1c2d2009-09-24 23:30:46 +00002036 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002037 Types.push_back(New);
2038 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002039 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002040}
2041
Mike Stump11289f42009-09-09 15:08:12 +00002042/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002043/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002044QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002045 assert(T->isFunctionType() && "block of function types only");
2046 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002047 // structure.
2048 llvm::FoldingSetNodeID ID;
2049 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002050
Steve Naroffec33ed92008-08-27 16:04:49 +00002051 void *InsertPos = 0;
2052 if (BlockPointerType *PT =
2053 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2054 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002055
2056 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002057 // type either so fill in the canonical type field.
2058 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002059 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002060 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002061
Steve Naroffec33ed92008-08-27 16:04:49 +00002062 // Get the new insert position for the node we care about.
2063 BlockPointerType *NewIP =
2064 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002065 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002066 }
John McCall90d1c2d2009-09-24 23:30:46 +00002067 BlockPointerType *New
2068 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002069 Types.push_back(New);
2070 BlockPointerTypes.InsertNode(New, InsertPos);
2071 return QualType(New, 0);
2072}
2073
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002074/// getLValueReferenceType - Return the uniqued reference to the type for an
2075/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002076QualType
2077ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002078 assert(getCanonicalType(T) != OverloadTy &&
2079 "Unresolved overloaded function type");
2080
Bill Wendling3708c182007-05-27 10:15:43 +00002081 // Unique pointers, to guarantee there is only one pointer of a particular
2082 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002083 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002084 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002085
2086 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002087 if (LValueReferenceType *RT =
2088 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002089 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002090
John McCallfc93cf92009-10-22 22:37:11 +00002091 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2092
Bill Wendling3708c182007-05-27 10:15:43 +00002093 // If the referencee type isn't canonical, this won't be a canonical type
2094 // either, so fill in the canonical type field.
2095 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002096 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2097 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2098 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002099
Bill Wendling3708c182007-05-27 10:15:43 +00002100 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002101 LValueReferenceType *NewIP =
2102 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002103 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002104 }
2105
John McCall90d1c2d2009-09-24 23:30:46 +00002106 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002107 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2108 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002109 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002110 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002111
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002112 return QualType(New, 0);
2113}
2114
2115/// getRValueReferenceType - Return the uniqued reference to the type for an
2116/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002117QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002118 // Unique pointers, to guarantee there is only one pointer of a particular
2119 // structure.
2120 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002121 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002122
2123 void *InsertPos = 0;
2124 if (RValueReferenceType *RT =
2125 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2126 return QualType(RT, 0);
2127
John McCallfc93cf92009-10-22 22:37:11 +00002128 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2129
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002130 // If the referencee type isn't canonical, this won't be a canonical type
2131 // either, so fill in the canonical type field.
2132 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002133 if (InnerRef || !T.isCanonical()) {
2134 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2135 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002136
2137 // Get the new insert position for the node we care about.
2138 RValueReferenceType *NewIP =
2139 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002140 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002141 }
2142
John McCall90d1c2d2009-09-24 23:30:46 +00002143 RValueReferenceType *New
2144 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002145 Types.push_back(New);
2146 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002147 return QualType(New, 0);
2148}
2149
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002150/// getMemberPointerType - Return the uniqued reference to the type for a
2151/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002152QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002153 // Unique pointers, to guarantee there is only one pointer of a particular
2154 // structure.
2155 llvm::FoldingSetNodeID ID;
2156 MemberPointerType::Profile(ID, T, Cls);
2157
2158 void *InsertPos = 0;
2159 if (MemberPointerType *PT =
2160 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2161 return QualType(PT, 0);
2162
2163 // If the pointee or class type isn't canonical, this won't be a canonical
2164 // type either, so fill in the canonical type field.
2165 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002166 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002167 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2168
2169 // Get the new insert position for the node we care about.
2170 MemberPointerType *NewIP =
2171 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002172 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002173 }
John McCall90d1c2d2009-09-24 23:30:46 +00002174 MemberPointerType *New
2175 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002176 Types.push_back(New);
2177 MemberPointerTypes.InsertNode(New, InsertPos);
2178 return QualType(New, 0);
2179}
2180
Mike Stump11289f42009-09-09 15:08:12 +00002181/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002182/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002183QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002184 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002185 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002186 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002187 assert((EltTy->isDependentType() ||
2188 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002189 "Constant array of VLAs is illegal!");
2190
Chris Lattnere2df3f92009-05-13 04:12:56 +00002191 // Convert the array size into a canonical width matching the pointer size for
2192 // the target.
2193 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002194 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002195 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002196
Chris Lattner23b7eb62007-06-15 23:05:46 +00002197 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002198 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002199
Chris Lattner36f8e652007-01-27 08:31:04 +00002200 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002201 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002202 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002203 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002204
John McCall33ddac02011-01-19 10:06:00 +00002205 // If the element type isn't canonical or has qualifiers, this won't
2206 // be a canonical type either, so fill in the canonical type field.
2207 QualType Canon;
2208 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2209 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002210 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002211 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002212 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002213
Chris Lattner36f8e652007-01-27 08:31:04 +00002214 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002215 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002216 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002217 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002218 }
Mike Stump11289f42009-09-09 15:08:12 +00002219
John McCall90d1c2d2009-09-24 23:30:46 +00002220 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002221 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002222 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002223 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002224 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002225}
2226
John McCall06549462011-01-18 08:40:38 +00002227/// getVariableArrayDecayedType - Turns the given type, which may be
2228/// variably-modified, into the corresponding type with all the known
2229/// sizes replaced with [*].
2230QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2231 // Vastly most common case.
2232 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002233
John McCall06549462011-01-18 08:40:38 +00002234 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002235
John McCall06549462011-01-18 08:40:38 +00002236 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002237 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002238 switch (ty->getTypeClass()) {
2239#define TYPE(Class, Base)
2240#define ABSTRACT_TYPE(Class, Base)
2241#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2242#include "clang/AST/TypeNodes.def"
2243 llvm_unreachable("didn't desugar past all non-canonical types?");
2244
2245 // These types should never be variably-modified.
2246 case Type::Builtin:
2247 case Type::Complex:
2248 case Type::Vector:
2249 case Type::ExtVector:
2250 case Type::DependentSizedExtVector:
2251 case Type::ObjCObject:
2252 case Type::ObjCInterface:
2253 case Type::ObjCObjectPointer:
2254 case Type::Record:
2255 case Type::Enum:
2256 case Type::UnresolvedUsing:
2257 case Type::TypeOfExpr:
2258 case Type::TypeOf:
2259 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002260 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002261 case Type::DependentName:
2262 case Type::InjectedClassName:
2263 case Type::TemplateSpecialization:
2264 case Type::DependentTemplateSpecialization:
2265 case Type::TemplateTypeParm:
2266 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002267 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002268 case Type::PackExpansion:
2269 llvm_unreachable("type should never be variably-modified");
2270
2271 // These types can be variably-modified but should never need to
2272 // further decay.
2273 case Type::FunctionNoProto:
2274 case Type::FunctionProto:
2275 case Type::BlockPointer:
2276 case Type::MemberPointer:
2277 return type;
2278
2279 // These types can be variably-modified. All these modifications
2280 // preserve structure except as noted by comments.
2281 // TODO: if we ever care about optimizing VLAs, there are no-op
2282 // optimizations available here.
2283 case Type::Pointer:
2284 result = getPointerType(getVariableArrayDecayedType(
2285 cast<PointerType>(ty)->getPointeeType()));
2286 break;
2287
2288 case Type::LValueReference: {
2289 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2290 result = getLValueReferenceType(
2291 getVariableArrayDecayedType(lv->getPointeeType()),
2292 lv->isSpelledAsLValue());
2293 break;
2294 }
2295
2296 case Type::RValueReference: {
2297 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2298 result = getRValueReferenceType(
2299 getVariableArrayDecayedType(lv->getPointeeType()));
2300 break;
2301 }
2302
Eli Friedman0dfb8892011-10-06 23:00:33 +00002303 case Type::Atomic: {
2304 const AtomicType *at = cast<AtomicType>(ty);
2305 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2306 break;
2307 }
2308
John McCall06549462011-01-18 08:40:38 +00002309 case Type::ConstantArray: {
2310 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2311 result = getConstantArrayType(
2312 getVariableArrayDecayedType(cat->getElementType()),
2313 cat->getSize(),
2314 cat->getSizeModifier(),
2315 cat->getIndexTypeCVRQualifiers());
2316 break;
2317 }
2318
2319 case Type::DependentSizedArray: {
2320 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2321 result = getDependentSizedArrayType(
2322 getVariableArrayDecayedType(dat->getElementType()),
2323 dat->getSizeExpr(),
2324 dat->getSizeModifier(),
2325 dat->getIndexTypeCVRQualifiers(),
2326 dat->getBracketsRange());
2327 break;
2328 }
2329
2330 // Turn incomplete types into [*] types.
2331 case Type::IncompleteArray: {
2332 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2333 result = getVariableArrayType(
2334 getVariableArrayDecayedType(iat->getElementType()),
2335 /*size*/ 0,
2336 ArrayType::Normal,
2337 iat->getIndexTypeCVRQualifiers(),
2338 SourceRange());
2339 break;
2340 }
2341
2342 // Turn VLA types into [*] types.
2343 case Type::VariableArray: {
2344 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2345 result = getVariableArrayType(
2346 getVariableArrayDecayedType(vat->getElementType()),
2347 /*size*/ 0,
2348 ArrayType::Star,
2349 vat->getIndexTypeCVRQualifiers(),
2350 vat->getBracketsRange());
2351 break;
2352 }
2353 }
2354
2355 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002356 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002357}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002358
Steve Naroffcadebd02007-08-30 18:14:25 +00002359/// getVariableArrayType - Returns a non-unique reference to the type for a
2360/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002361QualType ASTContext::getVariableArrayType(QualType EltTy,
2362 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002363 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002364 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002365 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002366 // Since we don't unique expressions, it isn't possible to unique VLA's
2367 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002368 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002369
John McCall33ddac02011-01-19 10:06:00 +00002370 // Be sure to pull qualifiers off the element type.
2371 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2372 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002373 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002374 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002375 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002376 }
2377
John McCall90d1c2d2009-09-24 23:30:46 +00002378 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002379 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002380
2381 VariableArrayTypes.push_back(New);
2382 Types.push_back(New);
2383 return QualType(New, 0);
2384}
2385
Douglas Gregor4619e432008-12-05 23:32:09 +00002386/// getDependentSizedArrayType - Returns a non-unique reference to
2387/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002388/// type.
John McCall33ddac02011-01-19 10:06:00 +00002389QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2390 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002391 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002392 unsigned elementTypeQuals,
2393 SourceRange brackets) const {
2394 assert((!numElements || numElements->isTypeDependent() ||
2395 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002396 "Size must be type- or value-dependent!");
2397
John McCall33ddac02011-01-19 10:06:00 +00002398 // Dependently-sized array types that do not have a specified number
2399 // of elements will have their sizes deduced from a dependent
2400 // initializer. We do no canonicalization here at all, which is okay
2401 // because they can't be used in most locations.
2402 if (!numElements) {
2403 DependentSizedArrayType *newType
2404 = new (*this, TypeAlignment)
2405 DependentSizedArrayType(*this, elementType, QualType(),
2406 numElements, ASM, elementTypeQuals,
2407 brackets);
2408 Types.push_back(newType);
2409 return QualType(newType, 0);
2410 }
2411
2412 // Otherwise, we actually build a new type every time, but we
2413 // also build a canonical type.
2414
2415 SplitQualType canonElementType = getCanonicalType(elementType).split();
2416
2417 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002418 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002419 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002420 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002421 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002422
John McCall33ddac02011-01-19 10:06:00 +00002423 // Look for an existing type with these properties.
2424 DependentSizedArrayType *canonTy =
2425 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002426
John McCall33ddac02011-01-19 10:06:00 +00002427 // If we don't have one, build one.
2428 if (!canonTy) {
2429 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002430 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002431 QualType(), numElements, ASM, elementTypeQuals,
2432 brackets);
2433 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2434 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002435 }
2436
John McCall33ddac02011-01-19 10:06:00 +00002437 // Apply qualifiers from the element type to the array.
2438 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002439 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002440
John McCall33ddac02011-01-19 10:06:00 +00002441 // If we didn't need extra canonicalization for the element type,
2442 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002443 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002444 return canon;
2445
2446 // Otherwise, we need to build a type which follows the spelling
2447 // of the element type.
2448 DependentSizedArrayType *sugaredType
2449 = new (*this, TypeAlignment)
2450 DependentSizedArrayType(*this, elementType, canon, numElements,
2451 ASM, elementTypeQuals, brackets);
2452 Types.push_back(sugaredType);
2453 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002454}
2455
John McCall33ddac02011-01-19 10:06:00 +00002456QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002457 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002458 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002459 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002460 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002461
John McCall33ddac02011-01-19 10:06:00 +00002462 void *insertPos = 0;
2463 if (IncompleteArrayType *iat =
2464 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2465 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002466
2467 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002468 // either, so fill in the canonical type field. We also have to pull
2469 // qualifiers off the element type.
2470 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002471
John McCall33ddac02011-01-19 10:06:00 +00002472 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2473 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002474 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002475 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002476 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002477
2478 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002479 IncompleteArrayType *existing =
2480 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2481 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002482 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002483
John McCall33ddac02011-01-19 10:06:00 +00002484 IncompleteArrayType *newType = new (*this, TypeAlignment)
2485 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002486
John McCall33ddac02011-01-19 10:06:00 +00002487 IncompleteArrayTypes.InsertNode(newType, insertPos);
2488 Types.push_back(newType);
2489 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002490}
2491
Steve Naroff91fcddb2007-07-18 18:00:27 +00002492/// getVectorType - Return the unique reference to a vector type of
2493/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002494QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002495 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002496 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002497
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002498 // Check if we've already instantiated a vector of this type.
2499 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002500 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002501
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002502 void *InsertPos = 0;
2503 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2504 return QualType(VTP, 0);
2505
2506 // If the element type isn't canonical, this won't be a canonical type either,
2507 // so fill in the canonical type field.
2508 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002509 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002510 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002511
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002512 // Get the new insert position for the node we care about.
2513 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002514 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002515 }
John McCall90d1c2d2009-09-24 23:30:46 +00002516 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002517 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002518 VectorTypes.InsertNode(New, InsertPos);
2519 Types.push_back(New);
2520 return QualType(New, 0);
2521}
2522
Nate Begemance4d7fc2008-04-18 23:10:10 +00002523/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002524/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002525QualType
2526ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002527 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002528
Steve Naroff91fcddb2007-07-18 18:00:27 +00002529 // Check if we've already instantiated a vector of this type.
2530 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002531 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002532 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002533 void *InsertPos = 0;
2534 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2535 return QualType(VTP, 0);
2536
2537 // If the element type isn't canonical, this won't be a canonical type either,
2538 // so fill in the canonical type field.
2539 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002540 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002541 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002542
Steve Naroff91fcddb2007-07-18 18:00:27 +00002543 // Get the new insert position for the node we care about.
2544 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002545 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002546 }
John McCall90d1c2d2009-09-24 23:30:46 +00002547 ExtVectorType *New = new (*this, TypeAlignment)
2548 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002549 VectorTypes.InsertNode(New, InsertPos);
2550 Types.push_back(New);
2551 return QualType(New, 0);
2552}
2553
Jay Foad39c79802011-01-12 09:06:06 +00002554QualType
2555ASTContext::getDependentSizedExtVectorType(QualType vecType,
2556 Expr *SizeExpr,
2557 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002558 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002559 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002560 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002561
Douglas Gregor352169a2009-07-31 03:54:25 +00002562 void *InsertPos = 0;
2563 DependentSizedExtVectorType *Canon
2564 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2565 DependentSizedExtVectorType *New;
2566 if (Canon) {
2567 // We already have a canonical version of this array type; use it as
2568 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002569 New = new (*this, TypeAlignment)
2570 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2571 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002572 } else {
2573 QualType CanonVecTy = getCanonicalType(vecType);
2574 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002575 New = new (*this, TypeAlignment)
2576 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2577 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002578
2579 DependentSizedExtVectorType *CanonCheck
2580 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2581 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2582 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002583 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2584 } else {
2585 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2586 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002587 New = new (*this, TypeAlignment)
2588 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002589 }
2590 }
Mike Stump11289f42009-09-09 15:08:12 +00002591
Douglas Gregor758a8692009-06-17 21:51:59 +00002592 Types.push_back(New);
2593 return QualType(New, 0);
2594}
2595
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002596/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002597///
Jay Foad39c79802011-01-12 09:06:06 +00002598QualType
2599ASTContext::getFunctionNoProtoType(QualType ResultTy,
2600 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002601 const CallingConv DefaultCC = Info.getCC();
2602 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2603 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002604 // Unique functions, to guarantee there is only one function of a particular
2605 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002606 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002607 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002608
Chris Lattner47955de2007-01-27 08:37:20 +00002609 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002610 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002611 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002612 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002613
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002614 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002615 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002616 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002617 Canonical =
2618 getFunctionNoProtoType(getCanonicalType(ResultTy),
2619 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002620
Chris Lattner47955de2007-01-27 08:37:20 +00002621 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002622 FunctionNoProtoType *NewIP =
2623 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002624 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002625 }
Mike Stump11289f42009-09-09 15:08:12 +00002626
Roman Divacky65b88cd2011-03-01 17:40:53 +00002627 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002628 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002629 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002630 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002631 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002632 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002633}
2634
Douglas Gregorcd780372013-01-17 23:36:45 +00002635/// \brief Determine whether \p T is canonical as the result type of a function.
2636static bool isCanonicalResultType(QualType T) {
2637 return T.isCanonical() &&
2638 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2639 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2640}
2641
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002642/// getFunctionType - Return a normal function type with a typed argument
2643/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002644QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002645ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002646 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002647 size_t NumArgs = ArgArray.size();
2648
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002649 // Unique functions, to guarantee there is only one function of a particular
2650 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002651 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002652 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2653 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002654
2655 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002656 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002657 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002658 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002659
2660 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002661 bool isCanonical =
Douglas Gregorcd780372013-01-17 23:36:45 +00002662 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002663 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002664 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002665 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002666 isCanonical = false;
2667
Roman Divacky65b88cd2011-03-01 17:40:53 +00002668 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2669 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2670 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002671
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002672 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002673 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002674 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002675 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002676 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002677 CanonicalArgs.reserve(NumArgs);
2678 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002679 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002680
John McCalldb40c7f2010-12-14 08:05:40 +00002681 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002682 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002683 CanonicalEPI.ExceptionSpecType = EST_None;
2684 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002685 CanonicalEPI.ExtInfo
2686 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2687
Douglas Gregorcd780372013-01-17 23:36:45 +00002688 // Result types do not have ARC lifetime qualifiers.
2689 QualType CanResultTy = getCanonicalType(ResultTy);
2690 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2691 Qualifiers Qs = CanResultTy.getQualifiers();
2692 Qs.removeObjCLifetime();
2693 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2694 }
2695
Jordan Rose5c382722013-03-08 21:51:21 +00002696 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002697
Chris Lattnerfd4de792007-01-27 01:15:32 +00002698 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002699 FunctionProtoType *NewIP =
2700 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002701 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002702 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002703
John McCall31168b02011-06-15 23:02:42 +00002704 // FunctionProtoType objects are allocated with extra bytes after
2705 // them for three variable size arrays at the end:
2706 // - parameter types
2707 // - exception types
2708 // - consumed-arguments flags
2709 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002710 // expression, or information used to resolve the exception
2711 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002712 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002713 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002714 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002715 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002716 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002717 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002718 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002719 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002720 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2721 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002722 }
John McCall31168b02011-06-15 23:02:42 +00002723 if (EPI.ConsumedArguments)
2724 Size += NumArgs * sizeof(bool);
2725
John McCalldb40c7f2010-12-14 08:05:40 +00002726 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002727 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2728 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Jordan Rose5c382722013-03-08 21:51:21 +00002729 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002730 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002731 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002732 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002733}
Chris Lattneref51c202006-11-10 07:17:23 +00002734
John McCalle78aac42010-03-10 03:28:59 +00002735#ifndef NDEBUG
2736static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2737 if (!isa<CXXRecordDecl>(D)) return false;
2738 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2739 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2740 return true;
2741 if (RD->getDescribedClassTemplate() &&
2742 !isa<ClassTemplateSpecializationDecl>(RD))
2743 return true;
2744 return false;
2745}
2746#endif
2747
2748/// getInjectedClassNameType - Return the unique reference to the
2749/// injected class name type for the specified templated declaration.
2750QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002751 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002752 assert(NeedsInjectedClassNameType(Decl));
2753 if (Decl->TypeForDecl) {
2754 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002755 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002756 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2757 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2758 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2759 } else {
John McCall424cec92011-01-19 06:33:43 +00002760 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002761 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002762 Decl->TypeForDecl = newType;
2763 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002764 }
2765 return QualType(Decl->TypeForDecl, 0);
2766}
2767
Douglas Gregor83a586e2008-04-13 21:07:44 +00002768/// getTypeDeclType - Return the unique reference to the type for the
2769/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002770QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002771 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002772 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002773
Richard Smithdda56e42011-04-15 14:24:37 +00002774 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002775 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002776
John McCall96f0b5f2010-03-10 06:48:02 +00002777 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2778 "Template type parameter types are always available.");
2779
John McCall81e38502010-02-16 03:57:14 +00002780 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002781 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002782 "struct/union has previous declaration");
2783 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002784 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002785 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002786 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002787 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002788 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002789 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002790 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002791 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2792 Decl->TypeForDecl = newType;
2793 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002794 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002795 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002796
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002797 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002798}
2799
Chris Lattner32d920b2007-01-26 02:01:53 +00002800/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002801/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002802QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002803ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2804 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002805 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002806
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002807 if (Canonical.isNull())
2808 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002809 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002810 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002811 Decl->TypeForDecl = newType;
2812 Types.push_back(newType);
2813 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002814}
2815
Jay Foad39c79802011-01-12 09:06:06 +00002816QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002817 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2818
Douglas Gregorec9fd132012-01-14 16:38:05 +00002819 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002820 if (PrevDecl->TypeForDecl)
2821 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2822
John McCall424cec92011-01-19 06:33:43 +00002823 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2824 Decl->TypeForDecl = newType;
2825 Types.push_back(newType);
2826 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002827}
2828
Jay Foad39c79802011-01-12 09:06:06 +00002829QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002830 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2831
Douglas Gregorec9fd132012-01-14 16:38:05 +00002832 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002833 if (PrevDecl->TypeForDecl)
2834 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2835
John McCall424cec92011-01-19 06:33:43 +00002836 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2837 Decl->TypeForDecl = newType;
2838 Types.push_back(newType);
2839 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002840}
2841
John McCall81904512011-01-06 01:58:22 +00002842QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2843 QualType modifiedType,
2844 QualType equivalentType) {
2845 llvm::FoldingSetNodeID id;
2846 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2847
2848 void *insertPos = 0;
2849 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2850 if (type) return QualType(type, 0);
2851
2852 QualType canon = getCanonicalType(equivalentType);
2853 type = new (*this, TypeAlignment)
2854 AttributedType(canon, attrKind, modifiedType, equivalentType);
2855
2856 Types.push_back(type);
2857 AttributedTypes.InsertNode(type, insertPos);
2858
2859 return QualType(type, 0);
2860}
2861
2862
John McCallcebee162009-10-18 09:09:24 +00002863/// \brief Retrieve a substitution-result type.
2864QualType
2865ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002866 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002867 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002868 && "replacement types must always be canonical");
2869
2870 llvm::FoldingSetNodeID ID;
2871 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2872 void *InsertPos = 0;
2873 SubstTemplateTypeParmType *SubstParm
2874 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2875
2876 if (!SubstParm) {
2877 SubstParm = new (*this, TypeAlignment)
2878 SubstTemplateTypeParmType(Parm, Replacement);
2879 Types.push_back(SubstParm);
2880 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2881 }
2882
2883 return QualType(SubstParm, 0);
2884}
2885
Douglas Gregorada4b792011-01-14 02:55:32 +00002886/// \brief Retrieve a
2887QualType ASTContext::getSubstTemplateTypeParmPackType(
2888 const TemplateTypeParmType *Parm,
2889 const TemplateArgument &ArgPack) {
2890#ifndef NDEBUG
2891 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2892 PEnd = ArgPack.pack_end();
2893 P != PEnd; ++P) {
2894 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2895 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2896 }
2897#endif
2898
2899 llvm::FoldingSetNodeID ID;
2900 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2901 void *InsertPos = 0;
2902 if (SubstTemplateTypeParmPackType *SubstParm
2903 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2904 return QualType(SubstParm, 0);
2905
2906 QualType Canon;
2907 if (!Parm->isCanonicalUnqualified()) {
2908 Canon = getCanonicalType(QualType(Parm, 0));
2909 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2910 ArgPack);
2911 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2912 }
2913
2914 SubstTemplateTypeParmPackType *SubstParm
2915 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2916 ArgPack);
2917 Types.push_back(SubstParm);
2918 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2919 return QualType(SubstParm, 0);
2920}
2921
Douglas Gregoreff93e02009-02-05 23:33:38 +00002922/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002923/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002924/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002925QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002926 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002927 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002928 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002929 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002930 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002931 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002932 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2933
2934 if (TypeParm)
2935 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002936
Chandler Carruth08836322011-05-01 00:51:33 +00002937 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002938 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002939 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002940
2941 TemplateTypeParmType *TypeCheck
2942 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2943 assert(!TypeCheck && "Template type parameter canonical type broken");
2944 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002945 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002946 TypeParm = new (*this, TypeAlignment)
2947 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002948
2949 Types.push_back(TypeParm);
2950 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2951
2952 return QualType(TypeParm, 0);
2953}
2954
John McCalle78aac42010-03-10 03:28:59 +00002955TypeSourceInfo *
2956ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2957 SourceLocation NameLoc,
2958 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002959 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002960 assert(!Name.getAsDependentTemplateName() &&
2961 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002962 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002963
2964 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00002965 TemplateSpecializationTypeLoc TL =
2966 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002967 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00002968 TL.setTemplateNameLoc(NameLoc);
2969 TL.setLAngleLoc(Args.getLAngleLoc());
2970 TL.setRAngleLoc(Args.getRAngleLoc());
2971 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2972 TL.setArgLocInfo(i, Args[i].getLocInfo());
2973 return DI;
2974}
2975
Mike Stump11289f42009-09-09 15:08:12 +00002976QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002977ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002978 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002979 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002980 assert(!Template.getAsDependentTemplateName() &&
2981 "No dependent template names here!");
2982
John McCall6b51f282009-11-23 01:53:49 +00002983 unsigned NumArgs = Args.size();
2984
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002985 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002986 ArgVec.reserve(NumArgs);
2987 for (unsigned i = 0; i != NumArgs; ++i)
2988 ArgVec.push_back(Args[i].getArgument());
2989
John McCall2408e322010-04-27 00:57:59 +00002990 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002991 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002992}
2993
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002994#ifndef NDEBUG
2995static bool hasAnyPackExpansions(const TemplateArgument *Args,
2996 unsigned NumArgs) {
2997 for (unsigned I = 0; I != NumArgs; ++I)
2998 if (Args[I].isPackExpansion())
2999 return true;
3000
3001 return true;
3002}
3003#endif
3004
John McCall0ad16662009-10-29 08:12:44 +00003005QualType
3006ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003007 const TemplateArgument *Args,
3008 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003009 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003010 assert(!Template.getAsDependentTemplateName() &&
3011 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003012 // Look through qualified template names.
3013 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3014 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003015
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003016 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003017 Template.getAsTemplateDecl() &&
3018 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003019 QualType CanonType;
3020 if (!Underlying.isNull())
3021 CanonType = getCanonicalType(Underlying);
3022 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003023 // We can get here with an alias template when the specialization contains
3024 // a pack expansion that does not match up with a parameter pack.
3025 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3026 "Caller must compute aliased type");
3027 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003028 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3029 NumArgs);
3030 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003031
Douglas Gregora8e02e72009-07-28 23:00:59 +00003032 // Allocate the (non-canonical) template specialization type, but don't
3033 // try to unique it: these types typically have location information that
3034 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003035 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3036 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003037 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003038 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003039 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003040 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3041 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003042
Douglas Gregor8bf42052009-02-09 18:46:07 +00003043 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003044 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003045}
3046
Mike Stump11289f42009-09-09 15:08:12 +00003047QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003048ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3049 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003050 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003051 assert(!Template.getAsDependentTemplateName() &&
3052 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003053
Douglas Gregore29139c2011-03-03 17:04:51 +00003054 // Look through qualified template names.
3055 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3056 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003057
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003058 // Build the canonical template specialization type.
3059 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003060 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003061 CanonArgs.reserve(NumArgs);
3062 for (unsigned I = 0; I != NumArgs; ++I)
3063 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3064
3065 // Determine whether this canonical template specialization type already
3066 // exists.
3067 llvm::FoldingSetNodeID ID;
3068 TemplateSpecializationType::Profile(ID, CanonTemplate,
3069 CanonArgs.data(), NumArgs, *this);
3070
3071 void *InsertPos = 0;
3072 TemplateSpecializationType *Spec
3073 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3074
3075 if (!Spec) {
3076 // Allocate a new canonical template specialization type.
3077 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3078 sizeof(TemplateArgument) * NumArgs),
3079 TypeAlignment);
3080 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3081 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003082 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003083 Types.push_back(Spec);
3084 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3085 }
3086
3087 assert(Spec->isDependentType() &&
3088 "Non-dependent template-id type must have a canonical type");
3089 return QualType(Spec, 0);
3090}
3091
3092QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003093ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3094 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003095 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003096 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003097 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003098
3099 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003100 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003101 if (T)
3102 return QualType(T, 0);
3103
Douglas Gregorc42075a2010-02-04 18:10:26 +00003104 QualType Canon = NamedType;
3105 if (!Canon.isCanonical()) {
3106 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003107 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3108 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003109 (void)CheckT;
3110 }
3111
Abramo Bagnara6150c882010-05-11 21:36:43 +00003112 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003113 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003114 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003115 return QualType(T, 0);
3116}
3117
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003118QualType
Jay Foad39c79802011-01-12 09:06:06 +00003119ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003120 llvm::FoldingSetNodeID ID;
3121 ParenType::Profile(ID, InnerType);
3122
3123 void *InsertPos = 0;
3124 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3125 if (T)
3126 return QualType(T, 0);
3127
3128 QualType Canon = InnerType;
3129 if (!Canon.isCanonical()) {
3130 Canon = getCanonicalType(InnerType);
3131 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3132 assert(!CheckT && "Paren canonical type broken");
3133 (void)CheckT;
3134 }
3135
3136 T = new (*this) ParenType(InnerType, Canon);
3137 Types.push_back(T);
3138 ParenTypes.InsertNode(T, InsertPos);
3139 return QualType(T, 0);
3140}
3141
Douglas Gregor02085352010-03-31 20:19:30 +00003142QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3143 NestedNameSpecifier *NNS,
3144 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003145 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003146 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3147
3148 if (Canon.isNull()) {
3149 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003150 ElaboratedTypeKeyword CanonKeyword = Keyword;
3151 if (Keyword == ETK_None)
3152 CanonKeyword = ETK_Typename;
3153
3154 if (CanonNNS != NNS || CanonKeyword != Keyword)
3155 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003156 }
3157
3158 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003159 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003160
3161 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003162 DependentNameType *T
3163 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003164 if (T)
3165 return QualType(T, 0);
3166
Douglas Gregor02085352010-03-31 20:19:30 +00003167 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003168 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003169 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003170 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003171}
3172
Mike Stump11289f42009-09-09 15:08:12 +00003173QualType
John McCallc392f372010-06-11 00:33:02 +00003174ASTContext::getDependentTemplateSpecializationType(
3175 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003176 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003177 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003178 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003179 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003180 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003181 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3182 ArgCopy.push_back(Args[I].getArgument());
3183 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3184 ArgCopy.size(),
3185 ArgCopy.data());
3186}
3187
3188QualType
3189ASTContext::getDependentTemplateSpecializationType(
3190 ElaboratedTypeKeyword Keyword,
3191 NestedNameSpecifier *NNS,
3192 const IdentifierInfo *Name,
3193 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003194 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003195 assert((!NNS || NNS->isDependent()) &&
3196 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003197
Douglas Gregorc42075a2010-02-04 18:10:26 +00003198 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003199 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3200 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003201
3202 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00003203 DependentTemplateSpecializationType *T
3204 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003205 if (T)
3206 return QualType(T, 0);
3207
John McCallc392f372010-06-11 00:33:02 +00003208 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003209
John McCallc392f372010-06-11 00:33:02 +00003210 ElaboratedTypeKeyword CanonKeyword = Keyword;
3211 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3212
3213 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003214 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003215 for (unsigned I = 0; I != NumArgs; ++I) {
3216 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3217 if (!CanonArgs[I].structurallyEquals(Args[I]))
3218 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003219 }
3220
John McCallc392f372010-06-11 00:33:02 +00003221 QualType Canon;
3222 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3223 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3224 Name, NumArgs,
3225 CanonArgs.data());
3226
3227 // Find the insert position again.
3228 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3229 }
3230
3231 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3232 sizeof(TemplateArgument) * NumArgs),
3233 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003234 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003235 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003236 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003237 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003238 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003239}
3240
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003241QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003242 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003243 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003244 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003245
3246 assert(Pattern->containsUnexpandedParameterPack() &&
3247 "Pack expansions must expand one or more parameter packs");
3248 void *InsertPos = 0;
3249 PackExpansionType *T
3250 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3251 if (T)
3252 return QualType(T, 0);
3253
3254 QualType Canon;
3255 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003256 Canon = getCanonicalType(Pattern);
3257 // The canonical type might not contain an unexpanded parameter pack, if it
3258 // contains an alias template specialization which ignores one of its
3259 // parameters.
3260 if (Canon->containsUnexpandedParameterPack()) {
3261 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003262
Richard Smith68eea502012-07-16 00:20:35 +00003263 // Find the insert position again, in case we inserted an element into
3264 // PackExpansionTypes and invalidated our insert position.
3265 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3266 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003267 }
3268
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003269 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003270 Types.push_back(T);
3271 PackExpansionTypes.InsertNode(T, InsertPos);
3272 return QualType(T, 0);
3273}
3274
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003275/// CmpProtocolNames - Comparison predicate for sorting protocols
3276/// alphabetically.
3277static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3278 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003279 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003280}
3281
John McCall8b07ec22010-05-15 11:32:37 +00003282static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003283 unsigned NumProtocols) {
3284 if (NumProtocols == 0) return true;
3285
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003286 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3287 return false;
3288
John McCallfc93cf92009-10-22 22:37:11 +00003289 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003290 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3291 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003292 return false;
3293 return true;
3294}
3295
3296static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003297 unsigned &NumProtocols) {
3298 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003299
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003300 // Sort protocols, keyed by name.
3301 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3302
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003303 // Canonicalize.
3304 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3305 Protocols[I] = Protocols[I]->getCanonicalDecl();
3306
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003307 // Remove duplicates.
3308 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3309 NumProtocols = ProtocolsEnd-Protocols;
3310}
3311
John McCall8b07ec22010-05-15 11:32:37 +00003312QualType ASTContext::getObjCObjectType(QualType BaseType,
3313 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003314 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003315 // If the base type is an interface and there aren't any protocols
3316 // to add, then the interface type will do just fine.
3317 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3318 return BaseType;
3319
3320 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003321 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003322 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003323 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003324 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3325 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003326
John McCall8b07ec22010-05-15 11:32:37 +00003327 // Build the canonical type, which has the canonical base type and
3328 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003329 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003330 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3331 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3332 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003333 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003334 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003335 unsigned UniqueCount = NumProtocols;
3336
John McCallfc93cf92009-10-22 22:37:11 +00003337 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003338 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3339 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003340 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003341 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3342 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003343 }
3344
3345 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003346 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3347 }
3348
3349 unsigned Size = sizeof(ObjCObjectTypeImpl);
3350 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3351 void *Mem = Allocate(Size, TypeAlignment);
3352 ObjCObjectTypeImpl *T =
3353 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3354
3355 Types.push_back(T);
3356 ObjCObjectTypes.InsertNode(T, InsertPos);
3357 return QualType(T, 0);
3358}
3359
3360/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3361/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003362QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003363 llvm::FoldingSetNodeID ID;
3364 ObjCObjectPointerType::Profile(ID, ObjectT);
3365
3366 void *InsertPos = 0;
3367 if (ObjCObjectPointerType *QT =
3368 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3369 return QualType(QT, 0);
3370
3371 // Find the canonical object type.
3372 QualType Canonical;
3373 if (!ObjectT.isCanonical()) {
3374 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3375
3376 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003377 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3378 }
3379
Douglas Gregorf85bee62010-02-08 22:59:26 +00003380 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003381 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3382 ObjCObjectPointerType *QType =
3383 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003384
Steve Narofffb4330f2009-06-17 22:40:22 +00003385 Types.push_back(QType);
3386 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003387 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003388}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003389
Douglas Gregor1c283312010-08-11 12:19:30 +00003390/// getObjCInterfaceType - Return the unique reference to the type for the
3391/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003392QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3393 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003394 if (Decl->TypeForDecl)
3395 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003396
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003397 if (PrevDecl) {
3398 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3399 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3400 return QualType(PrevDecl->TypeForDecl, 0);
3401 }
3402
Douglas Gregor7671e532011-12-16 16:34:57 +00003403 // Prefer the definition, if there is one.
3404 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3405 Decl = Def;
3406
Douglas Gregor1c283312010-08-11 12:19:30 +00003407 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3408 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3409 Decl->TypeForDecl = T;
3410 Types.push_back(T);
3411 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003412}
3413
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003414/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3415/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003416/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003417/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003418/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003419QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003420 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003421 if (tofExpr->isTypeDependent()) {
3422 llvm::FoldingSetNodeID ID;
3423 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003424
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003425 void *InsertPos = 0;
3426 DependentTypeOfExprType *Canon
3427 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3428 if (Canon) {
3429 // We already have a "canonical" version of an identical, dependent
3430 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003431 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003432 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003433 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003434 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003435 Canon
3436 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003437 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3438 toe = Canon;
3439 }
3440 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003441 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003442 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003443 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003444 Types.push_back(toe);
3445 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003446}
3447
Steve Naroffa773cd52007-08-01 18:02:17 +00003448/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3449/// TypeOfType AST's. The only motivation to unique these nodes would be
3450/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003451/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003452/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003453QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003454 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003455 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003456 Types.push_back(tot);
3457 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003458}
3459
Anders Carlssonad6bd352009-06-24 21:24:56 +00003460
Anders Carlsson81df7b82009-06-24 19:06:50 +00003461/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3462/// DecltypeType AST's. The only motivation to unique these nodes would be
3463/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003464/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003465/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003466QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003467 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003468
3469 // C++0x [temp.type]p2:
3470 // If an expression e involves a template parameter, decltype(e) denotes a
3471 // unique dependent type. Two such decltype-specifiers refer to the same
3472 // type only if their expressions are equivalent (14.5.6.1).
3473 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003474 llvm::FoldingSetNodeID ID;
3475 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003476
Douglas Gregora21f6c32009-07-30 23:36:40 +00003477 void *InsertPos = 0;
3478 DependentDecltypeType *Canon
3479 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3480 if (Canon) {
3481 // We already have a "canonical" version of an equivalent, dependent
3482 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003483 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003484 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003485 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003486 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003487 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003488 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3489 dt = Canon;
3490 }
3491 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003492 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3493 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003494 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003495 Types.push_back(dt);
3496 return QualType(dt, 0);
3497}
3498
Alexis Hunte852b102011-05-24 22:41:36 +00003499/// getUnaryTransformationType - We don't unique these, since the memory
3500/// savings are minimal and these are rare.
3501QualType ASTContext::getUnaryTransformType(QualType BaseType,
3502 QualType UnderlyingType,
3503 UnaryTransformType::UTTKind Kind)
3504 const {
3505 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003506 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3507 Kind,
3508 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003509 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003510 Types.push_back(Ty);
3511 return QualType(Ty, 0);
3512}
3513
Richard Smithb2bc2e62011-02-21 20:05:19 +00003514/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003515QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00003516 void *InsertPos = 0;
3517 if (!DeducedType.isNull()) {
3518 // Look in the folding set for an existing type.
3519 llvm::FoldingSetNodeID ID;
3520 AutoType::Profile(ID, DeducedType);
3521 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3522 return QualType(AT, 0);
3523 }
3524
3525 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3526 Types.push_back(AT);
3527 if (InsertPos)
3528 AutoTypes.InsertNode(AT, InsertPos);
3529 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003530}
3531
Eli Friedman0dfb8892011-10-06 23:00:33 +00003532/// getAtomicType - Return the uniqued reference to the atomic type for
3533/// the given value type.
3534QualType ASTContext::getAtomicType(QualType T) const {
3535 // Unique pointers, to guarantee there is only one pointer of a particular
3536 // structure.
3537 llvm::FoldingSetNodeID ID;
3538 AtomicType::Profile(ID, T);
3539
3540 void *InsertPos = 0;
3541 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3542 return QualType(AT, 0);
3543
3544 // If the atomic value type isn't canonical, this won't be a canonical type
3545 // either, so fill in the canonical type field.
3546 QualType Canonical;
3547 if (!T.isCanonical()) {
3548 Canonical = getAtomicType(getCanonicalType(T));
3549
3550 // Get the new insert position for the node we care about.
3551 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3552 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3553 }
3554 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3555 Types.push_back(New);
3556 AtomicTypes.InsertNode(New, InsertPos);
3557 return QualType(New, 0);
3558}
3559
Richard Smith02e85f32011-04-14 22:09:26 +00003560/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3561QualType ASTContext::getAutoDeductType() const {
3562 if (AutoDeductTy.isNull())
3563 AutoDeductTy = getAutoType(QualType());
3564 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3565 return AutoDeductTy;
3566}
3567
3568/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3569QualType ASTContext::getAutoRRefDeductType() const {
3570 if (AutoRRefDeductTy.isNull())
3571 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3572 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3573 return AutoRRefDeductTy;
3574}
3575
Chris Lattnerfb072462007-01-23 05:45:31 +00003576/// getTagDeclType - Return the unique reference to the type for the
3577/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003578QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003579 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003580 // FIXME: What is the design on getTagDeclType when it requires casting
3581 // away const? mutable?
3582 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003583}
3584
Mike Stump11289f42009-09-09 15:08:12 +00003585/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3586/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3587/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003588CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003589 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003590}
Chris Lattnerfb072462007-01-23 05:45:31 +00003591
Hans Wennborg27541db2011-10-27 08:29:09 +00003592/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3593CanQualType ASTContext::getIntMaxType() const {
3594 return getFromTargetType(Target->getIntMaxType());
3595}
3596
3597/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3598CanQualType ASTContext::getUIntMaxType() const {
3599 return getFromTargetType(Target->getUIntMaxType());
3600}
3601
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003602/// getSignedWCharType - Return the type of "signed wchar_t".
3603/// Used when in C++, as a GCC extension.
3604QualType ASTContext::getSignedWCharType() const {
3605 // FIXME: derive from "Target" ?
3606 return WCharTy;
3607}
3608
3609/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3610/// Used when in C++, as a GCC extension.
3611QualType ASTContext::getUnsignedWCharType() const {
3612 // FIXME: derive from "Target" ?
3613 return UnsignedIntTy;
3614}
3615
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00003616QualType ASTContext::getIntPtrType() const {
3617 return getFromTargetType(Target->getIntPtrType());
3618}
3619
3620QualType ASTContext::getUIntPtrType() const {
3621 return getCorrespondingUnsignedType(getIntPtrType());
3622}
3623
Hans Wennborg27541db2011-10-27 08:29:09 +00003624/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003625/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3626QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003627 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003628}
3629
Eli Friedman4e91899e2012-11-27 02:58:24 +00003630/// \brief Return the unique type for "pid_t" defined in
3631/// <sys/types.h>. We need this to compute the correct type for vfork().
3632QualType ASTContext::getProcessIDType() const {
3633 return getFromTargetType(Target->getProcessIDType());
3634}
3635
Chris Lattnera21ad802008-04-02 05:18:44 +00003636//===----------------------------------------------------------------------===//
3637// Type Operators
3638//===----------------------------------------------------------------------===//
3639
Jay Foad39c79802011-01-12 09:06:06 +00003640CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003641 // Push qualifiers into arrays, and then discard any remaining
3642 // qualifiers.
3643 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003644 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003645 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003646 QualType Result;
3647 if (isa<ArrayType>(Ty)) {
3648 Result = getArrayDecayedType(QualType(Ty,0));
3649 } else if (isa<FunctionType>(Ty)) {
3650 Result = getPointerType(QualType(Ty, 0));
3651 } else {
3652 Result = QualType(Ty, 0);
3653 }
3654
3655 return CanQualType::CreateUnsafe(Result);
3656}
3657
John McCall6c9dd522011-01-18 07:41:22 +00003658QualType ASTContext::getUnqualifiedArrayType(QualType type,
3659 Qualifiers &quals) {
3660 SplitQualType splitType = type.getSplitUnqualifiedType();
3661
3662 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3663 // the unqualified desugared type and then drops it on the floor.
3664 // We then have to strip that sugar back off with
3665 // getUnqualifiedDesugaredType(), which is silly.
3666 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003667 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003668
3669 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003670 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003671 quals = splitType.Quals;
3672 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003673 }
3674
John McCall6c9dd522011-01-18 07:41:22 +00003675 // Otherwise, recurse on the array's element type.
3676 QualType elementType = AT->getElementType();
3677 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3678
3679 // If that didn't change the element type, AT has no qualifiers, so we
3680 // can just use the results in splitType.
3681 if (elementType == unqualElementType) {
3682 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003683 quals = splitType.Quals;
3684 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003685 }
3686
3687 // Otherwise, add in the qualifiers from the outermost type, then
3688 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003689 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003690
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003691 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003692 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003693 CAT->getSizeModifier(), 0);
3694 }
3695
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003696 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003697 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003698 }
3699
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003700 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003701 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003702 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003703 VAT->getSizeModifier(),
3704 VAT->getIndexTypeCVRQualifiers(),
3705 VAT->getBracketsRange());
3706 }
3707
3708 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003709 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003710 DSAT->getSizeModifier(), 0,
3711 SourceRange());
3712}
3713
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003714/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3715/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3716/// they point to and return true. If T1 and T2 aren't pointer types
3717/// or pointer-to-member types, or if they are not similar at this
3718/// level, returns false and leaves T1 and T2 unchanged. Top-level
3719/// qualifiers on T1 and T2 are ignored. This function will typically
3720/// be called in a loop that successively "unwraps" pointer and
3721/// pointer-to-member types to compare them at each level.
3722bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3723 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3724 *T2PtrType = T2->getAs<PointerType>();
3725 if (T1PtrType && T2PtrType) {
3726 T1 = T1PtrType->getPointeeType();
3727 T2 = T2PtrType->getPointeeType();
3728 return true;
3729 }
3730
3731 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3732 *T2MPType = T2->getAs<MemberPointerType>();
3733 if (T1MPType && T2MPType &&
3734 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3735 QualType(T2MPType->getClass(), 0))) {
3736 T1 = T1MPType->getPointeeType();
3737 T2 = T2MPType->getPointeeType();
3738 return true;
3739 }
3740
David Blaikiebbafb8a2012-03-11 07:00:24 +00003741 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003742 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3743 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3744 if (T1OPType && T2OPType) {
3745 T1 = T1OPType->getPointeeType();
3746 T2 = T2OPType->getPointeeType();
3747 return true;
3748 }
3749 }
3750
3751 // FIXME: Block pointers, too?
3752
3753 return false;
3754}
3755
Jay Foad39c79802011-01-12 09:06:06 +00003756DeclarationNameInfo
3757ASTContext::getNameForTemplate(TemplateName Name,
3758 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003759 switch (Name.getKind()) {
3760 case TemplateName::QualifiedTemplate:
3761 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003762 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003763 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3764 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003765
John McCalld9dfe3a2011-06-30 08:33:18 +00003766 case TemplateName::OverloadedTemplate: {
3767 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3768 // DNInfo work in progress: CHECKME: what about DNLoc?
3769 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3770 }
3771
3772 case TemplateName::DependentTemplate: {
3773 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003774 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003775 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003776 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3777 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003778 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003779 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3780 // DNInfo work in progress: FIXME: source locations?
3781 DeclarationNameLoc DNLoc;
3782 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3783 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3784 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003785 }
3786 }
3787
John McCalld9dfe3a2011-06-30 08:33:18 +00003788 case TemplateName::SubstTemplateTemplateParm: {
3789 SubstTemplateTemplateParmStorage *subst
3790 = Name.getAsSubstTemplateTemplateParm();
3791 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3792 NameLoc);
3793 }
3794
3795 case TemplateName::SubstTemplateTemplateParmPack: {
3796 SubstTemplateTemplateParmPackStorage *subst
3797 = Name.getAsSubstTemplateTemplateParmPack();
3798 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3799 NameLoc);
3800 }
3801 }
3802
3803 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003804}
3805
Jay Foad39c79802011-01-12 09:06:06 +00003806TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003807 switch (Name.getKind()) {
3808 case TemplateName::QualifiedTemplate:
3809 case TemplateName::Template: {
3810 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003811 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003812 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003813 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3814
3815 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003816 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003817 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003818
John McCalld9dfe3a2011-06-30 08:33:18 +00003819 case TemplateName::OverloadedTemplate:
3820 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003821
John McCalld9dfe3a2011-06-30 08:33:18 +00003822 case TemplateName::DependentTemplate: {
3823 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3824 assert(DTN && "Non-dependent template names must refer to template decls.");
3825 return DTN->CanonicalTemplateName;
3826 }
3827
3828 case TemplateName::SubstTemplateTemplateParm: {
3829 SubstTemplateTemplateParmStorage *subst
3830 = Name.getAsSubstTemplateTemplateParm();
3831 return getCanonicalTemplateName(subst->getReplacement());
3832 }
3833
3834 case TemplateName::SubstTemplateTemplateParmPack: {
3835 SubstTemplateTemplateParmPackStorage *subst
3836 = Name.getAsSubstTemplateTemplateParmPack();
3837 TemplateTemplateParmDecl *canonParameter
3838 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3839 TemplateArgument canonArgPack
3840 = getCanonicalTemplateArgument(subst->getArgumentPack());
3841 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3842 }
3843 }
3844
3845 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003846}
3847
Douglas Gregoradee3e32009-11-11 23:06:43 +00003848bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3849 X = getCanonicalTemplateName(X);
3850 Y = getCanonicalTemplateName(Y);
3851 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3852}
3853
Mike Stump11289f42009-09-09 15:08:12 +00003854TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003855ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003856 switch (Arg.getKind()) {
3857 case TemplateArgument::Null:
3858 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003859
Douglas Gregora8e02e72009-07-28 23:00:59 +00003860 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003861 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003862
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003863 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00003864 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
3865 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003866 }
Mike Stump11289f42009-09-09 15:08:12 +00003867
Eli Friedmanb826a002012-09-26 02:36:12 +00003868 case TemplateArgument::NullPtr:
3869 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
3870 /*isNullPtr*/true);
3871
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003872 case TemplateArgument::Template:
3873 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003874
3875 case TemplateArgument::TemplateExpansion:
3876 return TemplateArgument(getCanonicalTemplateName(
3877 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003878 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003879
Douglas Gregora8e02e72009-07-28 23:00:59 +00003880 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003881 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003882
Douglas Gregora8e02e72009-07-28 23:00:59 +00003883 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003884 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003885
Douglas Gregora8e02e72009-07-28 23:00:59 +00003886 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003887 if (Arg.pack_size() == 0)
3888 return Arg;
3889
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003890 TemplateArgument *CanonArgs
3891 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003892 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003893 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003894 AEnd = Arg.pack_end();
3895 A != AEnd; (void)++A, ++Idx)
3896 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003897
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003898 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003899 }
3900 }
3901
3902 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003903 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003904}
3905
Douglas Gregor333489b2009-03-27 23:10:48 +00003906NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003907ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003908 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003909 return 0;
3910
3911 switch (NNS->getKind()) {
3912 case NestedNameSpecifier::Identifier:
3913 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003914 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003915 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3916 NNS->getAsIdentifier());
3917
3918 case NestedNameSpecifier::Namespace:
3919 // A namespace is canonical; build a nested-name-specifier with
3920 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003921 return NestedNameSpecifier::Create(*this, 0,
3922 NNS->getAsNamespace()->getOriginalNamespace());
3923
3924 case NestedNameSpecifier::NamespaceAlias:
3925 // A namespace is canonical; build a nested-name-specifier with
3926 // this namespace and no prefix.
3927 return NestedNameSpecifier::Create(*this, 0,
3928 NNS->getAsNamespaceAlias()->getNamespace()
3929 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003930
3931 case NestedNameSpecifier::TypeSpec:
3932 case NestedNameSpecifier::TypeSpecWithTemplate: {
3933 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003934
3935 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3936 // break it apart into its prefix and identifier, then reconsititute those
3937 // as the canonical nested-name-specifier. This is required to canonicalize
3938 // a dependent nested-name-specifier involving typedefs of dependent-name
3939 // types, e.g.,
3940 // typedef typename T::type T1;
3941 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00003942 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3943 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00003944 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003945
Eli Friedman5358a0a2012-03-03 04:09:56 +00003946 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3947 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3948 // first place?
John McCall33ddac02011-01-19 10:06:00 +00003949 return NestedNameSpecifier::Create(*this, 0, false,
3950 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003951 }
3952
3953 case NestedNameSpecifier::Global:
3954 // The global specifier is canonical and unique.
3955 return NNS;
3956 }
3957
David Blaikie8a40f702012-01-17 06:56:22 +00003958 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00003959}
3960
Chris Lattner7adf0762008-08-04 07:31:14 +00003961
Jay Foad39c79802011-01-12 09:06:06 +00003962const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003963 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003964 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003965 // Handle the common positive case fast.
3966 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3967 return AT;
3968 }
Mike Stump11289f42009-09-09 15:08:12 +00003969
John McCall8ccfcb52009-09-24 19:53:00 +00003970 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003971 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003972 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003973
John McCall8ccfcb52009-09-24 19:53:00 +00003974 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003975 // implements C99 6.7.3p8: "If the specification of an array type includes
3976 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003977
Chris Lattner7adf0762008-08-04 07:31:14 +00003978 // If we get here, we either have type qualifiers on the type, or we have
3979 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003980 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003981
John McCall33ddac02011-01-19 10:06:00 +00003982 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003983 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00003984
Chris Lattner7adf0762008-08-04 07:31:14 +00003985 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00003986 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00003987 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003988 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003989
Chris Lattner7adf0762008-08-04 07:31:14 +00003990 // Otherwise, we have an array and we have qualifiers on it. Push the
3991 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003992 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003993
Chris Lattner7adf0762008-08-04 07:31:14 +00003994 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3995 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3996 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003997 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003998 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3999 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4000 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004001 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004002
Mike Stump11289f42009-09-09 15:08:12 +00004003 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004004 = dyn_cast<DependentSizedArrayType>(ATy))
4005 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004006 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004007 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004008 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004009 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004010 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004011
Chris Lattner7adf0762008-08-04 07:31:14 +00004012 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004013 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004014 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004015 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004016 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004017 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004018}
4019
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004020QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004021 // C99 6.7.5.3p7:
4022 // A declaration of a parameter as "array of type" shall be
4023 // adjusted to "qualified pointer to type", where the type
4024 // qualifiers (if any) are those specified within the [ and ] of
4025 // the array type derivation.
4026 if (T->isArrayType())
4027 return getArrayDecayedType(T);
4028
4029 // C99 6.7.5.3p8:
4030 // A declaration of a parameter as "function returning type"
4031 // shall be adjusted to "pointer to function returning type", as
4032 // in 6.3.2.1.
4033 if (T->isFunctionType())
4034 return getPointerType(T);
4035
4036 return T;
4037}
4038
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004039QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004040 T = getVariableArrayDecayedType(T);
4041 T = getAdjustedParameterType(T);
4042 return T.getUnqualifiedType();
4043}
4044
Chris Lattnera21ad802008-04-02 05:18:44 +00004045/// getArrayDecayedType - Return the properly qualified result of decaying the
4046/// specified array type to a pointer. This operation is non-trivial when
4047/// handling typedefs etc. The canonical type of "T" must be an array type,
4048/// this returns a pointer to a properly qualified element of the array.
4049///
4050/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004051QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004052 // Get the element type with 'getAsArrayType' so that we don't lose any
4053 // typedefs in the element type of the array. This also handles propagation
4054 // of type qualifiers from the array type into the element type if present
4055 // (C99 6.7.3p8).
4056 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4057 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004058
Chris Lattner7adf0762008-08-04 07:31:14 +00004059 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004060
4061 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004062 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004063}
4064
John McCall33ddac02011-01-19 10:06:00 +00004065QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4066 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004067}
4068
John McCall33ddac02011-01-19 10:06:00 +00004069QualType ASTContext::getBaseElementType(QualType type) const {
4070 Qualifiers qs;
4071 while (true) {
4072 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004073 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004074 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004075
John McCall33ddac02011-01-19 10:06:00 +00004076 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004077 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004078 }
Mike Stump11289f42009-09-09 15:08:12 +00004079
John McCall33ddac02011-01-19 10:06:00 +00004080 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004081}
4082
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004083/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004084uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004085ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4086 uint64_t ElementCount = 1;
4087 do {
4088 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004089 CA = dyn_cast_or_null<ConstantArrayType>(
4090 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004091 } while (CA);
4092 return ElementCount;
4093}
4094
Steve Naroff0af91202007-04-27 21:51:21 +00004095/// getFloatingRank - Return a relative rank for floating point types.
4096/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004097static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004098 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004099 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004100
John McCall9dd450b2009-09-21 23:43:11 +00004101 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4102 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004103 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004104 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004105 case BuiltinType::Float: return FloatRank;
4106 case BuiltinType::Double: return DoubleRank;
4107 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004108 }
4109}
4110
Mike Stump11289f42009-09-09 15:08:12 +00004111/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4112/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004113/// 'typeDomain' is a real floating point or complex type.
4114/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004115QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4116 QualType Domain) const {
4117 FloatingRank EltRank = getFloatingRank(Size);
4118 if (Domain->isComplexType()) {
4119 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004120 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004121 case FloatRank: return FloatComplexTy;
4122 case DoubleRank: return DoubleComplexTy;
4123 case LongDoubleRank: return LongDoubleComplexTy;
4124 }
Steve Naroff0af91202007-04-27 21:51:21 +00004125 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004126
4127 assert(Domain->isRealFloatingType() && "Unknown domain!");
4128 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004129 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004130 case FloatRank: return FloatTy;
4131 case DoubleRank: return DoubleTy;
4132 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004133 }
David Blaikief47fa302012-01-17 02:30:50 +00004134 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004135}
4136
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004137/// getFloatingTypeOrder - Compare the rank of the two specified floating
4138/// point types, ignoring the domain of the type (i.e. 'double' ==
4139/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004140/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004141int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004142 FloatingRank LHSR = getFloatingRank(LHS);
4143 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004144
Chris Lattnerb90739d2008-04-06 23:38:49 +00004145 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004146 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004147 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004148 return 1;
4149 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004150}
4151
Chris Lattner76a00cf2008-04-06 22:59:24 +00004152/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4153/// routine will assert if passed a built-in type that isn't an integer or enum,
4154/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004155unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004156 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004157
Chris Lattner76a00cf2008-04-06 22:59:24 +00004158 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004159 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004160 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004161 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004162 case BuiltinType::Char_S:
4163 case BuiltinType::Char_U:
4164 case BuiltinType::SChar:
4165 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004166 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004167 case BuiltinType::Short:
4168 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004169 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004170 case BuiltinType::Int:
4171 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004172 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004173 case BuiltinType::Long:
4174 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004175 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004176 case BuiltinType::LongLong:
4177 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004178 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004179 case BuiltinType::Int128:
4180 case BuiltinType::UInt128:
4181 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004182 }
4183}
4184
Eli Friedman629ffb92009-08-20 04:21:42 +00004185/// \brief Whether this is a promotable bitfield reference according
4186/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4187///
4188/// \returns the type this bit-field will promote to, or NULL if no
4189/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004190QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004191 if (E->isTypeDependent() || E->isValueDependent())
4192 return QualType();
4193
Eli Friedman629ffb92009-08-20 04:21:42 +00004194 FieldDecl *Field = E->getBitField();
4195 if (!Field)
4196 return QualType();
4197
4198 QualType FT = Field->getType();
4199
Richard Smithcaf33902011-10-10 18:28:20 +00004200 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004201 uint64_t IntSize = getTypeSize(IntTy);
4202 // GCC extension compatibility: if the bit-field size is less than or equal
4203 // to the size of int, it gets promoted no matter what its type is.
4204 // For instance, unsigned long bf : 4 gets promoted to signed int.
4205 if (BitWidth < IntSize)
4206 return IntTy;
4207
4208 if (BitWidth == IntSize)
4209 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4210
4211 // Types bigger than int are not subject to promotions, and therefore act
4212 // like the base type.
4213 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4214 // is ridiculous.
4215 return QualType();
4216}
4217
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004218/// getPromotedIntegerType - Returns the type that Promotable will
4219/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4220/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004221QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004222 assert(!Promotable.isNull());
4223 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004224 if (const EnumType *ET = Promotable->getAs<EnumType>())
4225 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004226
4227 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4228 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4229 // (3.9.1) can be converted to a prvalue of the first of the following
4230 // types that can represent all the values of its underlying type:
4231 // int, unsigned int, long int, unsigned long int, long long int, or
4232 // unsigned long long int [...]
4233 // FIXME: Is there some better way to compute this?
4234 if (BT->getKind() == BuiltinType::WChar_S ||
4235 BT->getKind() == BuiltinType::WChar_U ||
4236 BT->getKind() == BuiltinType::Char16 ||
4237 BT->getKind() == BuiltinType::Char32) {
4238 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4239 uint64_t FromSize = getTypeSize(BT);
4240 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4241 LongLongTy, UnsignedLongLongTy };
4242 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4243 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4244 if (FromSize < ToSize ||
4245 (FromSize == ToSize &&
4246 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4247 return PromoteTypes[Idx];
4248 }
4249 llvm_unreachable("char type should fit into long long");
4250 }
4251 }
4252
4253 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004254 if (Promotable->isSignedIntegerType())
4255 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004256 uint64_t PromotableSize = getIntWidth(Promotable);
4257 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004258 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4259 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4260}
4261
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004262/// \brief Recurses in pointer/array types until it finds an objc retainable
4263/// type and returns its ownership.
4264Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4265 while (!T.isNull()) {
4266 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4267 return T.getObjCLifetime();
4268 if (T->isArrayType())
4269 T = getBaseElementType(T);
4270 else if (const PointerType *PT = T->getAs<PointerType>())
4271 T = PT->getPointeeType();
4272 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004273 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004274 else
4275 break;
4276 }
4277
4278 return Qualifiers::OCL_None;
4279}
4280
Mike Stump11289f42009-09-09 15:08:12 +00004281/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004282/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004283/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004284int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004285 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4286 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004287 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004288
Chris Lattner76a00cf2008-04-06 22:59:24 +00004289 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4290 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004291
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004292 unsigned LHSRank = getIntegerRank(LHSC);
4293 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004294
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004295 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4296 if (LHSRank == RHSRank) return 0;
4297 return LHSRank > RHSRank ? 1 : -1;
4298 }
Mike Stump11289f42009-09-09 15:08:12 +00004299
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004300 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4301 if (LHSUnsigned) {
4302 // If the unsigned [LHS] type is larger, return it.
4303 if (LHSRank >= RHSRank)
4304 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004305
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004306 // If the signed type can represent all values of the unsigned type, it
4307 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004308 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004309 return -1;
4310 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004311
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004312 // If the unsigned [RHS] type is larger, return it.
4313 if (RHSRank >= LHSRank)
4314 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004315
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004316 // If the signed type can represent all values of the unsigned type, it
4317 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004318 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004319 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004320}
Anders Carlsson98f07902007-08-17 05:31:46 +00004321
Anders Carlsson6d417272009-11-14 21:45:58 +00004322static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004323CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4324 DeclContext *DC, IdentifierInfo *Id) {
4325 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004326 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004327 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004328 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004329 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004330}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004331
Mike Stump11289f42009-09-09 15:08:12 +00004332// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004333QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004334 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00004335 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004336 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004337 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00004338 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004339
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004340 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004341
Anders Carlsson98f07902007-08-17 05:31:46 +00004342 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004343 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004344 // int flags;
4345 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004346 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004347 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004348 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004349 FieldTypes[3] = LongTy;
4350
Anders Carlsson98f07902007-08-17 05:31:46 +00004351 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004352 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004353 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004354 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004355 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004356 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004357 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004358 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004359 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004360 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004361 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004362 }
4363
Douglas Gregord5058122010-02-11 01:19:42 +00004364 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004365 }
Mike Stump11289f42009-09-09 15:08:12 +00004366
Anders Carlsson98f07902007-08-17 05:31:46 +00004367 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004368}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004369
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004370QualType ASTContext::getObjCSuperType() const {
4371 if (ObjCSuperType.isNull()) {
4372 RecordDecl *ObjCSuperTypeDecl =
4373 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4374 TUDecl->addDecl(ObjCSuperTypeDecl);
4375 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4376 }
4377 return ObjCSuperType;
4378}
4379
Douglas Gregor512b0772009-04-23 22:29:11 +00004380void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004381 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004382 assert(Rec && "Invalid CFConstantStringType");
4383 CFConstantStringTypeDecl = Rec->getDecl();
4384}
4385
Jay Foad39c79802011-01-12 09:06:06 +00004386QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004387 if (BlockDescriptorType)
4388 return getTagDeclType(BlockDescriptorType);
4389
4390 RecordDecl *T;
4391 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004392 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004393 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00004394 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004395
4396 QualType FieldTypes[] = {
4397 UnsignedLongTy,
4398 UnsignedLongTy,
4399 };
4400
4401 const char *FieldNames[] = {
4402 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004403 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004404 };
4405
4406 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004407 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00004408 SourceLocation(),
4409 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004410 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00004411 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004412 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004413 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004414 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00004415 T->addDecl(Field);
4416 }
4417
Douglas Gregord5058122010-02-11 01:19:42 +00004418 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004419
4420 BlockDescriptorType = T;
4421
4422 return getTagDeclType(BlockDescriptorType);
4423}
4424
Jay Foad39c79802011-01-12 09:06:06 +00004425QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004426 if (BlockDescriptorExtendedType)
4427 return getTagDeclType(BlockDescriptorExtendedType);
4428
4429 RecordDecl *T;
4430 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004431 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004432 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00004433 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004434
4435 QualType FieldTypes[] = {
4436 UnsignedLongTy,
4437 UnsignedLongTy,
4438 getPointerType(VoidPtrTy),
4439 getPointerType(VoidPtrTy)
4440 };
4441
4442 const char *FieldNames[] = {
4443 "reserved",
4444 "Size",
4445 "CopyFuncPtr",
4446 "DestroyFuncPtr"
4447 };
4448
4449 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004450 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004451 SourceLocation(),
4452 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004453 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004454 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004455 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004456 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004457 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004458 T->addDecl(Field);
4459 }
4460
Douglas Gregord5058122010-02-11 01:19:42 +00004461 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004462
4463 BlockDescriptorExtendedType = T;
4464
4465 return getTagDeclType(BlockDescriptorExtendedType);
4466}
4467
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004468/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4469/// requires copy/dispose. Note that this must match the logic
4470/// in buildByrefHelpers.
4471bool ASTContext::BlockRequiresCopying(QualType Ty,
4472 const VarDecl *D) {
4473 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4474 const Expr *copyExpr = getBlockVarCopyInits(D);
4475 if (!copyExpr && record->hasTrivialDestructor()) return false;
4476
Mike Stump94967902009-10-21 18:16:27 +00004477 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004478 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004479
4480 if (!Ty->isObjCRetainableType()) return false;
4481
4482 Qualifiers qs = Ty.getQualifiers();
4483
4484 // If we have lifetime, that dominates.
4485 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4486 assert(getLangOpts().ObjCAutoRefCount);
4487
4488 switch (lifetime) {
4489 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4490
4491 // These are just bits as far as the runtime is concerned.
4492 case Qualifiers::OCL_ExplicitNone:
4493 case Qualifiers::OCL_Autoreleasing:
4494 return false;
4495
4496 // Tell the runtime that this is ARC __weak, called by the
4497 // byref routines.
4498 case Qualifiers::OCL_Weak:
4499 // ARC __strong __block variables need to be retained.
4500 case Qualifiers::OCL_Strong:
4501 return true;
4502 }
4503 llvm_unreachable("fell out of lifetime switch!");
4504 }
4505 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4506 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004507}
4508
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004509bool ASTContext::getByrefLifetime(QualType Ty,
4510 Qualifiers::ObjCLifetime &LifeTime,
4511 bool &HasByrefExtendedLayout) const {
4512
4513 if (!getLangOpts().ObjC1 ||
4514 getLangOpts().getGC() != LangOptions::NonGC)
4515 return false;
4516
4517 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004518 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004519 HasByrefExtendedLayout = true;
4520 LifeTime = Qualifiers::OCL_None;
4521 }
4522 else if (getLangOpts().ObjCAutoRefCount)
4523 LifeTime = Ty.getObjCLifetime();
4524 // MRR.
4525 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4526 LifeTime = Qualifiers::OCL_ExplicitNone;
4527 else
4528 LifeTime = Qualifiers::OCL_None;
4529 return true;
4530}
4531
Douglas Gregorbab8a962011-09-08 01:46:34 +00004532TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4533 if (!ObjCInstanceTypeDecl)
4534 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4535 getTranslationUnitDecl(),
4536 SourceLocation(),
4537 SourceLocation(),
4538 &Idents.get("instancetype"),
4539 getTrivialTypeSourceInfo(getObjCIdType()));
4540 return ObjCInstanceTypeDecl;
4541}
4542
Anders Carlsson18acd442007-10-29 06:33:42 +00004543// This returns true if a type has been typedefed to BOOL:
4544// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004545static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004546 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004547 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4548 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004549
Anders Carlssond8499822007-10-29 05:01:08 +00004550 return false;
4551}
4552
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004553/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004554/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004555CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004556 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4557 return CharUnits::Zero();
4558
Ken Dyck40775002010-01-11 17:06:35 +00004559 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004560
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004561 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004562 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004563 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004564 // Treat arrays as pointers, since that's how they're passed in.
4565 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004566 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004567 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004568}
4569
4570static inline
4571std::string charUnitsToString(const CharUnits &CU) {
4572 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004573}
4574
John McCall351762c2011-02-07 10:33:21 +00004575/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004576/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004577std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4578 std::string S;
4579
David Chisnall950a9512009-11-17 19:33:30 +00004580 const BlockDecl *Decl = Expr->getBlockDecl();
4581 QualType BlockTy =
4582 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4583 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004584 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004585 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4586 BlockTy->getAs<FunctionType>()->getResultType(),
4587 S, true /*Extended*/);
4588 else
4589 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4590 S);
David Chisnall950a9512009-11-17 19:33:30 +00004591 // Compute size of all parameters.
4592 // Start with computing size of a pointer in number of bytes.
4593 // FIXME: There might(should) be a better way of doing this computation!
4594 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004595 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4596 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004597 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004598 E = Decl->param_end(); PI != E; ++PI) {
4599 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004600 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004601 if (sz.isZero())
4602 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004603 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004604 ParmOffset += sz;
4605 }
4606 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004607 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004608 // Block pointer and offset.
4609 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004610
4611 // Argument types.
4612 ParmOffset = PtrSize;
4613 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4614 Decl->param_end(); PI != E; ++PI) {
4615 ParmVarDecl *PVDecl = *PI;
4616 QualType PType = PVDecl->getOriginalType();
4617 if (const ArrayType *AT =
4618 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4619 // Use array's original type only if it has known number of
4620 // elements.
4621 if (!isa<ConstantArrayType>(AT))
4622 PType = PVDecl->getType();
4623 } else if (PType->isFunctionType())
4624 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004625 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004626 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4627 S, true /*Extended*/);
4628 else
4629 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004630 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004631 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004632 }
John McCall351762c2011-02-07 10:33:21 +00004633
4634 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004635}
4636
Douglas Gregora9d84932011-05-27 01:19:52 +00004637bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004638 std::string& S) {
4639 // Encode result type.
4640 getObjCEncodingForType(Decl->getResultType(), S);
4641 CharUnits ParmOffset;
4642 // Compute size of all parameters.
4643 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4644 E = Decl->param_end(); PI != E; ++PI) {
4645 QualType PType = (*PI)->getType();
4646 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004647 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004648 continue;
4649
David Chisnall50e4eba2010-12-30 14:05:53 +00004650 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004651 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004652 ParmOffset += sz;
4653 }
4654 S += charUnitsToString(ParmOffset);
4655 ParmOffset = CharUnits::Zero();
4656
4657 // Argument types.
4658 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4659 E = Decl->param_end(); PI != E; ++PI) {
4660 ParmVarDecl *PVDecl = *PI;
4661 QualType PType = PVDecl->getOriginalType();
4662 if (const ArrayType *AT =
4663 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4664 // Use array's original type only if it has known number of
4665 // elements.
4666 if (!isa<ConstantArrayType>(AT))
4667 PType = PVDecl->getType();
4668 } else if (PType->isFunctionType())
4669 PType = PVDecl->getType();
4670 getObjCEncodingForType(PType, S);
4671 S += charUnitsToString(ParmOffset);
4672 ParmOffset += getObjCEncodingTypeSize(PType);
4673 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004674
4675 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004676}
4677
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004678/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4679/// method parameter or return type. If Extended, include class names and
4680/// block object types.
4681void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4682 QualType T, std::string& S,
4683 bool Extended) const {
4684 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4685 getObjCEncodingForTypeQualifier(QT, S);
4686 // Encode parameter type.
4687 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4688 true /*OutermostType*/,
4689 false /*EncodingProperty*/,
4690 false /*StructField*/,
4691 Extended /*EncodeBlockParameters*/,
4692 Extended /*EncodeClassNames*/);
4693}
4694
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004695/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004696/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004697bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004698 std::string& S,
4699 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004700 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004701 // Encode return type.
4702 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4703 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004704 // Compute size of all parameters.
4705 // Start with computing size of a pointer in number of bytes.
4706 // FIXME: There might(should) be a better way of doing this computation!
4707 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004708 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004709 // The first two arguments (self and _cmd) are pointers; account for
4710 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004711 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004712 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004713 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004714 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004715 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004716 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004717 continue;
4718
Ken Dyck40775002010-01-11 17:06:35 +00004719 assert (sz.isPositive() &&
4720 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004721 ParmOffset += sz;
4722 }
Ken Dyck40775002010-01-11 17:06:35 +00004723 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004724 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004725 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004726
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004727 // Argument types.
4728 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004729 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004730 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004731 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004732 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004733 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004734 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4735 // Use array's original type only if it has known number of
4736 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004737 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004738 PType = PVDecl->getType();
4739 } else if (PType->isFunctionType())
4740 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004741 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4742 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004743 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004744 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004745 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004746
4747 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004748}
4749
Daniel Dunbar4932b362008-08-28 04:38:10 +00004750/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004751/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004752/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4753/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004754/// Property attributes are stored as a comma-delimited C string. The simple
4755/// attributes readonly and bycopy are encoded as single characters. The
4756/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4757/// encoded as single characters, followed by an identifier. Property types
4758/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004759/// these attributes are defined by the following enumeration:
4760/// @code
4761/// enum PropertyAttributes {
4762/// kPropertyReadOnly = 'R', // property is read-only.
4763/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4764/// kPropertyByref = '&', // property is a reference to the value last assigned
4765/// kPropertyDynamic = 'D', // property is dynamic
4766/// kPropertyGetter = 'G', // followed by getter selector name
4767/// kPropertySetter = 'S', // followed by setter selector name
4768/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004769/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004770/// kPropertyWeak = 'W' // 'weak' property
4771/// kPropertyStrong = 'P' // property GC'able
4772/// kPropertyNonAtomic = 'N' // property non-atomic
4773/// };
4774/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004775void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004776 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004777 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004778 // Collect information from the property implementation decl(s).
4779 bool Dynamic = false;
4780 ObjCPropertyImplDecl *SynthesizePID = 0;
4781
4782 // FIXME: Duplicated code due to poor abstraction.
4783 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004784 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004785 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4786 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004787 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004788 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004789 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004790 if (PID->getPropertyDecl() == PD) {
4791 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4792 Dynamic = true;
4793 } else {
4794 SynthesizePID = PID;
4795 }
4796 }
4797 }
4798 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004799 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004800 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004801 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004802 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004803 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004804 if (PID->getPropertyDecl() == PD) {
4805 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4806 Dynamic = true;
4807 } else {
4808 SynthesizePID = PID;
4809 }
4810 }
Mike Stump11289f42009-09-09 15:08:12 +00004811 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004812 }
4813 }
4814
4815 // FIXME: This is not very efficient.
4816 S = "T";
4817
4818 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004819 // GCC has some special rules regarding encoding of properties which
4820 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004821 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004822 true /* outermost type */,
4823 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004824
4825 if (PD->isReadOnly()) {
4826 S += ",R";
4827 } else {
4828 switch (PD->getSetterKind()) {
4829 case ObjCPropertyDecl::Assign: break;
4830 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004831 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004832 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004833 }
4834 }
4835
4836 // It really isn't clear at all what this means, since properties
4837 // are "dynamic by default".
4838 if (Dynamic)
4839 S += ",D";
4840
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004841 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4842 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004843
Daniel Dunbar4932b362008-08-28 04:38:10 +00004844 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4845 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004846 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004847 }
4848
4849 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4850 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004851 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004852 }
4853
4854 if (SynthesizePID) {
4855 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4856 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004857 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004858 }
4859
4860 // FIXME: OBJCGC: weak & strong
4861}
4862
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004863/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004864/// Another legacy compatibility encoding: 32-bit longs are encoded as
4865/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004866/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4867///
4868void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004869 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004870 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004871 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004872 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004873 else
Jay Foad39c79802011-01-12 09:06:06 +00004874 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004875 PointeeTy = IntTy;
4876 }
4877 }
4878}
4879
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004880void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004881 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004882 // We follow the behavior of gcc, expanding structures which are
4883 // directly pointed to, and expanding embedded structures. Note that
4884 // these rules are sufficient to prevent recursive encoding of the
4885 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004886 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004887 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004888}
4889
John McCall393a78d2012-12-20 02:45:14 +00004890static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
4891 BuiltinType::Kind kind) {
4892 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004893 case BuiltinType::Void: return 'v';
4894 case BuiltinType::Bool: return 'B';
4895 case BuiltinType::Char_U:
4896 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00004897 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00004898 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00004899 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00004900 case BuiltinType::UInt: return 'I';
4901 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00004902 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004903 case BuiltinType::UInt128: return 'T';
4904 case BuiltinType::ULongLong: return 'Q';
4905 case BuiltinType::Char_S:
4906 case BuiltinType::SChar: return 'c';
4907 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004908 case BuiltinType::WChar_S:
4909 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004910 case BuiltinType::Int: return 'i';
4911 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00004912 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004913 case BuiltinType::LongLong: return 'q';
4914 case BuiltinType::Int128: return 't';
4915 case BuiltinType::Float: return 'f';
4916 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004917 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00004918 case BuiltinType::NullPtr: return '*'; // like char*
4919
4920 case BuiltinType::Half:
4921 // FIXME: potentially need @encodes for these!
4922 return ' ';
4923
4924 case BuiltinType::ObjCId:
4925 case BuiltinType::ObjCClass:
4926 case BuiltinType::ObjCSel:
4927 llvm_unreachable("@encoding ObjC primitive type");
4928
4929 // OpenCL and placeholder types don't need @encodings.
4930 case BuiltinType::OCLImage1d:
4931 case BuiltinType::OCLImage1dArray:
4932 case BuiltinType::OCLImage1dBuffer:
4933 case BuiltinType::OCLImage2d:
4934 case BuiltinType::OCLImage2dArray:
4935 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004936 case BuiltinType::OCLEvent:
Guy Benyei61054192013-02-07 10:55:47 +00004937 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00004938 case BuiltinType::Dependent:
4939#define BUILTIN_TYPE(KIND, ID)
4940#define PLACEHOLDER_TYPE(KIND, ID) \
4941 case BuiltinType::KIND:
4942#include "clang/AST/BuiltinTypes.def"
4943 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00004944 }
David Blaikie5a6a0202013-01-09 17:48:41 +00004945 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00004946}
4947
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004948static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4949 EnumDecl *Enum = ET->getDecl();
4950
4951 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4952 if (!Enum->isFixed())
4953 return 'i';
4954
4955 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00004956 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
4957 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004958}
4959
Jay Foad39c79802011-01-12 09:06:06 +00004960static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004961 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004962 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004963 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004964 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4965 // The GNU runtime requires more information; bitfields are encoded as b,
4966 // then the offset (in bits) of the first element, then the type of the
4967 // bitfield, then the size in bits. For example, in this structure:
4968 //
4969 // struct
4970 // {
4971 // int integer;
4972 // int flags:2;
4973 // };
4974 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4975 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4976 // information is not especially sensible, but we're stuck with it for
4977 // compatibility with GCC, although providing it breaks anything that
4978 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00004979 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004980 const RecordDecl *RD = FD->getParent();
4981 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004982 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004983 if (const EnumType *ET = T->getAs<EnumType>())
4984 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00004985 else {
4986 const BuiltinType *BT = T->castAs<BuiltinType>();
4987 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
4988 }
David Chisnallb190a2c2010-06-04 01:10:52 +00004989 }
Richard Smithcaf33902011-10-10 18:28:20 +00004990 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004991}
4992
Daniel Dunbar07d07852009-10-18 21:17:35 +00004993// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004994void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4995 bool ExpandPointedToStructures,
4996 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004997 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004998 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004999 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005000 bool StructField,
5001 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005002 bool EncodeClassNames,
5003 bool EncodePointerToObjCTypedef) const {
John McCall393a78d2012-12-20 02:45:14 +00005004 CanQualType CT = getCanonicalType(T);
5005 switch (CT->getTypeClass()) {
5006 case Type::Builtin:
5007 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005008 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005009 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005010 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5011 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5012 else
5013 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005014 return;
Mike Stump11289f42009-09-09 15:08:12 +00005015
John McCall393a78d2012-12-20 02:45:14 +00005016 case Type::Complex: {
5017 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005018 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00005019 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00005020 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005021 return;
5022 }
John McCall393a78d2012-12-20 02:45:14 +00005023
5024 case Type::Atomic: {
5025 const AtomicType *AT = T->castAs<AtomicType>();
5026 S += 'A';
5027 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5028 false, false);
5029 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005030 }
John McCall393a78d2012-12-20 02:45:14 +00005031
5032 // encoding for pointer or reference types.
5033 case Type::Pointer:
5034 case Type::LValueReference:
5035 case Type::RValueReference: {
5036 QualType PointeeTy;
5037 if (isa<PointerType>(CT)) {
5038 const PointerType *PT = T->castAs<PointerType>();
5039 if (PT->isObjCSelType()) {
5040 S += ':';
5041 return;
5042 }
5043 PointeeTy = PT->getPointeeType();
5044 } else {
5045 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5046 }
5047
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005048 bool isReadOnly = false;
5049 // For historical/compatibility reasons, the read-only qualifier of the
5050 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5051 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005052 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005053 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005054 if (OutermostType && T.isConstQualified()) {
5055 isReadOnly = true;
5056 S += 'r';
5057 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005058 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005059 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005060 while (P->getAs<PointerType>())
5061 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005062 if (P.isConstQualified()) {
5063 isReadOnly = true;
5064 S += 'r';
5065 }
5066 }
5067 if (isReadOnly) {
5068 // Another legacy compatibility encoding. Some ObjC qualifier and type
5069 // combinations need to be rearranged.
5070 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005071 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005072 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005073 }
Mike Stump11289f42009-09-09 15:08:12 +00005074
Anders Carlssond8499822007-10-29 05:01:08 +00005075 if (PointeeTy->isCharType()) {
5076 // char pointer types should be encoded as '*' unless it is a
5077 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005078 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005079 S += '*';
5080 return;
5081 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005082 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005083 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5084 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5085 S += '#';
5086 return;
5087 }
5088 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5089 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5090 S += '@';
5091 return;
5092 }
5093 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005094 }
Anders Carlssond8499822007-10-29 05:01:08 +00005095 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005096 getLegacyIntegralTypeEncoding(PointeeTy);
5097
Mike Stump11289f42009-09-09 15:08:12 +00005098 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005099 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005100 return;
5101 }
John McCall393a78d2012-12-20 02:45:14 +00005102
5103 case Type::ConstantArray:
5104 case Type::IncompleteArray:
5105 case Type::VariableArray: {
5106 const ArrayType *AT = cast<ArrayType>(CT);
5107
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005108 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005109 // Incomplete arrays are encoded as a pointer to the array element.
5110 S += '^';
5111
Mike Stump11289f42009-09-09 15:08:12 +00005112 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005113 false, ExpandStructures, FD);
5114 } else {
5115 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005116
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005117 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
5118 if (getTypeSize(CAT->getElementType()) == 0)
5119 S += '0';
5120 else
5121 S += llvm::utostr(CAT->getSize().getZExtValue());
5122 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005123 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005124 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5125 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005126 S += '0';
5127 }
Mike Stump11289f42009-09-09 15:08:12 +00005128
5129 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005130 false, ExpandStructures, FD);
5131 S += ']';
5132 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005133 return;
5134 }
Mike Stump11289f42009-09-09 15:08:12 +00005135
John McCall393a78d2012-12-20 02:45:14 +00005136 case Type::FunctionNoProto:
5137 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005138 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005139 return;
Mike Stump11289f42009-09-09 15:08:12 +00005140
John McCall393a78d2012-12-20 02:45:14 +00005141 case Type::Record: {
5142 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005143 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005144 // Anonymous structures print as '?'
5145 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5146 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005147 if (ClassTemplateSpecializationDecl *Spec
5148 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5149 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005150 llvm::raw_string_ostream OS(S);
5151 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005152 TemplateArgs.data(),
5153 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005154 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005155 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005156 } else {
5157 S += '?';
5158 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005159 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005160 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005161 if (!RDecl->isUnion()) {
5162 getObjCEncodingForStructureImpl(RDecl, S, FD);
5163 } else {
5164 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5165 FieldEnd = RDecl->field_end();
5166 Field != FieldEnd; ++Field) {
5167 if (FD) {
5168 S += '"';
5169 S += Field->getNameAsString();
5170 S += '"';
5171 }
Mike Stump11289f42009-09-09 15:08:12 +00005172
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005173 // Special case bit-fields.
5174 if (Field->isBitField()) {
5175 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00005176 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005177 } else {
5178 QualType qt = Field->getType();
5179 getLegacyIntegralTypeEncoding(qt);
5180 getObjCEncodingForTypeImpl(qt, S, false, true,
5181 FD, /*OutermostType*/false,
5182 /*EncodingProperty*/false,
5183 /*StructField*/true);
5184 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005185 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005186 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005187 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005188 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005189 return;
5190 }
Mike Stump11289f42009-09-09 15:08:12 +00005191
John McCall393a78d2012-12-20 02:45:14 +00005192 case Type::BlockPointer: {
5193 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005194 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005195 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005196 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005197
5198 S += '<';
5199 // Block return type
5200 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5201 ExpandPointedToStructures, ExpandStructures,
5202 FD,
5203 false /* OutermostType */,
5204 EncodingProperty,
5205 false /* StructField */,
5206 EncodeBlockParameters,
5207 EncodeClassNames);
5208 // Block self
5209 S += "@?";
5210 // Block parameters
5211 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5212 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5213 E = FPT->arg_type_end(); I && (I != E); ++I) {
5214 getObjCEncodingForTypeImpl(*I, S,
5215 ExpandPointedToStructures,
5216 ExpandStructures,
5217 FD,
5218 false /* OutermostType */,
5219 EncodingProperty,
5220 false /* StructField */,
5221 EncodeBlockParameters,
5222 EncodeClassNames);
5223 }
5224 }
5225 S += '>';
5226 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005227 return;
5228 }
Mike Stump11289f42009-09-09 15:08:12 +00005229
John McCall393a78d2012-12-20 02:45:14 +00005230 case Type::ObjCObject:
5231 case Type::ObjCInterface: {
5232 // Ignore protocol qualifiers when mangling at this level.
5233 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005234
John McCall393a78d2012-12-20 02:45:14 +00005235 // The assumption seems to be that this assert will succeed
5236 // because nested levels will have filtered out 'id' and 'Class'.
5237 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005238 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005239 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005240 S += '{';
5241 const IdentifierInfo *II = OI->getIdentifier();
5242 S += II->getName();
5243 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005244 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005245 DeepCollectObjCIvars(OI, true, Ivars);
5246 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005247 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005248 if (Field->isBitField())
5249 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005250 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005251 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5252 false, false, false, false, false,
5253 EncodePointerToObjCTypedef);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005254 }
5255 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005256 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005257 }
Mike Stump11289f42009-09-09 15:08:12 +00005258
John McCall393a78d2012-12-20 02:45:14 +00005259 case Type::ObjCObjectPointer: {
5260 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005261 if (OPT->isObjCIdType()) {
5262 S += '@';
5263 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005264 }
Mike Stump11289f42009-09-09 15:08:12 +00005265
Steve Narofff0c86112009-10-28 22:03:49 +00005266 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5267 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5268 // Since this is a binary compatibility issue, need to consult with runtime
5269 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005270 S += '#';
5271 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005272 }
Mike Stump11289f42009-09-09 15:08:12 +00005273
Chris Lattnere7cabb92009-07-13 00:10:46 +00005274 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005275 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005276 ExpandPointedToStructures,
5277 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005278 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005279 // Note that we do extended encoding of protocol qualifer list
5280 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005281 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00005282 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5283 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005284 S += '<';
5285 S += (*I)->getNameAsString();
5286 S += '>';
5287 }
5288 S += '"';
5289 }
5290 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005291 }
Mike Stump11289f42009-09-09 15:08:12 +00005292
Chris Lattnere7cabb92009-07-13 00:10:46 +00005293 QualType PointeeTy = OPT->getPointeeType();
5294 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005295 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5296 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005297 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005298 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005299 // {...};
5300 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00005301 getObjCEncodingForTypeImpl(PointeeTy, S,
5302 false, ExpandPointedToStructures,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005303 NULL,
5304 false, false, false, false, false,
5305 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005306 return;
5307 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005308
5309 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005310 if (OPT->getInterfaceDecl() &&
5311 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005312 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005313 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00005314 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5315 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005316 S += '<';
5317 S += (*I)->getNameAsString();
5318 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005319 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005320 S += '"';
5321 }
5322 return;
5323 }
Mike Stump11289f42009-09-09 15:08:12 +00005324
John McCalla9e6e8d2010-05-17 23:56:34 +00005325 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005326 // FIXME: we shoul do better than that. 'M' is available.
5327 case Type::MemberPointer:
John McCalla9e6e8d2010-05-17 23:56:34 +00005328 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005329
John McCall393a78d2012-12-20 02:45:14 +00005330 case Type::Vector:
5331 case Type::ExtVector:
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005332 // This matches gcc's encoding, even though technically it is
5333 // insufficient.
5334 // FIXME. We should do a better job than gcc.
5335 return;
John McCall393a78d2012-12-20 02:45:14 +00005336
5337#define ABSTRACT_TYPE(KIND, BASE)
5338#define TYPE(KIND, BASE)
5339#define DEPENDENT_TYPE(KIND, BASE) \
5340 case Type::KIND:
5341#define NON_CANONICAL_TYPE(KIND, BASE) \
5342 case Type::KIND:
5343#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5344 case Type::KIND:
5345#include "clang/AST/TypeNodes.def"
5346 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005347 }
John McCall393a78d2012-12-20 02:45:14 +00005348 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005349}
5350
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005351void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5352 std::string &S,
5353 const FieldDecl *FD,
5354 bool includeVBases) const {
5355 assert(RDecl && "Expected non-null RecordDecl");
5356 assert(!RDecl->isUnion() && "Should not be called for unions");
5357 if (!RDecl->getDefinition())
5358 return;
5359
5360 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5361 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5362 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5363
5364 if (CXXRec) {
5365 for (CXXRecordDecl::base_class_iterator
5366 BI = CXXRec->bases_begin(),
5367 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5368 if (!BI->isVirtual()) {
5369 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005370 if (base->isEmpty())
5371 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005372 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005373 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5374 std::make_pair(offs, base));
5375 }
5376 }
5377 }
5378
5379 unsigned i = 0;
5380 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5381 FieldEnd = RDecl->field_end();
5382 Field != FieldEnd; ++Field, ++i) {
5383 uint64_t offs = layout.getFieldOffset(i);
5384 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005385 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005386 }
5387
5388 if (CXXRec && includeVBases) {
5389 for (CXXRecordDecl::base_class_iterator
5390 BI = CXXRec->vbases_begin(),
5391 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5392 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005393 if (base->isEmpty())
5394 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005395 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005396 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5397 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5398 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005399 }
5400 }
5401
5402 CharUnits size;
5403 if (CXXRec) {
5404 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5405 } else {
5406 size = layout.getSize();
5407 }
5408
5409 uint64_t CurOffs = 0;
5410 std::multimap<uint64_t, NamedDecl *>::iterator
5411 CurLayObj = FieldOrBaseOffsets.begin();
5412
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005413 if (CXXRec && CXXRec->isDynamicClass() &&
5414 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005415 if (FD) {
5416 S += "\"_vptr$";
5417 std::string recname = CXXRec->getNameAsString();
5418 if (recname.empty()) recname = "?";
5419 S += recname;
5420 S += '"';
5421 }
5422 S += "^^?";
5423 CurOffs += getTypeSize(VoidPtrTy);
5424 }
5425
5426 if (!RDecl->hasFlexibleArrayMember()) {
5427 // Mark the end of the structure.
5428 uint64_t offs = toBits(size);
5429 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5430 std::make_pair(offs, (NamedDecl*)0));
5431 }
5432
5433 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5434 assert(CurOffs <= CurLayObj->first);
5435
5436 if (CurOffs < CurLayObj->first) {
5437 uint64_t padding = CurLayObj->first - CurOffs;
5438 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5439 // packing/alignment of members is different that normal, in which case
5440 // the encoding will be out-of-sync with the real layout.
5441 // If the runtime switches to just consider the size of types without
5442 // taking into account alignment, we could make padding explicit in the
5443 // encoding (e.g. using arrays of chars). The encoding strings would be
5444 // longer then though.
5445 CurOffs += padding;
5446 }
5447
5448 NamedDecl *dcl = CurLayObj->second;
5449 if (dcl == 0)
5450 break; // reached end of structure.
5451
5452 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5453 // We expand the bases without their virtual bases since those are going
5454 // in the initial structure. Note that this differs from gcc which
5455 // expands virtual bases each time one is encountered in the hierarchy,
5456 // making the encoding type bigger than it really is.
5457 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005458 assert(!base->isEmpty());
5459 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005460 } else {
5461 FieldDecl *field = cast<FieldDecl>(dcl);
5462 if (FD) {
5463 S += '"';
5464 S += field->getNameAsString();
5465 S += '"';
5466 }
5467
5468 if (field->isBitField()) {
5469 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00005470 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005471 } else {
5472 QualType qt = field->getType();
5473 getLegacyIntegralTypeEncoding(qt);
5474 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5475 /*OutermostType*/false,
5476 /*EncodingProperty*/false,
5477 /*StructField*/true);
5478 CurOffs += getTypeSize(field->getType());
5479 }
5480 }
5481 }
5482}
5483
Mike Stump11289f42009-09-09 15:08:12 +00005484void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005485 std::string& S) const {
5486 if (QT & Decl::OBJC_TQ_In)
5487 S += 'n';
5488 if (QT & Decl::OBJC_TQ_Inout)
5489 S += 'N';
5490 if (QT & Decl::OBJC_TQ_Out)
5491 S += 'o';
5492 if (QT & Decl::OBJC_TQ_Bycopy)
5493 S += 'O';
5494 if (QT & Decl::OBJC_TQ_Byref)
5495 S += 'R';
5496 if (QT & Decl::OBJC_TQ_Oneway)
5497 S += 'V';
5498}
5499
Douglas Gregor3ea72692011-08-12 05:46:01 +00005500TypedefDecl *ASTContext::getObjCIdDecl() const {
5501 if (!ObjCIdDecl) {
5502 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5503 T = getObjCObjectPointerType(T);
5504 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5505 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5506 getTranslationUnitDecl(),
5507 SourceLocation(), SourceLocation(),
5508 &Idents.get("id"), IdInfo);
5509 }
5510
5511 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005512}
5513
Douglas Gregor52e02802011-08-12 06:17:30 +00005514TypedefDecl *ASTContext::getObjCSelDecl() const {
5515 if (!ObjCSelDecl) {
5516 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5517 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5518 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5519 getTranslationUnitDecl(),
5520 SourceLocation(), SourceLocation(),
5521 &Idents.get("SEL"), SelInfo);
5522 }
5523 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005524}
5525
Douglas Gregor0a586182011-08-12 05:59:41 +00005526TypedefDecl *ASTContext::getObjCClassDecl() const {
5527 if (!ObjCClassDecl) {
5528 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5529 T = getObjCObjectPointerType(T);
5530 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5531 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5532 getTranslationUnitDecl(),
5533 SourceLocation(), SourceLocation(),
5534 &Idents.get("Class"), ClassInfo);
5535 }
5536
5537 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005538}
5539
Douglas Gregord53ae832012-01-17 18:09:05 +00005540ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5541 if (!ObjCProtocolClassDecl) {
5542 ObjCProtocolClassDecl
5543 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5544 SourceLocation(),
5545 &Idents.get("Protocol"),
5546 /*PrevDecl=*/0,
5547 SourceLocation(), true);
5548 }
5549
5550 return ObjCProtocolClassDecl;
5551}
5552
Meador Inge5d3fb222012-06-16 03:34:49 +00005553//===----------------------------------------------------------------------===//
5554// __builtin_va_list Construction Functions
5555//===----------------------------------------------------------------------===//
5556
5557static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5558 // typedef char* __builtin_va_list;
5559 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5560 TypeSourceInfo *TInfo
5561 = Context->getTrivialTypeSourceInfo(CharPtrType);
5562
5563 TypedefDecl *VaListTypeDecl
5564 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5565 Context->getTranslationUnitDecl(),
5566 SourceLocation(), SourceLocation(),
5567 &Context->Idents.get("__builtin_va_list"),
5568 TInfo);
5569 return VaListTypeDecl;
5570}
5571
5572static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5573 // typedef void* __builtin_va_list;
5574 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5575 TypeSourceInfo *TInfo
5576 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5577
5578 TypedefDecl *VaListTypeDecl
5579 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5580 Context->getTranslationUnitDecl(),
5581 SourceLocation(), SourceLocation(),
5582 &Context->Idents.get("__builtin_va_list"),
5583 TInfo);
5584 return VaListTypeDecl;
5585}
5586
Tim Northover9bb857a2013-01-31 12:13:10 +00005587static TypedefDecl *
5588CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5589 RecordDecl *VaListTagDecl;
5590 if (Context->getLangOpts().CPlusPlus) {
5591 // namespace std { struct __va_list {
5592 NamespaceDecl *NS;
5593 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5594 Context->getTranslationUnitDecl(),
5595 /*Inline*/false, SourceLocation(),
5596 SourceLocation(), &Context->Idents.get("std"),
5597 /*PrevDecl*/0);
5598
5599 VaListTagDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5600 Context->getTranslationUnitDecl(),
5601 SourceLocation(), SourceLocation(),
5602 &Context->Idents.get("__va_list"));
5603 VaListTagDecl->setDeclContext(NS);
5604 } else {
5605 // struct __va_list
5606 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5607 Context->getTranslationUnitDecl(),
5608 &Context->Idents.get("__va_list"));
5609 }
5610
5611 VaListTagDecl->startDefinition();
5612
5613 const size_t NumFields = 5;
5614 QualType FieldTypes[NumFields];
5615 const char *FieldNames[NumFields];
5616
5617 // void *__stack;
5618 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5619 FieldNames[0] = "__stack";
5620
5621 // void *__gr_top;
5622 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5623 FieldNames[1] = "__gr_top";
5624
5625 // void *__vr_top;
5626 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5627 FieldNames[2] = "__vr_top";
5628
5629 // int __gr_offs;
5630 FieldTypes[3] = Context->IntTy;
5631 FieldNames[3] = "__gr_offs";
5632
5633 // int __vr_offs;
5634 FieldTypes[4] = Context->IntTy;
5635 FieldNames[4] = "__vr_offs";
5636
5637 // Create fields
5638 for (unsigned i = 0; i < NumFields; ++i) {
5639 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5640 VaListTagDecl,
5641 SourceLocation(),
5642 SourceLocation(),
5643 &Context->Idents.get(FieldNames[i]),
5644 FieldTypes[i], /*TInfo=*/0,
5645 /*BitWidth=*/0,
5646 /*Mutable=*/false,
5647 ICIS_NoInit);
5648 Field->setAccess(AS_public);
5649 VaListTagDecl->addDecl(Field);
5650 }
5651 VaListTagDecl->completeDefinition();
5652 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5653 Context->VaListTagTy = VaListTagType;
5654
5655 // } __builtin_va_list;
5656 TypedefDecl *VaListTypedefDecl
5657 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5658 Context->getTranslationUnitDecl(),
5659 SourceLocation(), SourceLocation(),
5660 &Context->Idents.get("__builtin_va_list"),
5661 Context->getTrivialTypeSourceInfo(VaListTagType));
5662
5663 return VaListTypedefDecl;
5664}
5665
Meador Inge5d3fb222012-06-16 03:34:49 +00005666static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5667 // typedef struct __va_list_tag {
5668 RecordDecl *VaListTagDecl;
5669
5670 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5671 Context->getTranslationUnitDecl(),
5672 &Context->Idents.get("__va_list_tag"));
5673 VaListTagDecl->startDefinition();
5674
5675 const size_t NumFields = 5;
5676 QualType FieldTypes[NumFields];
5677 const char *FieldNames[NumFields];
5678
5679 // unsigned char gpr;
5680 FieldTypes[0] = Context->UnsignedCharTy;
5681 FieldNames[0] = "gpr";
5682
5683 // unsigned char fpr;
5684 FieldTypes[1] = Context->UnsignedCharTy;
5685 FieldNames[1] = "fpr";
5686
5687 // unsigned short reserved;
5688 FieldTypes[2] = Context->UnsignedShortTy;
5689 FieldNames[2] = "reserved";
5690
5691 // void* overflow_arg_area;
5692 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5693 FieldNames[3] = "overflow_arg_area";
5694
5695 // void* reg_save_area;
5696 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5697 FieldNames[4] = "reg_save_area";
5698
5699 // Create fields
5700 for (unsigned i = 0; i < NumFields; ++i) {
5701 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5702 SourceLocation(),
5703 SourceLocation(),
5704 &Context->Idents.get(FieldNames[i]),
5705 FieldTypes[i], /*TInfo=*/0,
5706 /*BitWidth=*/0,
5707 /*Mutable=*/false,
5708 ICIS_NoInit);
5709 Field->setAccess(AS_public);
5710 VaListTagDecl->addDecl(Field);
5711 }
5712 VaListTagDecl->completeDefinition();
5713 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005714 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005715
5716 // } __va_list_tag;
5717 TypedefDecl *VaListTagTypedefDecl
5718 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5719 Context->getTranslationUnitDecl(),
5720 SourceLocation(), SourceLocation(),
5721 &Context->Idents.get("__va_list_tag"),
5722 Context->getTrivialTypeSourceInfo(VaListTagType));
5723 QualType VaListTagTypedefType =
5724 Context->getTypedefType(VaListTagTypedefDecl);
5725
5726 // typedef __va_list_tag __builtin_va_list[1];
5727 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5728 QualType VaListTagArrayType
5729 = Context->getConstantArrayType(VaListTagTypedefType,
5730 Size, ArrayType::Normal, 0);
5731 TypeSourceInfo *TInfo
5732 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5733 TypedefDecl *VaListTypedefDecl
5734 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5735 Context->getTranslationUnitDecl(),
5736 SourceLocation(), SourceLocation(),
5737 &Context->Idents.get("__builtin_va_list"),
5738 TInfo);
5739
5740 return VaListTypedefDecl;
5741}
5742
5743static TypedefDecl *
5744CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5745 // typedef struct __va_list_tag {
5746 RecordDecl *VaListTagDecl;
5747 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5748 Context->getTranslationUnitDecl(),
5749 &Context->Idents.get("__va_list_tag"));
5750 VaListTagDecl->startDefinition();
5751
5752 const size_t NumFields = 4;
5753 QualType FieldTypes[NumFields];
5754 const char *FieldNames[NumFields];
5755
5756 // unsigned gp_offset;
5757 FieldTypes[0] = Context->UnsignedIntTy;
5758 FieldNames[0] = "gp_offset";
5759
5760 // unsigned fp_offset;
5761 FieldTypes[1] = Context->UnsignedIntTy;
5762 FieldNames[1] = "fp_offset";
5763
5764 // void* overflow_arg_area;
5765 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5766 FieldNames[2] = "overflow_arg_area";
5767
5768 // void* reg_save_area;
5769 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5770 FieldNames[3] = "reg_save_area";
5771
5772 // Create fields
5773 for (unsigned i = 0; i < NumFields; ++i) {
5774 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5775 VaListTagDecl,
5776 SourceLocation(),
5777 SourceLocation(),
5778 &Context->Idents.get(FieldNames[i]),
5779 FieldTypes[i], /*TInfo=*/0,
5780 /*BitWidth=*/0,
5781 /*Mutable=*/false,
5782 ICIS_NoInit);
5783 Field->setAccess(AS_public);
5784 VaListTagDecl->addDecl(Field);
5785 }
5786 VaListTagDecl->completeDefinition();
5787 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005788 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005789
5790 // } __va_list_tag;
5791 TypedefDecl *VaListTagTypedefDecl
5792 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5793 Context->getTranslationUnitDecl(),
5794 SourceLocation(), SourceLocation(),
5795 &Context->Idents.get("__va_list_tag"),
5796 Context->getTrivialTypeSourceInfo(VaListTagType));
5797 QualType VaListTagTypedefType =
5798 Context->getTypedefType(VaListTagTypedefDecl);
5799
5800 // typedef __va_list_tag __builtin_va_list[1];
5801 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5802 QualType VaListTagArrayType
5803 = Context->getConstantArrayType(VaListTagTypedefType,
5804 Size, ArrayType::Normal,0);
5805 TypeSourceInfo *TInfo
5806 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5807 TypedefDecl *VaListTypedefDecl
5808 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5809 Context->getTranslationUnitDecl(),
5810 SourceLocation(), SourceLocation(),
5811 &Context->Idents.get("__builtin_va_list"),
5812 TInfo);
5813
5814 return VaListTypedefDecl;
5815}
5816
5817static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5818 // typedef int __builtin_va_list[4];
5819 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5820 QualType IntArrayType
5821 = Context->getConstantArrayType(Context->IntTy,
5822 Size, ArrayType::Normal, 0);
5823 TypedefDecl *VaListTypedefDecl
5824 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5825 Context->getTranslationUnitDecl(),
5826 SourceLocation(), SourceLocation(),
5827 &Context->Idents.get("__builtin_va_list"),
5828 Context->getTrivialTypeSourceInfo(IntArrayType));
5829
5830 return VaListTypedefDecl;
5831}
5832
Logan Chien57086ce2012-10-10 06:56:20 +00005833static TypedefDecl *
5834CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5835 RecordDecl *VaListDecl;
5836 if (Context->getLangOpts().CPlusPlus) {
5837 // namespace std { struct __va_list {
5838 NamespaceDecl *NS;
5839 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5840 Context->getTranslationUnitDecl(),
5841 /*Inline*/false, SourceLocation(),
5842 SourceLocation(), &Context->Idents.get("std"),
5843 /*PrevDecl*/0);
5844
5845 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5846 Context->getTranslationUnitDecl(),
5847 SourceLocation(), SourceLocation(),
5848 &Context->Idents.get("__va_list"));
5849
5850 VaListDecl->setDeclContext(NS);
5851
5852 } else {
5853 // struct __va_list {
5854 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
5855 Context->getTranslationUnitDecl(),
5856 &Context->Idents.get("__va_list"));
5857 }
5858
5859 VaListDecl->startDefinition();
5860
5861 // void * __ap;
5862 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5863 VaListDecl,
5864 SourceLocation(),
5865 SourceLocation(),
5866 &Context->Idents.get("__ap"),
5867 Context->getPointerType(Context->VoidTy),
5868 /*TInfo=*/0,
5869 /*BitWidth=*/0,
5870 /*Mutable=*/false,
5871 ICIS_NoInit);
5872 Field->setAccess(AS_public);
5873 VaListDecl->addDecl(Field);
5874
5875 // };
5876 VaListDecl->completeDefinition();
5877
5878 // typedef struct __va_list __builtin_va_list;
5879 TypeSourceInfo *TInfo
5880 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
5881
5882 TypedefDecl *VaListTypeDecl
5883 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5884 Context->getTranslationUnitDecl(),
5885 SourceLocation(), SourceLocation(),
5886 &Context->Idents.get("__builtin_va_list"),
5887 TInfo);
5888
5889 return VaListTypeDecl;
5890}
5891
Meador Inge5d3fb222012-06-16 03:34:49 +00005892static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5893 TargetInfo::BuiltinVaListKind Kind) {
5894 switch (Kind) {
5895 case TargetInfo::CharPtrBuiltinVaList:
5896 return CreateCharPtrBuiltinVaListDecl(Context);
5897 case TargetInfo::VoidPtrBuiltinVaList:
5898 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00005899 case TargetInfo::AArch64ABIBuiltinVaList:
5900 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00005901 case TargetInfo::PowerABIBuiltinVaList:
5902 return CreatePowerABIBuiltinVaListDecl(Context);
5903 case TargetInfo::X86_64ABIBuiltinVaList:
5904 return CreateX86_64ABIBuiltinVaListDecl(Context);
5905 case TargetInfo::PNaClABIBuiltinVaList:
5906 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00005907 case TargetInfo::AAPCSABIBuiltinVaList:
5908 return CreateAAPCSABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00005909 }
5910
5911 llvm_unreachable("Unhandled __builtin_va_list type kind");
5912}
5913
5914TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5915 if (!BuiltinVaListDecl)
5916 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5917
5918 return BuiltinVaListDecl;
5919}
5920
Meador Ingecfb60902012-07-01 15:57:25 +00005921QualType ASTContext::getVaListTagType() const {
5922 // Force the creation of VaListTagTy by building the __builtin_va_list
5923 // declaration.
5924 if (VaListTagTy.isNull())
5925 (void) getBuiltinVaListDecl();
5926
5927 return VaListTagTy;
5928}
5929
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005930void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00005931 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00005932 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00005933
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005934 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00005935}
5936
John McCalld28ae272009-12-02 08:04:21 +00005937/// \brief Retrieve the template name that corresponds to a non-empty
5938/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00005939TemplateName
5940ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5941 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00005942 unsigned size = End - Begin;
5943 assert(size > 1 && "set is not overloaded!");
5944
5945 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5946 size * sizeof(FunctionTemplateDecl*));
5947 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5948
5949 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00005950 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00005951 NamedDecl *D = *I;
5952 assert(isa<FunctionTemplateDecl>(D) ||
5953 (isa<UsingShadowDecl>(D) &&
5954 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5955 *Storage++ = D;
5956 }
5957
5958 return TemplateName(OT);
5959}
5960
Douglas Gregordc572a32009-03-30 22:58:21 +00005961/// \brief Retrieve the template name that represents a qualified
5962/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00005963TemplateName
5964ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5965 bool TemplateKeyword,
5966 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00005967 assert(NNS && "Missing nested-name-specifier in qualified template name");
5968
Douglas Gregorc42075a2010-02-04 18:10:26 +00005969 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00005970 llvm::FoldingSetNodeID ID;
5971 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5972
5973 void *InsertPos = 0;
5974 QualifiedTemplateName *QTN =
5975 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5976 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00005977 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
5978 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00005979 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5980 }
5981
5982 return TemplateName(QTN);
5983}
5984
5985/// \brief Retrieve the template name that represents a dependent
5986/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00005987TemplateName
5988ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5989 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00005990 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00005991 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00005992
5993 llvm::FoldingSetNodeID ID;
5994 DependentTemplateName::Profile(ID, NNS, Name);
5995
5996 void *InsertPos = 0;
5997 DependentTemplateName *QTN =
5998 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5999
6000 if (QTN)
6001 return TemplateName(QTN);
6002
6003 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6004 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006005 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6006 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006007 } else {
6008 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006009 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6010 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006011 DependentTemplateName *CheckQTN =
6012 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6013 assert(!CheckQTN && "Dependent type name canonicalization broken");
6014 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006015 }
6016
6017 DependentTemplateNames.InsertNode(QTN, InsertPos);
6018 return TemplateName(QTN);
6019}
6020
Douglas Gregor71395fa2009-11-04 00:56:37 +00006021/// \brief Retrieve the template name that represents a dependent
6022/// template name such as \c MetaFun::template operator+.
6023TemplateName
6024ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006025 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006026 assert((!NNS || NNS->isDependent()) &&
6027 "Nested name specifier must be dependent");
6028
6029 llvm::FoldingSetNodeID ID;
6030 DependentTemplateName::Profile(ID, NNS, Operator);
6031
6032 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006033 DependentTemplateName *QTN
6034 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006035
6036 if (QTN)
6037 return TemplateName(QTN);
6038
6039 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6040 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006041 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6042 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006043 } else {
6044 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006045 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6046 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006047
6048 DependentTemplateName *CheckQTN
6049 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6050 assert(!CheckQTN && "Dependent template name canonicalization broken");
6051 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006052 }
6053
6054 DependentTemplateNames.InsertNode(QTN, InsertPos);
6055 return TemplateName(QTN);
6056}
6057
Douglas Gregor5590be02011-01-15 06:45:20 +00006058TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006059ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6060 TemplateName replacement) const {
6061 llvm::FoldingSetNodeID ID;
6062 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6063
6064 void *insertPos = 0;
6065 SubstTemplateTemplateParmStorage *subst
6066 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6067
6068 if (!subst) {
6069 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6070 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6071 }
6072
6073 return TemplateName(subst);
6074}
6075
6076TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006077ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6078 const TemplateArgument &ArgPack) const {
6079 ASTContext &Self = const_cast<ASTContext &>(*this);
6080 llvm::FoldingSetNodeID ID;
6081 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6082
6083 void *InsertPos = 0;
6084 SubstTemplateTemplateParmPackStorage *Subst
6085 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6086
6087 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006088 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006089 ArgPack.pack_size(),
6090 ArgPack.pack_begin());
6091 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6092 }
6093
6094 return TemplateName(Subst);
6095}
6096
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006097/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006098/// TargetInfo, produce the corresponding type. The unsigned @p Type
6099/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006100CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006101 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006102 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006103 case TargetInfo::SignedShort: return ShortTy;
6104 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6105 case TargetInfo::SignedInt: return IntTy;
6106 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6107 case TargetInfo::SignedLong: return LongTy;
6108 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6109 case TargetInfo::SignedLongLong: return LongLongTy;
6110 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6111 }
6112
David Blaikie83d382b2011-09-23 05:06:16 +00006113 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006114}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006115
6116//===----------------------------------------------------------------------===//
6117// Type Predicates.
6118//===----------------------------------------------------------------------===//
6119
Fariborz Jahanian96207692009-02-18 21:49:28 +00006120/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6121/// garbage collection attribute.
6122///
John McCall553d45a2011-01-12 00:34:59 +00006123Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006124 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006125 return Qualifiers::GCNone;
6126
David Blaikiebbafb8a2012-03-11 07:00:24 +00006127 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006128 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6129
6130 // Default behaviour under objective-C's gc is for ObjC pointers
6131 // (or pointers to them) be treated as though they were declared
6132 // as __strong.
6133 if (GCAttrs == Qualifiers::GCNone) {
6134 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6135 return Qualifiers::Strong;
6136 else if (Ty->isPointerType())
6137 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6138 } else {
6139 // It's not valid to set GC attributes on anything that isn't a
6140 // pointer.
6141#ifndef NDEBUG
6142 QualType CT = Ty->getCanonicalTypeInternal();
6143 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6144 CT = AT->getElementType();
6145 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6146#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006147 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006148 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006149}
6150
Chris Lattner49af6a42008-04-07 06:51:04 +00006151//===----------------------------------------------------------------------===//
6152// Type Compatibility Testing
6153//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006154
Mike Stump11289f42009-09-09 15:08:12 +00006155/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006156/// compatible.
6157static bool areCompatVectorTypes(const VectorType *LHS,
6158 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006159 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006160 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006161 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006162}
6163
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006164bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6165 QualType SecondVec) {
6166 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6167 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6168
6169 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6170 return true;
6171
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006172 // Treat Neon vector types and most AltiVec vector types as if they are the
6173 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006174 const VectorType *First = FirstVec->getAs<VectorType>();
6175 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006176 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006177 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006178 First->getVectorKind() != VectorType::AltiVecPixel &&
6179 First->getVectorKind() != VectorType::AltiVecBool &&
6180 Second->getVectorKind() != VectorType::AltiVecPixel &&
6181 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006182 return true;
6183
6184 return false;
6185}
6186
Steve Naroff8e6aee52009-07-23 01:01:38 +00006187//===----------------------------------------------------------------------===//
6188// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6189//===----------------------------------------------------------------------===//
6190
6191/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6192/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006193bool
6194ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6195 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006196 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006197 return true;
6198 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6199 E = rProto->protocol_end(); PI != E; ++PI)
6200 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6201 return true;
6202 return false;
6203}
6204
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006205/// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
Steve Naroff8e6aee52009-07-23 01:01:38 +00006206/// return true if lhs's protocols conform to rhs's protocol; false
6207/// otherwise.
6208bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
6209 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
6210 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
6211 return false;
6212}
6213
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006214/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6215/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006216bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6217 QualType rhs) {
6218 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6219 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6220 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6221
6222 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6223 E = lhsQID->qual_end(); I != E; ++I) {
6224 bool match = false;
6225 ObjCProtocolDecl *lhsProto = *I;
6226 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6227 E = rhsOPT->qual_end(); J != E; ++J) {
6228 ObjCProtocolDecl *rhsProto = *J;
6229 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6230 match = true;
6231 break;
6232 }
6233 }
6234 if (!match)
6235 return false;
6236 }
6237 return true;
6238}
6239
Steve Naroff8e6aee52009-07-23 01:01:38 +00006240/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6241/// ObjCQualifiedIDType.
6242bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6243 bool compare) {
6244 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006245 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006246 lhs->isObjCIdType() || lhs->isObjCClassType())
6247 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006248 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006249 rhs->isObjCIdType() || rhs->isObjCClassType())
6250 return true;
6251
6252 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006253 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006254
Steve Naroff8e6aee52009-07-23 01:01:38 +00006255 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006256
Steve Naroff8e6aee52009-07-23 01:01:38 +00006257 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006258 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006259 // make sure we check the class hierarchy.
6260 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6261 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6262 E = lhsQID->qual_end(); I != E; ++I) {
6263 // when comparing an id<P> on lhs with a static type on rhs,
6264 // see if static class implements all of id's protocols, directly or
6265 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006266 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006267 return false;
6268 }
6269 }
6270 // If there are no qualifiers and no interface, we have an 'id'.
6271 return true;
6272 }
Mike Stump11289f42009-09-09 15:08:12 +00006273 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006274 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6275 E = lhsQID->qual_end(); I != E; ++I) {
6276 ObjCProtocolDecl *lhsProto = *I;
6277 bool match = false;
6278
6279 // when comparing an id<P> on lhs with a static type on rhs,
6280 // see if static class implements all of id's protocols, directly or
6281 // through its super class and categories.
6282 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6283 E = rhsOPT->qual_end(); J != E; ++J) {
6284 ObjCProtocolDecl *rhsProto = *J;
6285 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6286 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6287 match = true;
6288 break;
6289 }
6290 }
Mike Stump11289f42009-09-09 15:08:12 +00006291 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006292 // make sure we check the class hierarchy.
6293 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6294 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6295 E = lhsQID->qual_end(); I != E; ++I) {
6296 // when comparing an id<P> on lhs with a static type on rhs,
6297 // see if static class implements all of id's protocols, directly or
6298 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006299 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006300 match = true;
6301 break;
6302 }
6303 }
6304 }
6305 if (!match)
6306 return false;
6307 }
Mike Stump11289f42009-09-09 15:08:12 +00006308
Steve Naroff8e6aee52009-07-23 01:01:38 +00006309 return true;
6310 }
Mike Stump11289f42009-09-09 15:08:12 +00006311
Steve Naroff8e6aee52009-07-23 01:01:38 +00006312 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6313 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6314
Mike Stump11289f42009-09-09 15:08:12 +00006315 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006316 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006317 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006318 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6319 E = lhsOPT->qual_end(); I != E; ++I) {
6320 ObjCProtocolDecl *lhsProto = *I;
6321 bool match = false;
6322
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006323 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006324 // see if static class implements all of id's protocols, directly or
6325 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006326 // First, lhs protocols in the qualifier list must be found, direct
6327 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006328 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6329 E = rhsQID->qual_end(); J != E; ++J) {
6330 ObjCProtocolDecl *rhsProto = *J;
6331 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6332 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6333 match = true;
6334 break;
6335 }
6336 }
6337 if (!match)
6338 return false;
6339 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006340
6341 // Static class's protocols, or its super class or category protocols
6342 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6343 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6344 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6345 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6346 // This is rather dubious but matches gcc's behavior. If lhs has
6347 // no type qualifier and its class has no static protocol(s)
6348 // assume that it is mismatch.
6349 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6350 return false;
6351 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6352 LHSInheritedProtocols.begin(),
6353 E = LHSInheritedProtocols.end(); I != E; ++I) {
6354 bool match = false;
6355 ObjCProtocolDecl *lhsProto = (*I);
6356 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6357 E = rhsQID->qual_end(); J != E; ++J) {
6358 ObjCProtocolDecl *rhsProto = *J;
6359 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6360 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6361 match = true;
6362 break;
6363 }
6364 }
6365 if (!match)
6366 return false;
6367 }
6368 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006369 return true;
6370 }
6371 return false;
6372}
6373
Eli Friedman47f77112008-08-22 00:56:42 +00006374/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006375/// compatible for assignment from RHS to LHS. This handles validation of any
6376/// protocol qualifiers on the LHS or RHS.
6377///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006378bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6379 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006380 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6381 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6382
Steve Naroff1329fa02009-07-15 18:40:39 +00006383 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006384 if (LHS->isObjCUnqualifiedIdOrClass() ||
6385 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006386 return true;
6387
John McCall8b07ec22010-05-15 11:32:37 +00006388 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006389 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6390 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006391 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006392
6393 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6394 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6395 QualType(RHSOPT,0));
6396
John McCall8b07ec22010-05-15 11:32:37 +00006397 // If we have 2 user-defined types, fall into that path.
6398 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006399 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006400
Steve Naroff8e6aee52009-07-23 01:01:38 +00006401 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006402}
6403
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006404/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006405/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006406/// arguments in block literals. When passed as arguments, passing 'A*' where
6407/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6408/// not OK. For the return type, the opposite is not OK.
6409bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6410 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006411 const ObjCObjectPointerType *RHSOPT,
6412 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006413 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006414 return true;
6415
6416 if (LHSOPT->isObjCBuiltinType()) {
6417 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6418 }
6419
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006420 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006421 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6422 QualType(RHSOPT,0),
6423 false);
6424
6425 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6426 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6427 if (LHS && RHS) { // We have 2 user-defined types.
6428 if (LHS != RHS) {
6429 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006430 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006431 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006432 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006433 }
6434 else
6435 return true;
6436 }
6437 return false;
6438}
6439
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006440/// getIntersectionOfProtocols - This routine finds the intersection of set
6441/// of protocols inherited from two distinct objective-c pointer objects.
6442/// It is used to build composite qualifier list of the composite type of
6443/// the conditional expression involving two objective-c pointer objects.
6444static
6445void getIntersectionOfProtocols(ASTContext &Context,
6446 const ObjCObjectPointerType *LHSOPT,
6447 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006448 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006449
John McCall8b07ec22010-05-15 11:32:37 +00006450 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6451 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6452 assert(LHS->getInterface() && "LHS must have an interface base");
6453 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006454
6455 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6456 unsigned LHSNumProtocols = LHS->getNumProtocols();
6457 if (LHSNumProtocols > 0)
6458 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6459 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006460 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006461 Context.CollectInheritedProtocols(LHS->getInterface(),
6462 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006463 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6464 LHSInheritedProtocols.end());
6465 }
6466
6467 unsigned RHSNumProtocols = RHS->getNumProtocols();
6468 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006469 ObjCProtocolDecl **RHSProtocols =
6470 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006471 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6472 if (InheritedProtocolSet.count(RHSProtocols[i]))
6473 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006474 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006475 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006476 Context.CollectInheritedProtocols(RHS->getInterface(),
6477 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006478 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6479 RHSInheritedProtocols.begin(),
6480 E = RHSInheritedProtocols.end(); I != E; ++I)
6481 if (InheritedProtocolSet.count((*I)))
6482 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006483 }
6484}
6485
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006486/// areCommonBaseCompatible - Returns common base class of the two classes if
6487/// one found. Note that this is O'2 algorithm. But it will be called as the
6488/// last type comparison in a ?-exp of ObjC pointer types before a
6489/// warning is issued. So, its invokation is extremely rare.
6490QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006491 const ObjCObjectPointerType *Lptr,
6492 const ObjCObjectPointerType *Rptr) {
6493 const ObjCObjectType *LHS = Lptr->getObjectType();
6494 const ObjCObjectType *RHS = Rptr->getObjectType();
6495 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6496 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006497 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006498 return QualType();
6499
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006500 do {
John McCall8b07ec22010-05-15 11:32:37 +00006501 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006502 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006503 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006504 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6505
6506 QualType Result = QualType(LHS, 0);
6507 if (!Protocols.empty())
6508 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6509 Result = getObjCObjectPointerType(Result);
6510 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006511 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006512 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006513
6514 return QualType();
6515}
6516
John McCall8b07ec22010-05-15 11:32:37 +00006517bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6518 const ObjCObjectType *RHS) {
6519 assert(LHS->getInterface() && "LHS is not an interface type");
6520 assert(RHS->getInterface() && "RHS is not an interface type");
6521
Chris Lattner49af6a42008-04-07 06:51:04 +00006522 // Verify that the base decls are compatible: the RHS must be a subclass of
6523 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006524 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006525 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006526
Chris Lattner49af6a42008-04-07 06:51:04 +00006527 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6528 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006529 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006530 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006531
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006532 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6533 // more detailed analysis is required.
6534 if (RHS->getNumProtocols() == 0) {
6535 // OK, if LHS is a superclass of RHS *and*
6536 // this superclass is assignment compatible with LHS.
6537 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006538 bool IsSuperClass =
6539 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6540 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006541 // OK if conversion of LHS to SuperClass results in narrowing of types
6542 // ; i.e., SuperClass may implement at least one of the protocols
6543 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6544 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6545 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006546 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006547 // If super class has no protocols, it is not a match.
6548 if (SuperClassInheritedProtocols.empty())
6549 return false;
6550
6551 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6552 LHSPE = LHS->qual_end();
6553 LHSPI != LHSPE; LHSPI++) {
6554 bool SuperImplementsProtocol = false;
6555 ObjCProtocolDecl *LHSProto = (*LHSPI);
6556
6557 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6558 SuperClassInheritedProtocols.begin(),
6559 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6560 ObjCProtocolDecl *SuperClassProto = (*I);
6561 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6562 SuperImplementsProtocol = true;
6563 break;
6564 }
6565 }
6566 if (!SuperImplementsProtocol)
6567 return false;
6568 }
6569 return true;
6570 }
6571 return false;
6572 }
Mike Stump11289f42009-09-09 15:08:12 +00006573
John McCall8b07ec22010-05-15 11:32:37 +00006574 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6575 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006576 LHSPI != LHSPE; LHSPI++) {
6577 bool RHSImplementsProtocol = false;
6578
6579 // If the RHS doesn't implement the protocol on the left, the types
6580 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006581 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6582 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006583 RHSPI != RHSPE; RHSPI++) {
6584 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006585 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006586 break;
6587 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006588 }
6589 // FIXME: For better diagnostics, consider passing back the protocol name.
6590 if (!RHSImplementsProtocol)
6591 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006592 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006593 // The RHS implements all protocols listed on the LHS.
6594 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006595}
6596
Steve Naroffb7605152009-02-12 17:52:19 +00006597bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6598 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006599 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6600 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006601
Steve Naroff7cae42b2009-07-10 23:34:53 +00006602 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006603 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006604
6605 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6606 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006607}
6608
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006609bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6610 return canAssignObjCInterfaces(
6611 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6612 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6613}
6614
Mike Stump11289f42009-09-09 15:08:12 +00006615/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006616/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006617/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006618/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006619bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6620 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006621 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006622 return hasSameType(LHS, RHS);
6623
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006624 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006625}
6626
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006627bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006628 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006629}
6630
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006631bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6632 return !mergeTypes(LHS, RHS, true).isNull();
6633}
6634
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006635/// mergeTransparentUnionType - if T is a transparent union type and a member
6636/// of T is compatible with SubType, return the merged type, else return
6637/// QualType()
6638QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6639 bool OfBlockPointer,
6640 bool Unqualified) {
6641 if (const RecordType *UT = T->getAsUnionType()) {
6642 RecordDecl *UD = UT->getDecl();
6643 if (UD->hasAttr<TransparentUnionAttr>()) {
6644 for (RecordDecl::field_iterator it = UD->field_begin(),
6645 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006646 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006647 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6648 if (!MT.isNull())
6649 return MT;
6650 }
6651 }
6652 }
6653
6654 return QualType();
6655}
6656
6657/// mergeFunctionArgumentTypes - merge two types which appear as function
6658/// argument types
6659QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6660 bool OfBlockPointer,
6661 bool Unqualified) {
6662 // GNU extension: two types are compatible if they appear as a function
6663 // argument, one of the types is a transparent union type and the other
6664 // type is compatible with a union member
6665 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6666 Unqualified);
6667 if (!lmerge.isNull())
6668 return lmerge;
6669
6670 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6671 Unqualified);
6672 if (!rmerge.isNull())
6673 return rmerge;
6674
6675 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6676}
6677
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006678QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006679 bool OfBlockPointer,
6680 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006681 const FunctionType *lbase = lhs->getAs<FunctionType>();
6682 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006683 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6684 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006685 bool allLTypes = true;
6686 bool allRTypes = true;
6687
6688 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006689 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006690 if (OfBlockPointer) {
6691 QualType RHS = rbase->getResultType();
6692 QualType LHS = lbase->getResultType();
6693 bool UnqualifiedResult = Unqualified;
6694 if (!UnqualifiedResult)
6695 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006696 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006697 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006698 else
John McCall8c6b56f2010-12-15 01:06:38 +00006699 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6700 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006701 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006702
6703 if (Unqualified)
6704 retType = retType.getUnqualifiedType();
6705
6706 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6707 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6708 if (Unqualified) {
6709 LRetType = LRetType.getUnqualifiedType();
6710 RRetType = RRetType.getUnqualifiedType();
6711 }
6712
6713 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006714 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006715 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006716 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006717
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006718 // FIXME: double check this
6719 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6720 // rbase->getRegParmAttr() != 0 &&
6721 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006722 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6723 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006724
Douglas Gregor8c940862010-01-18 17:14:39 +00006725 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00006726 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00006727 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006728
John McCall8c6b56f2010-12-15 01:06:38 +00006729 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006730 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6731 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006732 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6733 return QualType();
6734
John McCall31168b02011-06-15 23:02:42 +00006735 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6736 return QualType();
6737
John McCall8c6b56f2010-12-15 01:06:38 +00006738 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6739 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006740
Rafael Espindola8778c282012-11-29 16:09:03 +00006741 if (lbaseInfo.getNoReturn() != NoReturn)
6742 allLTypes = false;
6743 if (rbaseInfo.getNoReturn() != NoReturn)
6744 allRTypes = false;
6745
John McCall31168b02011-06-15 23:02:42 +00006746 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006747
Eli Friedman47f77112008-08-22 00:56:42 +00006748 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006749 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6750 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006751 unsigned lproto_nargs = lproto->getNumArgs();
6752 unsigned rproto_nargs = rproto->getNumArgs();
6753
6754 // Compatible functions must have the same number of arguments
6755 if (lproto_nargs != rproto_nargs)
6756 return QualType();
6757
6758 // Variadic and non-variadic functions aren't compatible
6759 if (lproto->isVariadic() != rproto->isVariadic())
6760 return QualType();
6761
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006762 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6763 return QualType();
6764
Fariborz Jahanian97676972011-09-28 21:52:05 +00006765 if (LangOpts.ObjCAutoRefCount &&
6766 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6767 return QualType();
6768
Eli Friedman47f77112008-08-22 00:56:42 +00006769 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006770 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00006771 for (unsigned i = 0; i < lproto_nargs; i++) {
6772 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6773 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006774 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6775 OfBlockPointer,
6776 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006777 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006778
6779 if (Unqualified)
6780 argtype = argtype.getUnqualifiedType();
6781
Eli Friedman47f77112008-08-22 00:56:42 +00006782 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006783 if (Unqualified) {
6784 largtype = largtype.getUnqualifiedType();
6785 rargtype = rargtype.getUnqualifiedType();
6786 }
6787
Chris Lattner465fa322008-10-05 17:34:18 +00006788 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6789 allLTypes = false;
6790 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6791 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006792 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006793
Eli Friedman47f77112008-08-22 00:56:42 +00006794 if (allLTypes) return lhs;
6795 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006796
6797 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6798 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00006799 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006800 }
6801
6802 if (lproto) allRTypes = false;
6803 if (rproto) allLTypes = false;
6804
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006805 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006806 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006807 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006808 if (proto->isVariadic()) return QualType();
6809 // Check that the types are compatible with the types that
6810 // would result from default argument promotions (C99 6.7.5.3p15).
6811 // The only types actually affected are promotable integer
6812 // types and floats, which would be passed as a different
6813 // type depending on whether the prototype is visible.
6814 unsigned proto_nargs = proto->getNumArgs();
6815 for (unsigned i = 0; i < proto_nargs; ++i) {
6816 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00006817
Eli Friedman448ce402012-08-30 00:44:15 +00006818 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00006819 // to pass enum values.
Eli Friedman448ce402012-08-30 00:44:15 +00006820 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
6821 argTy = Enum->getDecl()->getIntegerType();
6822 if (argTy.isNull())
6823 return QualType();
6824 }
Douglas Gregor2973d402010-02-03 19:27:29 +00006825
Eli Friedman47f77112008-08-22 00:56:42 +00006826 if (argTy->isPromotableIntegerType() ||
6827 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6828 return QualType();
6829 }
6830
6831 if (allLTypes) return lhs;
6832 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006833
6834 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6835 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00006836 return getFunctionType(retType,
6837 ArrayRef<QualType>(proto->arg_type_begin(),
6838 proto->getNumArgs()),
6839 EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006840 }
6841
6842 if (allLTypes) return lhs;
6843 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00006844 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00006845}
6846
John McCall433c2e62013-03-21 00:10:07 +00006847/// Given that we have an enum type and a non-enum type, try to merge them.
6848static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
6849 QualType other, bool isBlockReturnType) {
6850 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
6851 // a signed integer type, or an unsigned integer type.
6852 // Compatibility is based on the underlying type, not the promotion
6853 // type.
6854 QualType underlyingType = ET->getDecl()->getIntegerType();
6855 if (underlyingType.isNull()) return QualType();
6856 if (Context.hasSameType(underlyingType, other))
6857 return other;
6858
6859 // In block return types, we're more permissive and accept any
6860 // integral type of the same size.
6861 if (isBlockReturnType && other->isIntegerType() &&
6862 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
6863 return other;
6864
6865 return QualType();
6866}
6867
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006868QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006869 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006870 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00006871 // C++ [expr]: If an expression initially has the type "reference to T", the
6872 // type is adjusted to "T" prior to any further analysis, the expression
6873 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006874 // expression is an lvalue unless the reference is an rvalue reference and
6875 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00006876 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6877 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006878
6879 if (Unqualified) {
6880 LHS = LHS.getUnqualifiedType();
6881 RHS = RHS.getUnqualifiedType();
6882 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00006883
Eli Friedman47f77112008-08-22 00:56:42 +00006884 QualType LHSCan = getCanonicalType(LHS),
6885 RHSCan = getCanonicalType(RHS);
6886
6887 // If two types are identical, they are compatible.
6888 if (LHSCan == RHSCan)
6889 return LHS;
6890
John McCall8ccfcb52009-09-24 19:53:00 +00006891 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006892 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6893 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00006894 if (LQuals != RQuals) {
6895 // If any of these qualifiers are different, we have a type
6896 // mismatch.
6897 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00006898 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6899 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00006900 return QualType();
6901
6902 // Exactly one GC qualifier difference is allowed: __strong is
6903 // okay if the other type has no GC qualifier but is an Objective
6904 // C object pointer (i.e. implicitly strong by default). We fix
6905 // this by pretending that the unqualified type was actually
6906 // qualified __strong.
6907 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6908 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6909 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6910
6911 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6912 return QualType();
6913
6914 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6915 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6916 }
6917 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6918 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6919 }
Eli Friedman47f77112008-08-22 00:56:42 +00006920 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00006921 }
6922
6923 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00006924
Eli Friedmandcca6332009-06-01 01:22:52 +00006925 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6926 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00006927
Chris Lattnerfd652912008-01-14 05:45:46 +00006928 // We want to consider the two function types to be the same for these
6929 // comparisons, just force one to the other.
6930 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6931 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00006932
6933 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00006934 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6935 LHSClass = Type::ConstantArray;
6936 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6937 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00006938
John McCall8b07ec22010-05-15 11:32:37 +00006939 // ObjCInterfaces are just specialized ObjCObjects.
6940 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6941 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6942
Nate Begemance4d7fc2008-04-18 23:10:10 +00006943 // Canonicalize ExtVector -> Vector.
6944 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6945 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00006946
Chris Lattner95554662008-04-07 05:43:21 +00006947 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006948 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00006949 // Note that we only have special rules for turning block enum
6950 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00006951 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00006952 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006953 }
John McCall9dd450b2009-09-21 23:43:11 +00006954 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00006955 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006956 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006957 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00006958 if (OfBlockPointer && !BlockReturnType) {
6959 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6960 return LHS;
6961 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6962 return RHS;
6963 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006964
Eli Friedman47f77112008-08-22 00:56:42 +00006965 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00006966 }
Eli Friedman47f77112008-08-22 00:56:42 +00006967
Steve Naroffc6edcbd2008-01-09 22:43:08 +00006968 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006969 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006970#define TYPE(Class, Base)
6971#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00006972#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006973#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6974#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6975#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00006976 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006977
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006978 case Type::LValueReference:
6979 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006980 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00006981 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006982
John McCall8b07ec22010-05-15 11:32:37 +00006983 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006984 case Type::IncompleteArray:
6985 case Type::VariableArray:
6986 case Type::FunctionProto:
6987 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00006988 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006989
Chris Lattnerfd652912008-01-14 05:45:46 +00006990 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00006991 {
6992 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006993 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6994 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006995 if (Unqualified) {
6996 LHSPointee = LHSPointee.getUnqualifiedType();
6997 RHSPointee = RHSPointee.getUnqualifiedType();
6998 }
6999 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7000 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007001 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007002 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007003 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007004 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007005 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007006 return getPointerType(ResultType);
7007 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007008 case Type::BlockPointer:
7009 {
7010 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007011 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7012 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007013 if (Unqualified) {
7014 LHSPointee = LHSPointee.getUnqualifiedType();
7015 RHSPointee = RHSPointee.getUnqualifiedType();
7016 }
7017 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7018 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007019 if (ResultType.isNull()) return QualType();
7020 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7021 return LHS;
7022 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7023 return RHS;
7024 return getBlockPointerType(ResultType);
7025 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007026 case Type::Atomic:
7027 {
7028 // Merge two pointer types, while trying to preserve typedef info
7029 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7030 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7031 if (Unqualified) {
7032 LHSValue = LHSValue.getUnqualifiedType();
7033 RHSValue = RHSValue.getUnqualifiedType();
7034 }
7035 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7036 Unqualified);
7037 if (ResultType.isNull()) return QualType();
7038 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7039 return LHS;
7040 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7041 return RHS;
7042 return getAtomicType(ResultType);
7043 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007044 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007045 {
7046 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7047 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7048 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7049 return QualType();
7050
7051 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7052 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007053 if (Unqualified) {
7054 LHSElem = LHSElem.getUnqualifiedType();
7055 RHSElem = RHSElem.getUnqualifiedType();
7056 }
7057
7058 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007059 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007060 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7061 return LHS;
7062 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7063 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007064 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7065 ArrayType::ArraySizeModifier(), 0);
7066 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7067 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007068 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7069 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007070 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7071 return LHS;
7072 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7073 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007074 if (LVAT) {
7075 // FIXME: This isn't correct! But tricky to implement because
7076 // the array's size has to be the size of LHS, but the type
7077 // has to be different.
7078 return LHS;
7079 }
7080 if (RVAT) {
7081 // FIXME: This isn't correct! But tricky to implement because
7082 // the array's size has to be the size of RHS, but the type
7083 // has to be different.
7084 return RHS;
7085 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007086 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7087 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007088 return getIncompleteArrayType(ResultType,
7089 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007090 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007091 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007092 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007093 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007094 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007095 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007096 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007097 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007098 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007099 case Type::Complex:
7100 // Distinct complex types are incompatible.
7101 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007102 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007103 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007104 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7105 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007106 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007107 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007108 case Type::ObjCObject: {
7109 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007110 // FIXME: This should be type compatibility, e.g. whether
7111 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007112 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7113 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7114 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007115 return LHS;
7116
Eli Friedman47f77112008-08-22 00:56:42 +00007117 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007118 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007119 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007120 if (OfBlockPointer) {
7121 if (canAssignObjCInterfacesInBlockPointer(
7122 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007123 RHS->getAs<ObjCObjectPointerType>(),
7124 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007125 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007126 return QualType();
7127 }
John McCall9dd450b2009-09-21 23:43:11 +00007128 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7129 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007130 return LHS;
7131
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007132 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007133 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007134 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007135
David Blaikie8a40f702012-01-17 06:56:22 +00007136 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007137}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007138
Fariborz Jahanian97676972011-09-28 21:52:05 +00007139bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7140 const FunctionProtoType *FromFunctionType,
7141 const FunctionProtoType *ToFunctionType) {
7142 if (FromFunctionType->hasAnyConsumedArgs() !=
7143 ToFunctionType->hasAnyConsumedArgs())
7144 return false;
7145 FunctionProtoType::ExtProtoInfo FromEPI =
7146 FromFunctionType->getExtProtoInfo();
7147 FunctionProtoType::ExtProtoInfo ToEPI =
7148 ToFunctionType->getExtProtoInfo();
7149 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
7150 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
7151 ArgIdx != NumArgs; ++ArgIdx) {
7152 if (FromEPI.ConsumedArguments[ArgIdx] !=
7153 ToEPI.ConsumedArguments[ArgIdx])
7154 return false;
7155 }
7156 return true;
7157}
7158
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007159/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7160/// 'RHS' attributes and returns the merged version; including for function
7161/// return types.
7162QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7163 QualType LHSCan = getCanonicalType(LHS),
7164 RHSCan = getCanonicalType(RHS);
7165 // If two types are identical, they are compatible.
7166 if (LHSCan == RHSCan)
7167 return LHS;
7168 if (RHSCan->isFunctionType()) {
7169 if (!LHSCan->isFunctionType())
7170 return QualType();
7171 QualType OldReturnType =
7172 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7173 QualType NewReturnType =
7174 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7175 QualType ResReturnType =
7176 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7177 if (ResReturnType.isNull())
7178 return QualType();
7179 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7180 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7181 // In either case, use OldReturnType to build the new function type.
7182 const FunctionType *F = LHS->getAs<FunctionType>();
7183 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007184 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7185 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007186 QualType ResultType
Jordan Rose5c382722013-03-08 21:51:21 +00007187 = getFunctionType(OldReturnType,
7188 ArrayRef<QualType>(FPT->arg_type_begin(),
7189 FPT->getNumArgs()),
7190 EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007191 return ResultType;
7192 }
7193 }
7194 return QualType();
7195 }
7196
7197 // If the qualifiers are different, the types can still be merged.
7198 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7199 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7200 if (LQuals != RQuals) {
7201 // If any of these qualifiers are different, we have a type mismatch.
7202 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7203 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7204 return QualType();
7205
7206 // Exactly one GC qualifier difference is allowed: __strong is
7207 // okay if the other type has no GC qualifier but is an Objective
7208 // C object pointer (i.e. implicitly strong by default). We fix
7209 // this by pretending that the unqualified type was actually
7210 // qualified __strong.
7211 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7212 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7213 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7214
7215 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7216 return QualType();
7217
7218 if (GC_L == Qualifiers::Strong)
7219 return LHS;
7220 if (GC_R == Qualifiers::Strong)
7221 return RHS;
7222 return QualType();
7223 }
7224
7225 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7226 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7227 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7228 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7229 if (ResQT == LHSBaseQT)
7230 return LHS;
7231 if (ResQT == RHSBaseQT)
7232 return RHS;
7233 }
7234 return QualType();
7235}
7236
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007237//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007238// Integer Predicates
7239//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007240
Jay Foad39c79802011-01-12 09:06:06 +00007241unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00007242 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00007243 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007244 if (T->isBooleanType())
7245 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007246 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007247 return (unsigned)getTypeSize(T);
7248}
7249
Abramo Bagnara13640492012-09-09 10:21:24 +00007250QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007251 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007252
7253 // Turn <4 x signed int> -> <4 x unsigned int>
7254 if (const VectorType *VTy = T->getAs<VectorType>())
7255 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007256 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007257
7258 // For enums, we return the unsigned version of the base type.
7259 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007260 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007261
7262 const BuiltinType *BTy = T->getAs<BuiltinType>();
7263 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007264 switch (BTy->getKind()) {
7265 case BuiltinType::Char_S:
7266 case BuiltinType::SChar:
7267 return UnsignedCharTy;
7268 case BuiltinType::Short:
7269 return UnsignedShortTy;
7270 case BuiltinType::Int:
7271 return UnsignedIntTy;
7272 case BuiltinType::Long:
7273 return UnsignedLongTy;
7274 case BuiltinType::LongLong:
7275 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007276 case BuiltinType::Int128:
7277 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007278 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007279 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007280 }
7281}
7282
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007283ASTMutationListener::~ASTMutationListener() { }
7284
Chris Lattnerecd79c62009-06-14 00:45:47 +00007285
7286//===----------------------------------------------------------------------===//
7287// Builtin Type Computation
7288//===----------------------------------------------------------------------===//
7289
7290/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007291/// pointer over the consumed characters. This returns the resultant type. If
7292/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7293/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7294/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007295///
7296/// RequiresICE is filled in on return to indicate whether the value is required
7297/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007298static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007299 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007300 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007301 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007302 // Modifiers.
7303 int HowLong = 0;
7304 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007305 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007306
Chris Lattnerdc226c22010-10-01 22:42:38 +00007307 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007308 bool Done = false;
7309 while (!Done) {
7310 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007311 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007312 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007313 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007314 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007315 case 'S':
7316 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7317 assert(!Signed && "Can't use 'S' modifier multiple times!");
7318 Signed = true;
7319 break;
7320 case 'U':
7321 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7322 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7323 Unsigned = true;
7324 break;
7325 case 'L':
7326 assert(HowLong <= 2 && "Can't have LLLL modifier");
7327 ++HowLong;
7328 break;
7329 }
7330 }
7331
7332 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007333
Chris Lattnerecd79c62009-06-14 00:45:47 +00007334 // Read the base type.
7335 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007336 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007337 case 'v':
7338 assert(HowLong == 0 && !Signed && !Unsigned &&
7339 "Bad modifiers used with 'v'!");
7340 Type = Context.VoidTy;
7341 break;
7342 case 'f':
7343 assert(HowLong == 0 && !Signed && !Unsigned &&
7344 "Bad modifiers used with 'f'!");
7345 Type = Context.FloatTy;
7346 break;
7347 case 'd':
7348 assert(HowLong < 2 && !Signed && !Unsigned &&
7349 "Bad modifiers used with 'd'!");
7350 if (HowLong)
7351 Type = Context.LongDoubleTy;
7352 else
7353 Type = Context.DoubleTy;
7354 break;
7355 case 's':
7356 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7357 if (Unsigned)
7358 Type = Context.UnsignedShortTy;
7359 else
7360 Type = Context.ShortTy;
7361 break;
7362 case 'i':
7363 if (HowLong == 3)
7364 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7365 else if (HowLong == 2)
7366 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7367 else if (HowLong == 1)
7368 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7369 else
7370 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7371 break;
7372 case 'c':
7373 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7374 if (Signed)
7375 Type = Context.SignedCharTy;
7376 else if (Unsigned)
7377 Type = Context.UnsignedCharTy;
7378 else
7379 Type = Context.CharTy;
7380 break;
7381 case 'b': // boolean
7382 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7383 Type = Context.BoolTy;
7384 break;
7385 case 'z': // size_t.
7386 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7387 Type = Context.getSizeType();
7388 break;
7389 case 'F':
7390 Type = Context.getCFConstantStringType();
7391 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007392 case 'G':
7393 Type = Context.getObjCIdType();
7394 break;
7395 case 'H':
7396 Type = Context.getObjCSelType();
7397 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007398 case 'M':
7399 Type = Context.getObjCSuperType();
7400 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007401 case 'a':
7402 Type = Context.getBuiltinVaListType();
7403 assert(!Type.isNull() && "builtin va list type not initialized!");
7404 break;
7405 case 'A':
7406 // This is a "reference" to a va_list; however, what exactly
7407 // this means depends on how va_list is defined. There are two
7408 // different kinds of va_list: ones passed by value, and ones
7409 // passed by reference. An example of a by-value va_list is
7410 // x86, where va_list is a char*. An example of by-ref va_list
7411 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7412 // we want this argument to be a char*&; for x86-64, we want
7413 // it to be a __va_list_tag*.
7414 Type = Context.getBuiltinVaListType();
7415 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007416 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007417 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007418 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007419 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007420 break;
7421 case 'V': {
7422 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007423 unsigned NumElements = strtoul(Str, &End, 10);
7424 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007425 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007426
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007427 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7428 RequiresICE, false);
7429 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007430
7431 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007432 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007433 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007434 break;
7435 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007436 case 'E': {
7437 char *End;
7438
7439 unsigned NumElements = strtoul(Str, &End, 10);
7440 assert(End != Str && "Missing vector size");
7441
7442 Str = End;
7443
7444 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7445 false);
7446 Type = Context.getExtVectorType(ElementType, NumElements);
7447 break;
7448 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007449 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007450 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7451 false);
7452 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007453 Type = Context.getComplexType(ElementType);
7454 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007455 }
7456 case 'Y' : {
7457 Type = Context.getPointerDiffType();
7458 break;
7459 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007460 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007461 Type = Context.getFILEType();
7462 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007463 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007464 return QualType();
7465 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007466 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007467 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007468 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007469 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007470 else
7471 Type = Context.getjmp_bufType();
7472
Mike Stump2adb4da2009-07-28 23:47:15 +00007473 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007474 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007475 return QualType();
7476 }
7477 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007478 case 'K':
7479 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7480 Type = Context.getucontext_tType();
7481
7482 if (Type.isNull()) {
7483 Error = ASTContext::GE_Missing_ucontext;
7484 return QualType();
7485 }
7486 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007487 case 'p':
7488 Type = Context.getProcessIDType();
7489 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007490 }
Mike Stump11289f42009-09-09 15:08:12 +00007491
Chris Lattnerdc226c22010-10-01 22:42:38 +00007492 // If there are modifiers and if we're allowed to parse them, go for it.
7493 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007494 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007495 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007496 default: Done = true; --Str; break;
7497 case '*':
7498 case '&': {
7499 // Both pointers and references can have their pointee types
7500 // qualified with an address space.
7501 char *End;
7502 unsigned AddrSpace = strtoul(Str, &End, 10);
7503 if (End != Str && AddrSpace != 0) {
7504 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7505 Str = End;
7506 }
7507 if (c == '*')
7508 Type = Context.getPointerType(Type);
7509 else
7510 Type = Context.getLValueReferenceType(Type);
7511 break;
7512 }
7513 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7514 case 'C':
7515 Type = Type.withConst();
7516 break;
7517 case 'D':
7518 Type = Context.getVolatileType(Type);
7519 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007520 case 'R':
7521 Type = Type.withRestrict();
7522 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007523 }
7524 }
Chris Lattner84733392010-10-01 07:13:18 +00007525
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007526 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007527 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007528
Chris Lattnerecd79c62009-06-14 00:45:47 +00007529 return Type;
7530}
7531
7532/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007533QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007534 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007535 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007536 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007537
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007538 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007539
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007540 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007541 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007542 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7543 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007544 if (Error != GE_None)
7545 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007546
7547 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7548
Chris Lattnerecd79c62009-06-14 00:45:47 +00007549 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007550 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007551 if (Error != GE_None)
7552 return QualType();
7553
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007554 // If this argument is required to be an IntegerConstantExpression and the
7555 // caller cares, fill in the bitmask we return.
7556 if (RequiresICE && IntegerConstantArgs)
7557 *IntegerConstantArgs |= 1 << ArgTypes.size();
7558
Chris Lattnerecd79c62009-06-14 00:45:47 +00007559 // Do array -> pointer decay. The builtin should use the decayed type.
7560 if (Ty->isArrayType())
7561 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007562
Chris Lattnerecd79c62009-06-14 00:45:47 +00007563 ArgTypes.push_back(Ty);
7564 }
7565
7566 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7567 "'.' should only occur at end of builtin type list!");
7568
John McCall991eb4b2010-12-21 00:44:39 +00007569 FunctionType::ExtInfo EI;
7570 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7571
7572 bool Variadic = (TypeStr[0] == '.');
7573
7574 // We really shouldn't be making a no-proto type here, especially in C++.
7575 if (ArgTypes.empty() && Variadic)
7576 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007577
John McCalldb40c7f2010-12-14 08:05:40 +00007578 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007579 EPI.ExtInfo = EI;
7580 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007581
Jordan Rose5c382722013-03-08 21:51:21 +00007582 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007583}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007584
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007585GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
7586 GVALinkage External = GVA_StrongExternal;
7587
7588 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007589 switch (L) {
7590 case NoLinkage:
7591 case InternalLinkage:
7592 case UniqueExternalLinkage:
7593 return GVA_Internal;
7594
7595 case ExternalLinkage:
7596 switch (FD->getTemplateSpecializationKind()) {
7597 case TSK_Undeclared:
7598 case TSK_ExplicitSpecialization:
7599 External = GVA_StrongExternal;
7600 break;
7601
7602 case TSK_ExplicitInstantiationDefinition:
7603 return GVA_ExplicitTemplateInstantiation;
7604
7605 case TSK_ExplicitInstantiationDeclaration:
7606 case TSK_ImplicitInstantiation:
7607 External = GVA_TemplateInstantiation;
7608 break;
7609 }
7610 }
7611
7612 if (!FD->isInlined())
7613 return External;
7614
David Blaikiebbafb8a2012-03-11 07:00:24 +00007615 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007616 // GNU or C99 inline semantics. Determine whether this symbol should be
7617 // externally visible.
7618 if (FD->isInlineDefinitionExternallyVisible())
7619 return External;
7620
7621 // C99 inline semantics, where the symbol is not externally visible.
7622 return GVA_C99Inline;
7623 }
7624
7625 // C++0x [temp.explicit]p9:
7626 // [ Note: The intent is that an inline function that is the subject of
7627 // an explicit instantiation declaration will still be implicitly
7628 // instantiated when used so that the body can be considered for
7629 // inlining, but that no out-of-line copy of the inline function would be
7630 // generated in the translation unit. -- end note ]
7631 if (FD->getTemplateSpecializationKind()
7632 == TSK_ExplicitInstantiationDeclaration)
7633 return GVA_C99Inline;
7634
7635 return GVA_CXXInline;
7636}
7637
7638GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7639 // If this is a static data member, compute the kind of template
7640 // specialization. Otherwise, this variable is not part of a
7641 // template.
7642 TemplateSpecializationKind TSK = TSK_Undeclared;
7643 if (VD->isStaticDataMember())
7644 TSK = VD->getTemplateSpecializationKind();
7645
7646 Linkage L = VD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007647
7648 switch (L) {
7649 case NoLinkage:
7650 case InternalLinkage:
7651 case UniqueExternalLinkage:
7652 return GVA_Internal;
7653
7654 case ExternalLinkage:
7655 switch (TSK) {
7656 case TSK_Undeclared:
7657 case TSK_ExplicitSpecialization:
7658 return GVA_StrongExternal;
7659
7660 case TSK_ExplicitInstantiationDeclaration:
7661 llvm_unreachable("Variable should not be instantiated");
7662 // Fall through to treat this like any other instantiation.
7663
7664 case TSK_ExplicitInstantiationDefinition:
7665 return GVA_ExplicitTemplateInstantiation;
7666
7667 case TSK_ImplicitInstantiation:
7668 return GVA_TemplateInstantiation;
7669 }
7670 }
7671
David Blaikie8a40f702012-01-17 06:56:22 +00007672 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007673}
7674
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007675bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007676 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7677 if (!VD->isFileVarDecl())
7678 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00007679 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007680 return false;
7681
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007682 // Weak references don't produce any output by themselves.
7683 if (D->hasAttr<WeakRefAttr>())
7684 return false;
7685
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007686 // Aliases and used decls are required.
7687 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7688 return true;
7689
7690 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7691 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007692 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007693 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007694
7695 // Constructors and destructors are required.
7696 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7697 return true;
7698
John McCall6bd2a892013-01-25 22:31:03 +00007699 // The key function for a class is required. This rule only comes
7700 // into play when inline functions can be key functions, though.
7701 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7702 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7703 const CXXRecordDecl *RD = MD->getParent();
7704 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7705 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7706 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7707 return true;
7708 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007709 }
7710 }
7711
7712 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7713
7714 // static, static inline, always_inline, and extern inline functions can
7715 // always be deferred. Normal inline functions can be deferred in C99/C++.
7716 // Implicit template instantiations can also be deferred in C++.
7717 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007718 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007719 return false;
7720 return true;
7721 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007722
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007723 const VarDecl *VD = cast<VarDecl>(D);
7724 assert(VD->isFileVarDecl() && "Expected file scoped var");
7725
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007726 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7727 return false;
7728
Richard Smitha0e5e542012-11-12 21:38:00 +00007729 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007730 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smitha0e5e542012-11-12 21:38:00 +00007731 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7732 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007733
Richard Smitha0e5e542012-11-12 21:38:00 +00007734 // Variables that have destruction with side-effects are required.
7735 if (VD->getType().isDestructedType())
7736 return true;
7737
7738 // Variables that have initialization with side-effects are required.
7739 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7740 return true;
7741
7742 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007743}
Charles Davis53c59df2010-08-16 03:33:14 +00007744
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007745CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davis99202b32010-11-09 18:04:24 +00007746 // Pass through to the C++ ABI object
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007747 return ABI->getDefaultMethodCallConv(isVariadic);
7748}
7749
7750CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
John McCall359b8852013-01-25 22:30:49 +00007751 if (CC == CC_C && !LangOpts.MRTD &&
7752 getTargetInfo().getCXXABI().isMemberFunctionCCDefault())
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007753 return CC_Default;
7754 return CC;
Charles Davis99202b32010-11-09 18:04:24 +00007755}
7756
Jay Foad39c79802011-01-12 09:06:06 +00007757bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007758 // Pass through to the C++ ABI object
7759 return ABI->isNearlyEmpty(RD);
7760}
7761
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007762MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00007763 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00007764 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00007765 case TargetCXXABI::GenericItanium:
7766 case TargetCXXABI::GenericARM:
7767 case TargetCXXABI::iOS:
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007768 return createItaniumMangleContext(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00007769 case TargetCXXABI::Microsoft:
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007770 return createMicrosoftMangleContext(*this, getDiagnostics());
7771 }
David Blaikie83d382b2011-09-23 05:06:16 +00007772 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007773}
7774
Charles Davis53c59df2010-08-16 03:33:14 +00007775CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007776
7777size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00007778 return ASTRecordLayouts.getMemorySize()
7779 + llvm::capacity_in_bytes(ObjCLayouts)
7780 + llvm::capacity_in_bytes(KeyFunctions)
7781 + llvm::capacity_in_bytes(ObjCImpls)
7782 + llvm::capacity_in_bytes(BlockVarCopyInits)
7783 + llvm::capacity_in_bytes(DeclAttrs)
7784 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7785 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7786 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7787 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7788 + llvm::capacity_in_bytes(OverriddenMethods)
7789 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007790 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00007791 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007792}
Ted Kremenek540017e2011-10-06 05:00:56 +00007793
David Blaikie095deba2012-11-14 01:52:05 +00007794void ASTContext::addUnnamedTag(const TagDecl *Tag) {
7795 // FIXME: This mangling should be applied to function local classes too
7796 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl() ||
7797 !isa<CXXRecordDecl>(Tag->getParent()) || Tag->getLinkage() != ExternalLinkage)
7798 return;
7799
7800 std::pair<llvm::DenseMap<const DeclContext *, unsigned>::iterator, bool> P =
7801 UnnamedMangleContexts.insert(std::make_pair(Tag->getParent(), 0));
7802 UnnamedMangleNumbers.insert(std::make_pair(Tag, P.first->second++));
7803}
7804
7805int ASTContext::getUnnamedTagManglingNumber(const TagDecl *Tag) const {
7806 llvm::DenseMap<const TagDecl *, unsigned>::const_iterator I =
7807 UnnamedMangleNumbers.find(Tag);
7808 return I != UnnamedMangleNumbers.end() ? I->second : -1;
7809}
7810
Douglas Gregor63798542012-02-20 19:44:39 +00007811unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7812 CXXRecordDecl *Lambda = CallOperator->getParent();
7813 return LambdaMangleContexts[Lambda->getDeclContext()]
7814 .getManglingNumber(CallOperator);
7815}
7816
7817
Ted Kremenek540017e2011-10-06 05:00:56 +00007818void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7819 ParamIndices[D] = index;
7820}
7821
7822unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7823 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7824 assert(I != ParamIndices.end() &&
7825 "ParmIndices lacks entry set by ParmVarDecl");
7826 return I->second;
7827}