blob: 960f261816b12bc91ac885144ba4d5acbc7798ce [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 }
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000100 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
101 // When tag declaration (but not definition!) is part of the
102 // decl-specifier-seq of some other declaration, it doesn't get comment
103 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
104 return NULL;
105 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000106 // TODO: handle comments for function parameters properly.
107 if (isa<ParmVarDecl>(D))
108 return NULL;
109
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000110 // TODO: we could look up template parameter documentation in the template
111 // documentation.
112 if (isa<TemplateTypeParmDecl>(D) ||
113 isa<NonTypeTemplateParmDecl>(D) ||
114 isa<TemplateTemplateParmDecl>(D))
115 return NULL;
116
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000117 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000118
119 // If there are no comments anywhere, we won't find anything.
120 if (RawComments.empty())
121 return NULL;
122
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000123 // Find declaration location.
124 // For Objective-C declarations we generally don't expect to have multiple
125 // declarators, thus use declaration starting location as the "declaration
126 // location".
127 // For all other declarations multiple declarators are used quite frequently,
128 // so we use the location of the identifier as the "declaration location".
129 SourceLocation DeclLoc;
130 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000131 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000132 isa<RedeclarableTemplateDecl>(D) ||
133 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000134 DeclLoc = D->getLocStart();
135 else
136 DeclLoc = D->getLocation();
137
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000138 // If the declaration doesn't map directly to a location in a file, we
139 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000140 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
141 return NULL;
142
143 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000144 ArrayRef<RawComment *>::iterator Comment;
145 {
146 // When searching for comments during parsing, the comment we are looking
147 // for is usually among the last two comments we parsed -- check them
148 // first.
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000149 RawComment CommentAtDeclLoc(
150 SourceMgr, SourceRange(DeclLoc), false,
151 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000152 BeforeThanCompare<RawComment> Compare(SourceMgr);
153 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
154 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
155 if (!Found && RawComments.size() >= 2) {
156 MaybeBeforeDecl--;
157 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
158 }
159
160 if (Found) {
161 Comment = MaybeBeforeDecl + 1;
162 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
163 &CommentAtDeclLoc, Compare));
164 } else {
165 // Slow path.
166 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
167 &CommentAtDeclLoc, Compare);
168 }
169 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000170
171 // Decompose the location for the declaration and find the beginning of the
172 // file buffer.
173 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
174
175 // First check whether we have a trailing comment.
176 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000177 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Dmitri Gribenko44cd7e62012-07-06 23:27:33 +0000178 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000179 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000180 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000181 // Check that Doxygen trailing comment comes after the declaration, starts
182 // on the same line and in the same file as the declaration.
183 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
184 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
185 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
186 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000187 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000188 }
189 }
190
191 // The comment just after the declaration was not a trailing comment.
192 // Let's look at the previous comment.
193 if (Comment == RawComments.begin())
194 return NULL;
195 --Comment;
196
197 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000198 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000199 return NULL;
200
201 // Decompose the end of the comment.
202 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000203 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000204
205 // If the comment and the declaration aren't in the same file, then they
206 // aren't related.
207 if (DeclLocDecomp.first != CommentEndDecomp.first)
208 return NULL;
209
210 // Get the corresponding buffer.
211 bool Invalid = false;
212 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
213 &Invalid).data();
214 if (Invalid)
215 return NULL;
216
217 // Extract text between the comment and declaration.
218 StringRef Text(Buffer + CommentEndDecomp.second,
219 DeclLocDecomp.second - CommentEndDecomp.second);
220
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000221 // There should be no other declarations or preprocessor directives between
222 // comment and declaration.
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000223 if (Text.find_first_of(",;{}#@") != StringRef::npos)
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000224 return NULL;
225
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000226 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000227}
228
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000229namespace {
230/// If we have a 'templated' declaration for a template, adjust 'D' to
231/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000232/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000233const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000234 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000235 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000236 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000237 return FTD;
238
239 // Nothing to do if function is not an implicit instantiation.
240 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
241 return D;
242
243 // Function is an implicit instantiation of a function template?
244 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
245 return FTD;
246
247 // Function is instantiated from a member definition of a class template?
248 if (const FunctionDecl *MemberDecl =
249 FD->getInstantiatedFromMemberFunction())
250 return MemberDecl;
251
252 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000253 }
Dmitri Gribenko90631802012-08-22 17:44:32 +0000254 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
255 // Static data member is instantiated from a member definition of a class
256 // template?
257 if (VD->isStaticDataMember())
258 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
259 return MemberDecl;
260
261 return D;
262 }
263 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
264 // Is this class declaration part of a class template?
265 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
266 return CTD;
267
268 // Class is an implicit instantiation of a class template or partial
269 // specialization?
270 if (const ClassTemplateSpecializationDecl *CTSD =
271 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
272 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
273 return D;
274 llvm::PointerUnion<ClassTemplateDecl *,
275 ClassTemplatePartialSpecializationDecl *>
276 PU = CTSD->getSpecializedTemplateOrPartial();
277 return PU.is<ClassTemplateDecl*>() ?
278 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
279 static_cast<const Decl*>(
280 PU.get<ClassTemplatePartialSpecializationDecl *>());
281 }
282
283 // Class is instantiated from a member definition of a class template?
284 if (const MemberSpecializationInfo *Info =
285 CRD->getMemberSpecializationInfo())
286 return Info->getInstantiatedFrom();
287
288 return D;
289 }
290 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
291 // Enum is instantiated from a member definition of a class template?
292 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
293 return MemberDecl;
294
295 return D;
296 }
297 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000298 return D;
299}
300} // unnamed namespace
301
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000302const RawComment *ASTContext::getRawCommentForAnyRedecl(
303 const Decl *D,
304 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000305 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000306
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000307 // Check whether we have cached a comment for this declaration already.
308 {
309 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
310 RedeclComments.find(D);
311 if (Pos != RedeclComments.end()) {
312 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000313 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
314 if (OriginalDecl)
315 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000316 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000317 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000318 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000319 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000320
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000321 // Search for comments attached to declarations in the redeclaration chain.
322 const RawComment *RC = NULL;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000323 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000324 for (Decl::redecl_iterator I = D->redecls_begin(),
325 E = D->redecls_end();
326 I != E; ++I) {
327 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
328 RedeclComments.find(*I);
329 if (Pos != RedeclComments.end()) {
330 const RawCommentAndCacheFlags &Raw = Pos->second;
331 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
332 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000333 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000334 break;
335 }
336 } else {
337 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000338 OriginalDeclForRC = *I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000339 RawCommentAndCacheFlags Raw;
340 if (RC) {
341 Raw.setRaw(RC);
342 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
343 } else
344 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000345 Raw.setOriginalDecl(*I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000346 RedeclComments[*I] = Raw;
347 if (RC)
348 break;
349 }
350 }
351
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000352 // If we found a comment, it should be a documentation comment.
353 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000354
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000355 if (OriginalDecl)
356 *OriginalDecl = OriginalDeclForRC;
357
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000358 // Update cache for every declaration in the redeclaration chain.
359 RawCommentAndCacheFlags Raw;
360 Raw.setRaw(RC);
361 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000362 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000363
364 for (Decl::redecl_iterator I = D->redecls_begin(),
365 E = D->redecls_end();
366 I != E; ++I) {
367 RawCommentAndCacheFlags &R = RedeclComments[*I];
368 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
369 R = Raw;
370 }
371
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000372 return RC;
373}
374
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000375static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
376 SmallVectorImpl<const NamedDecl *> &Redeclared) {
377 const DeclContext *DC = ObjCMethod->getDeclContext();
378 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
379 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
380 if (!ID)
381 return;
382 // Add redeclared method here.
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000383 for (ObjCInterfaceDecl::known_extensions_iterator
384 Ext = ID->known_extensions_begin(),
385 ExtEnd = ID->known_extensions_end();
386 Ext != ExtEnd; ++Ext) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000387 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000388 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000389 ObjCMethod->isInstanceMethod()))
390 Redeclared.push_back(RedeclaredMethod);
391 }
392 }
393}
394
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000395comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
396 const Decl *D) const {
397 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
398 ThisDeclInfo->CommentDecl = D;
399 ThisDeclInfo->IsFilled = false;
400 ThisDeclInfo->fill();
401 ThisDeclInfo->CommentDecl = FC->getDecl();
402 comments::FullComment *CFC =
403 new (*this) comments::FullComment(FC->getBlocks(),
404 ThisDeclInfo);
405 return CFC;
406
407}
408
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000409comments::FullComment *ASTContext::getCommentForDecl(
410 const Decl *D,
411 const Preprocessor *PP) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000412 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000413
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000414 const Decl *Canonical = D->getCanonicalDecl();
415 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
416 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000417
418 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000419 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000420 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000421 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000422 return CFC;
423 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000424 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000425 }
426
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000427 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000428
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000429 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000430 if (!RC) {
431 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000432 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000433 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000434 if (OMD && OMD->isPropertyAccessor())
435 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
436 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
437 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000438 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000439 addRedeclaredMethods(OMD, Overridden);
440 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000441 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
442 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
443 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000444 }
Fariborz Jahanian6384fbb2013-05-02 15:44:16 +0000445 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000446 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000447 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000448 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000449 if (const TagType *TT = QT->getAs<TagType>())
450 if (const Decl *TD = TT->getDecl())
451 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000452 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000453 }
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000454 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
455 while (IC->getSuperClass()) {
456 IC = IC->getSuperClass();
457 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
458 return cloneFullComment(FC, D);
459 }
460 }
461 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
462 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
463 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
464 return cloneFullComment(FC, D);
465 }
466 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
467 if (!(RD = RD->getDefinition()))
468 return NULL;
469 // Check non-virtual bases.
470 for (CXXRecordDecl::base_class_const_iterator I =
471 RD->bases_begin(), E = RD->bases_end(); I != E; ++I) {
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000472 if (I->isVirtual() || (I->getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000473 continue;
474 QualType Ty = I->getType();
475 if (Ty.isNull())
476 continue;
477 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
478 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
479 continue;
480
481 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
482 return cloneFullComment(FC, D);
483 }
484 }
485 // Check virtual bases.
486 for (CXXRecordDecl::base_class_const_iterator I =
487 RD->vbases_begin(), E = RD->vbases_end(); I != E; ++I) {
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000488 if (I->getAccessSpecifier() != AS_public)
489 continue;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000490 QualType Ty = I->getType();
491 if (Ty.isNull())
492 continue;
493 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
494 if (!(VirtualBase= VirtualBase->getDefinition()))
495 continue;
496 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
497 return cloneFullComment(FC, D);
498 }
499 }
500 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000501 return NULL;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000502 }
503
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000504 // If the RawComment was attached to other redeclaration of this Decl, we
505 // should parse the comment in context of that other Decl. This is important
506 // because comments can contain references to parameter names which can be
507 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000508 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000509 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000510
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000511 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000512 ParsedComments[Canonical] = FC;
513 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000514}
515
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000516void
517ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
518 TemplateTemplateParmDecl *Parm) {
519 ID.AddInteger(Parm->getDepth());
520 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000521 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000522
523 TemplateParameterList *Params = Parm->getTemplateParameters();
524 ID.AddInteger(Params->size());
525 for (TemplateParameterList::const_iterator P = Params->begin(),
526 PEnd = Params->end();
527 P != PEnd; ++P) {
528 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
529 ID.AddInteger(0);
530 ID.AddBoolean(TTP->isParameterPack());
531 continue;
532 }
533
534 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
535 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000536 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000537 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000538 if (NTTP->isExpandedParameterPack()) {
539 ID.AddBoolean(true);
540 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000541 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
542 QualType T = NTTP->getExpansionType(I);
543 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
544 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000545 } else
546 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000547 continue;
548 }
549
550 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
551 ID.AddInteger(2);
552 Profile(ID, TTP);
553 }
554}
555
556TemplateTemplateParmDecl *
557ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000558 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000559 // Check if we already have a canonical template template parameter.
560 llvm::FoldingSetNodeID ID;
561 CanonicalTemplateTemplateParm::Profile(ID, TTP);
562 void *InsertPos = 0;
563 CanonicalTemplateTemplateParm *Canonical
564 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
565 if (Canonical)
566 return Canonical->getParam();
567
568 // Build a canonical template parameter list.
569 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000570 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000571 CanonParams.reserve(Params->size());
572 for (TemplateParameterList::const_iterator P = Params->begin(),
573 PEnd = Params->end();
574 P != PEnd; ++P) {
575 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
576 CanonParams.push_back(
577 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000578 SourceLocation(),
579 SourceLocation(),
580 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000581 TTP->getIndex(), 0, false,
582 TTP->isParameterPack()));
583 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000584 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
585 QualType T = getCanonicalType(NTTP->getType());
586 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
587 NonTypeTemplateParmDecl *Param;
588 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000589 SmallVector<QualType, 2> ExpandedTypes;
590 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000591 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
592 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
593 ExpandedTInfos.push_back(
594 getTrivialTypeSourceInfo(ExpandedTypes.back()));
595 }
596
597 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000598 SourceLocation(),
599 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000600 NTTP->getDepth(),
601 NTTP->getPosition(), 0,
602 T,
603 TInfo,
604 ExpandedTypes.data(),
605 ExpandedTypes.size(),
606 ExpandedTInfos.data());
607 } else {
608 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000609 SourceLocation(),
610 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000611 NTTP->getDepth(),
612 NTTP->getPosition(), 0,
613 T,
614 NTTP->isParameterPack(),
615 TInfo);
616 }
617 CanonParams.push_back(Param);
618
619 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000620 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
621 cast<TemplateTemplateParmDecl>(*P)));
622 }
623
624 TemplateTemplateParmDecl *CanonTTP
625 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
626 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000627 TTP->getPosition(),
628 TTP->isParameterPack(),
629 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000630 TemplateParameterList::Create(*this, SourceLocation(),
631 SourceLocation(),
632 CanonParams.data(),
633 CanonParams.size(),
634 SourceLocation()));
635
636 // Get the new insert position for the node we care about.
637 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
638 assert(Canonical == 0 && "Shouldn't be in the map!");
639 (void)Canonical;
640
641 // Create the canonical template template parameter entry.
642 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
643 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
644 return CanonTTP;
645}
646
Charles Davis53c59df2010-08-16 03:33:14 +0000647CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000648 if (!LangOpts.CPlusPlus) return 0;
649
John McCall359b8852013-01-25 22:30:49 +0000650 switch (T.getCXXABI().getKind()) {
651 case TargetCXXABI::GenericARM:
652 case TargetCXXABI::iOS:
John McCall86353412010-08-21 22:46:04 +0000653 return CreateARMCXXABI(*this);
Tim Northover9bb857a2013-01-31 12:13:10 +0000654 case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000655 case TargetCXXABI::GenericItanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000656 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000657 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000658 return CreateMicrosoftCXXABI(*this);
659 }
David Blaikie8a40f702012-01-17 06:56:22 +0000660 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000661}
662
Douglas Gregore8bbc122011-09-02 00:18:52 +0000663static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000664 const LangOptions &LOpts) {
665 if (LOpts.FakeAddressSpaceMap) {
666 // The fake address space map must have a distinct entry for each
667 // language-specific address space.
668 static const unsigned FakeAddrSpaceMap[] = {
669 1, // opencl_global
670 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000671 3, // opencl_constant
672 4, // cuda_device
673 5, // cuda_constant
674 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000675 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000676 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000677 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000678 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000679 }
680}
681
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000682ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000683 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000684 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000685 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000686 unsigned size_reserve,
687 bool DelayInitialization)
688 : FunctionProtoTypes(this_()),
689 TemplateSpecializationTypes(this_()),
690 DependentTemplateSpecializationTypes(this_()),
691 SubstTemplateTemplateParmPacks(this_()),
692 GlobalNestedNameSpecifier(0),
693 Int128Decl(0), UInt128Decl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000694 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000695 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanianf2578572012-08-30 18:49:41 +0000696 BOOLDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000697 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000698 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000699 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
700 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
701 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000702 NullTypeSourceInfo(QualType()),
703 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000704 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000705 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000706 Idents(idents), Selectors(sels),
707 BuiltinInfo(builtins),
708 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000709 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000710 Comments(SM), CommentsLoaded(false),
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000711 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000712 LastSDM(0, 0),
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +0000713 UniqueBlockByRefTypeID(0)
Douglas Gregore8bbc122011-09-02 00:18:52 +0000714{
Mike Stump11289f42009-09-09 15:08:12 +0000715 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000716 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000717
718 if (!DelayInitialization) {
719 assert(t && "No target supplied for ASTContext initialization");
720 InitBuiltinTypes(*t);
721 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000722}
723
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000724ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000725 // Release the DenseMaps associated with DeclContext objects.
726 // FIXME: Is this the ideal solution?
727 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000728
Douglas Gregor5b11d492010-07-25 17:53:33 +0000729 // Call all of the deallocation functions.
730 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
731 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000732
Ted Kremenek076baeb2010-06-08 23:00:58 +0000733 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000734 // because they can contain DenseMaps.
735 for (llvm::DenseMap<const ObjCContainerDecl*,
736 const ASTRecordLayout*>::iterator
737 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
738 // Increment in loop to prevent using deallocated memory.
739 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
740 R->Destroy(*this);
741
Ted Kremenek076baeb2010-06-08 23:00:58 +0000742 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
743 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
744 // Increment in loop to prevent using deallocated memory.
745 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
746 R->Destroy(*this);
747 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000748
749 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
750 AEnd = DeclAttrs.end();
751 A != AEnd; ++A)
752 A->second->~AttrVec();
753}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000754
Douglas Gregor1a809332010-05-23 18:26:36 +0000755void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
756 Deallocations.push_back(std::make_pair(Callback, Data));
757}
758
Mike Stump11289f42009-09-09 15:08:12 +0000759void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000760ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000761 ExternalSource.reset(Source.take());
762}
763
Chris Lattner4eb445d2007-01-26 01:27:23 +0000764void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000765 llvm::errs() << "\n*** AST Context Stats:\n";
766 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000767
Douglas Gregora30d0462009-05-26 14:40:08 +0000768 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000769#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000770#define ABSTRACT_TYPE(Name, Parent)
771#include "clang/AST/TypeNodes.def"
772 0 // Extra
773 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000774
Chris Lattner4eb445d2007-01-26 01:27:23 +0000775 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
776 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000777 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000778 }
779
Douglas Gregora30d0462009-05-26 14:40:08 +0000780 unsigned Idx = 0;
781 unsigned TotalBytes = 0;
782#define TYPE(Name, Parent) \
783 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000784 llvm::errs() << " " << counts[Idx] << " " << #Name \
785 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000786 TotalBytes += counts[Idx] * sizeof(Name##Type); \
787 ++Idx;
788#define ABSTRACT_TYPE(Name, Parent)
789#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000790
Chandler Carruth3c147a72011-07-04 05:32:14 +0000791 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
792
Douglas Gregor7454c562010-07-02 20:37:36 +0000793 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000794 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
795 << NumImplicitDefaultConstructors
796 << " implicit default constructors created\n";
797 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
798 << NumImplicitCopyConstructors
799 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000800 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000801 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
802 << NumImplicitMoveConstructors
803 << " implicit move constructors created\n";
804 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
805 << NumImplicitCopyAssignmentOperators
806 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000807 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000808 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
809 << NumImplicitMoveAssignmentOperators
810 << " implicit move assignment operators created\n";
811 llvm::errs() << NumImplicitDestructorsDeclared << "/"
812 << NumImplicitDestructors
813 << " implicit destructors created\n";
814
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000815 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000816 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000817 ExternalSource->PrintStats();
818 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000819
Douglas Gregor5b11d492010-07-25 17:53:33 +0000820 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000821}
822
Douglas Gregor801c99d2011-08-12 06:49:56 +0000823TypedefDecl *ASTContext::getInt128Decl() const {
824 if (!Int128Decl) {
825 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
826 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
827 getTranslationUnitDecl(),
828 SourceLocation(),
829 SourceLocation(),
830 &Idents.get("__int128_t"),
831 TInfo);
832 }
833
834 return Int128Decl;
835}
836
837TypedefDecl *ASTContext::getUInt128Decl() const {
838 if (!UInt128Decl) {
839 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
840 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
841 getTranslationUnitDecl(),
842 SourceLocation(),
843 SourceLocation(),
844 &Idents.get("__uint128_t"),
845 TInfo);
846 }
847
848 return UInt128Decl;
849}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000850
John McCall48f2d582009-10-23 23:03:21 +0000851void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000852 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000853 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000854 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000855}
856
Douglas Gregore8bbc122011-09-02 00:18:52 +0000857void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
858 assert((!this->Target || this->Target == &Target) &&
859 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000860 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000861
Douglas Gregore8bbc122011-09-02 00:18:52 +0000862 this->Target = &Target;
863
864 ABI.reset(createCXXABI(Target));
865 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
866
Chris Lattner970e54e2006-11-12 00:37:36 +0000867 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000868 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000869
Chris Lattner970e54e2006-11-12 00:37:36 +0000870 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000871 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000872 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000873 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000874 InitBuiltinType(CharTy, BuiltinType::Char_S);
875 else
876 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000877 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000878 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
879 InitBuiltinType(ShortTy, BuiltinType::Short);
880 InitBuiltinType(IntTy, BuiltinType::Int);
881 InitBuiltinType(LongTy, BuiltinType::Long);
882 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000883
Chris Lattner970e54e2006-11-12 00:37:36 +0000884 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000885 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
886 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
887 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
888 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
889 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000890
Chris Lattner970e54e2006-11-12 00:37:36 +0000891 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000892 InitBuiltinType(FloatTy, BuiltinType::Float);
893 InitBuiltinType(DoubleTy, BuiltinType::Double);
894 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000895
Chris Lattnerf122cef2009-04-30 02:43:43 +0000896 // GNU extension, 128-bit integers.
897 InitBuiltinType(Int128Ty, BuiltinType::Int128);
898 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
899
Hans Wennborg0d81e012013-05-10 10:08:40 +0000900 // C++ 3.9.1p5
901 if (TargetInfo::isTypeSigned(Target.getWCharType()))
902 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
903 else // -fshort-wchar makes wchar_t be unsigned.
904 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
905 if (LangOpts.CPlusPlus && LangOpts.WChar)
906 WideCharTy = WCharTy;
907 else {
908 // C99 (or C++ using -fno-wchar).
909 WideCharTy = getFromTargetType(Target.getWCharType());
910 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000911
James Molloy36365542012-05-04 10:55:22 +0000912 WIntTy = getFromTargetType(Target.getWIntType());
913
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000914 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
915 InitBuiltinType(Char16Ty, BuiltinType::Char16);
916 else // C99
917 Char16Ty = getFromTargetType(Target.getChar16Type());
918
919 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
920 InitBuiltinType(Char32Ty, BuiltinType::Char32);
921 else // C99
922 Char32Ty = getFromTargetType(Target.getChar32Type());
923
Douglas Gregor4619e432008-12-05 23:32:09 +0000924 // Placeholder type for type-dependent expressions whose type is
925 // completely unknown. No code should ever check a type against
926 // DependentTy and users should never see it; however, it is here to
927 // help diagnose failures to properly check for type-dependent
928 // expressions.
929 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000930
John McCall36e7fe32010-10-12 00:20:44 +0000931 // Placeholder type for functions.
932 InitBuiltinType(OverloadTy, BuiltinType::Overload);
933
John McCall0009fcc2011-04-26 20:42:42 +0000934 // Placeholder type for bound members.
935 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
936
John McCall526ab472011-10-25 17:37:35 +0000937 // Placeholder type for pseudo-objects.
938 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
939
John McCall31996342011-04-07 08:22:57 +0000940 // "any" type; useful for debugger-like clients.
941 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
942
John McCall8a6b59a2011-10-17 18:09:15 +0000943 // Placeholder type for unbridged ARC casts.
944 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
945
Eli Friedman34866c72012-08-31 00:14:07 +0000946 // Placeholder type for builtin functions.
947 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
948
Chris Lattner970e54e2006-11-12 00:37:36 +0000949 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000950 FloatComplexTy = getComplexType(FloatTy);
951 DoubleComplexTy = getComplexType(DoubleTy);
952 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000953
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000954 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000955 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
956 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000957 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000958
959 if (LangOpts.OpenCL) {
960 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
961 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
962 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
963 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
964 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
965 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000966
Guy Benyei61054192013-02-07 10:55:47 +0000967 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000968 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000969 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000970
971 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000972 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
973 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000974
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000975 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +0000976
977 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000978
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000979 // void * type
980 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000981
982 // nullptr type (C++0x 2.14.7)
983 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000984
985 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
986 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +0000987
988 // Builtin type used to help define __builtin_va_list.
989 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +0000990}
991
David Blaikie9c902b52011-09-25 23:23:43 +0000992DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000993 return SourceMgr.getDiagnostics();
994}
995
Douglas Gregor561eceb2010-08-30 16:49:28 +0000996AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
997 AttrVec *&Result = DeclAttrs[D];
998 if (!Result) {
999 void *Mem = Allocate(sizeof(AttrVec));
1000 Result = new (Mem) AttrVec;
1001 }
1002
1003 return *Result;
1004}
1005
1006/// \brief Erase the attributes corresponding to the given declaration.
1007void ASTContext::eraseDeclAttrs(const Decl *D) {
1008 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1009 if (Pos != DeclAttrs.end()) {
1010 Pos->second->~AttrVec();
1011 DeclAttrs.erase(Pos);
1012 }
1013}
1014
Douglas Gregor86d142a2009-10-08 07:24:58 +00001015MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001016ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001017 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +00001018 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001019 = InstantiatedFromStaticDataMember.find(Var);
1020 if (Pos == InstantiatedFromStaticDataMember.end())
1021 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001022
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001023 return Pos->second;
1024}
1025
Mike Stump11289f42009-09-09 15:08:12 +00001026void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001027ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001028 TemplateSpecializationKind TSK,
1029 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001030 assert(Inst->isStaticDataMember() && "Not a static data member");
1031 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1032 assert(!InstantiatedFromStaticDataMember[Inst] &&
1033 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +00001034 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001035 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001036}
1037
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001038FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1039 const FunctionDecl *FD){
1040 assert(FD && "Specialization is 0");
1041 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001042 = ClassScopeSpecializationPattern.find(FD);
1043 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001044 return 0;
1045
1046 return Pos->second;
1047}
1048
1049void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1050 FunctionDecl *Pattern) {
1051 assert(FD && "Specialization is 0");
1052 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001053 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001054}
1055
John McCalle61f2ba2009-11-18 02:36:19 +00001056NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001057ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001058 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001059 = InstantiatedFromUsingDecl.find(UUD);
1060 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001061 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001062
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001063 return Pos->second;
1064}
1065
1066void
John McCallb96ec562009-12-04 22:46:56 +00001067ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1068 assert((isa<UsingDecl>(Pattern) ||
1069 isa<UnresolvedUsingValueDecl>(Pattern) ||
1070 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1071 "pattern decl is not a using decl");
1072 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1073 InstantiatedFromUsingDecl[Inst] = Pattern;
1074}
1075
1076UsingShadowDecl *
1077ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1078 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1079 = InstantiatedFromUsingShadowDecl.find(Inst);
1080 if (Pos == InstantiatedFromUsingShadowDecl.end())
1081 return 0;
1082
1083 return Pos->second;
1084}
1085
1086void
1087ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1088 UsingShadowDecl *Pattern) {
1089 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1090 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001091}
1092
Anders Carlsson5da84842009-09-01 04:26:58 +00001093FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1094 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1095 = InstantiatedFromUnnamedFieldDecl.find(Field);
1096 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1097 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001098
Anders Carlsson5da84842009-09-01 04:26:58 +00001099 return Pos->second;
1100}
1101
1102void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1103 FieldDecl *Tmpl) {
1104 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1105 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1106 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1107 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001108
Anders Carlsson5da84842009-09-01 04:26:58 +00001109 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1110}
1111
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +00001112bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
1113 const FieldDecl *LastFD) const {
1114 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001115 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +00001116}
1117
Fariborz Jahanianeb397412011-05-02 17:20:56 +00001118bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
1119 const FieldDecl *LastFD) const {
1120 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001121 FD->getBitWidthValue(*this) == 0 &&
1122 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +00001123}
1124
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001125bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
1126 const FieldDecl *LastFD) const {
1127 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001128 FD->getBitWidthValue(*this) &&
1129 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001130}
1131
Chad Rosierf01a7dd2011-08-04 23:34:15 +00001132bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001133 const FieldDecl *LastFD) const {
1134 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001135 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001136}
1137
Chad Rosierf01a7dd2011-08-04 23:34:15 +00001138bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001139 const FieldDecl *LastFD) const {
1140 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001141 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001142}
1143
Douglas Gregor832940b2010-03-02 23:58:15 +00001144ASTContext::overridden_cxx_method_iterator
1145ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1146 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001147 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001148 if (Pos == OverriddenMethods.end())
1149 return 0;
1150
1151 return Pos->second.begin();
1152}
1153
1154ASTContext::overridden_cxx_method_iterator
1155ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1156 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001157 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001158 if (Pos == OverriddenMethods.end())
1159 return 0;
1160
1161 return Pos->second.end();
1162}
1163
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001164unsigned
1165ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1166 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001167 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001168 if (Pos == OverriddenMethods.end())
1169 return 0;
1170
1171 return Pos->second.size();
1172}
1173
Douglas Gregor832940b2010-03-02 23:58:15 +00001174void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1175 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001176 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001177 OverriddenMethods[Method].push_back(Overridden);
1178}
1179
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001180void ASTContext::getOverriddenMethods(
1181 const NamedDecl *D,
1182 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001183 assert(D);
1184
1185 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001186 Overridden.append(overridden_methods_begin(CXXMethod),
1187 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001188 return;
1189 }
1190
1191 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1192 if (!Method)
1193 return;
1194
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001195 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1196 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001197 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001198}
1199
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001200void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1201 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1202 assert(!Import->isFromASTFile() && "Non-local import declaration");
1203 if (!FirstLocalImport) {
1204 FirstLocalImport = Import;
1205 LastLocalImport = Import;
1206 return;
1207 }
1208
1209 LastLocalImport->NextLocalImport = Import;
1210 LastLocalImport = Import;
1211}
1212
Chris Lattner53cfe802007-07-18 17:52:12 +00001213//===----------------------------------------------------------------------===//
1214// Type Sizing and Analysis
1215//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001216
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001217/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1218/// scalar floating point type.
1219const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001220 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001221 assert(BT && "Not a floating point type!");
1222 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001223 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001224 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001225 case BuiltinType::Float: return Target->getFloatFormat();
1226 case BuiltinType::Double: return Target->getDoubleFormat();
1227 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001228 }
1229}
1230
Ken Dyck160146e2010-01-27 17:10:57 +00001231/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +00001232/// specified decl. Note that bitfields do not have a valid alignment, so
1233/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001234/// If @p RefAsPointee, references are treated like their underlying type
1235/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +00001236CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001237 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001238
John McCall94268702010-10-08 18:24:19 +00001239 bool UseAlignAttrOnly = false;
1240 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1241 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001242
John McCall94268702010-10-08 18:24:19 +00001243 // __attribute__((aligned)) can increase or decrease alignment
1244 // *except* on a struct or struct member, where it only increases
1245 // alignment unless 'packed' is also specified.
1246 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001247 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001248 // ignore that possibility; Sema should diagnose it.
1249 if (isa<FieldDecl>(D)) {
1250 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1251 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1252 } else {
1253 UseAlignAttrOnly = true;
1254 }
1255 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001256 else if (isa<FieldDecl>(D))
1257 UseAlignAttrOnly =
1258 D->hasAttr<PackedAttr>() ||
1259 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001260
John McCall4e819612011-01-20 07:57:12 +00001261 // If we're using the align attribute only, just ignore everything
1262 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001263 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001264 // do nothing
1265
John McCall94268702010-10-08 18:24:19 +00001266 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001267 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001268 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001269 if (RefAsPointee)
1270 T = RT->getPointeeType();
1271 else
1272 T = getPointerType(RT->getPointeeType());
1273 }
1274 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001275 // Adjust alignments of declarations with array type by the
1276 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +00001277 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +00001278 const ArrayType *arrayType;
1279 if (MinWidth && (arrayType = getAsArrayType(T))) {
1280 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001281 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +00001282 else if (isa<ConstantArrayType>(arrayType) &&
1283 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001284 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +00001285
John McCall33ddac02011-01-19 10:06:00 +00001286 // Walk through any array types while we're at it.
1287 T = getBaseElementType(arrayType);
1288 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001289 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001290 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1291 if (VD->hasGlobalStorage())
1292 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1293 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001294 }
John McCall4e819612011-01-20 07:57:12 +00001295
1296 // Fields can be subject to extra alignment constraints, like if
1297 // the field is packed, the struct is packed, or the struct has a
1298 // a max-field-alignment constraint (#pragma pack). So calculate
1299 // the actual alignment of the field within the struct, and then
1300 // (as we're expected to) constrain that by the alignment of the type.
1301 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1302 // So calculate the alignment of the field.
1303 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1304
1305 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +00001306 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001307
1308 // Use the GCD of that and the offset within the record.
1309 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1310 if (offset > 0) {
1311 // Alignment is always a power of 2, so the GCD will be a power of 2,
1312 // which means we get to do this crazy thing instead of Euclid's.
1313 uint64_t lowBitOfOffset = offset & (~offset + 1);
1314 if (lowBitOfOffset < fieldAlign)
1315 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1316 }
1317
1318 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +00001319 }
Chris Lattner68061312009-01-24 21:53:27 +00001320 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001321
Ken Dyckcc56c542011-01-15 18:38:59 +00001322 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001323}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001324
John McCallf1249922012-08-21 04:10:00 +00001325// getTypeInfoDataSizeInChars - Return the size of a type, in
1326// chars. If the type is a record, its data size is returned. This is
1327// the size of the memcpy that's performed when assigning this type
1328// using a trivial copy/move assignment operator.
1329std::pair<CharUnits, CharUnits>
1330ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1331 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1332
1333 // In C++, objects can sometimes be allocated into the tail padding
1334 // of a base-class subobject. We decide whether that's possible
1335 // during class layout, so here we can just trust the layout results.
1336 if (getLangOpts().CPlusPlus) {
1337 if (const RecordType *RT = T->getAs<RecordType>()) {
1338 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1339 sizeAndAlign.first = layout.getDataSize();
1340 }
1341 }
1342
1343 return sizeAndAlign;
1344}
1345
John McCall87fe5d52010-05-20 01:18:31 +00001346std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001347ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001348 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +00001349 return std::make_pair(toCharUnitsFromBits(Info.first),
1350 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +00001351}
1352
1353std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001354ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001355 return getTypeInfoInChars(T.getTypePtr());
1356}
1357
Daniel Dunbarc6475872012-03-09 04:12:54 +00001358std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1359 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1360 if (it != MemoizedTypeInfo.end())
1361 return it->second;
1362
1363 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1364 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1365 return Info;
1366}
1367
1368/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1369/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001370///
1371/// FIXME: Pointers into different addr spaces could have different sizes and
1372/// alignment requirements: getPointerInfo should take an AddrSpace, this
1373/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001374std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001375ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001376 uint64_t Width=0;
1377 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001378 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001379#define TYPE(Class, Base)
1380#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001381#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001382#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1383#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001384 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001385
Chris Lattner355332d2007-07-13 22:27:08 +00001386 case Type::FunctionNoProto:
1387 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001388 // GCC extension: alignof(function) = 32 bits
1389 Width = 0;
1390 Align = 32;
1391 break;
1392
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001393 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001394 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001395 Width = 0;
1396 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1397 break;
1398
Steve Naroff5c131802007-08-30 01:06:46 +00001399 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001400 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001401
Chris Lattner37e05872008-03-05 18:54:05 +00001402 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001403 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001404 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1405 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001406 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001407 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +00001408 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001409 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001410 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001411 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001412 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001413 const VectorType *VT = cast<VectorType>(T);
1414 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1415 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001416 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001417 // If the alignment is not a power of 2, round up to the next power of 2.
1418 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001419 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001420 Align = llvm::NextPowerOf2(Align);
1421 Width = llvm::RoundUpToAlignment(Width, Align);
1422 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001423 // Adjust the alignment based on the target max.
1424 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1425 if (TargetVectorAlign && TargetVectorAlign < Align)
1426 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001427 break;
1428 }
Chris Lattner647fb222007-07-18 18:26:58 +00001429
Chris Lattner7570e9c2008-03-08 08:52:55 +00001430 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001431 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001432 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001433 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001434 // GCC extension: alignof(void) = 8 bits.
1435 Width = 0;
1436 Align = 8;
1437 break;
1438
Chris Lattner6a4f7452007-12-19 19:23:28 +00001439 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001440 Width = Target->getBoolWidth();
1441 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001442 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001443 case BuiltinType::Char_S:
1444 case BuiltinType::Char_U:
1445 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001446 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001447 Width = Target->getCharWidth();
1448 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001449 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001450 case BuiltinType::WChar_S:
1451 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001452 Width = Target->getWCharWidth();
1453 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001454 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001455 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001456 Width = Target->getChar16Width();
1457 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001458 break;
1459 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001460 Width = Target->getChar32Width();
1461 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001462 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001463 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001464 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001465 Width = Target->getShortWidth();
1466 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001467 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001468 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001469 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001470 Width = Target->getIntWidth();
1471 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001472 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001473 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001474 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001475 Width = Target->getLongWidth();
1476 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001477 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001478 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001479 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001480 Width = Target->getLongLongWidth();
1481 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001482 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001483 case BuiltinType::Int128:
1484 case BuiltinType::UInt128:
1485 Width = 128;
1486 Align = 128; // int128_t is 128-bit aligned on all targets.
1487 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001488 case BuiltinType::Half:
1489 Width = Target->getHalfWidth();
1490 Align = Target->getHalfAlign();
1491 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001492 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001493 Width = Target->getFloatWidth();
1494 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001495 break;
1496 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001497 Width = Target->getDoubleWidth();
1498 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001499 break;
1500 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001501 Width = Target->getLongDoubleWidth();
1502 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001503 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001504 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001505 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1506 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001507 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001508 case BuiltinType::ObjCId:
1509 case BuiltinType::ObjCClass:
1510 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001511 Width = Target->getPointerWidth(0);
1512 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001513 break;
Guy Benyei61054192013-02-07 10:55:47 +00001514 case BuiltinType::OCLSampler:
1515 // Samplers are modeled as integers.
1516 Width = Target->getIntWidth();
1517 Align = Target->getIntAlign();
1518 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001519 case BuiltinType::OCLEvent:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001520 case BuiltinType::OCLImage1d:
1521 case BuiltinType::OCLImage1dArray:
1522 case BuiltinType::OCLImage1dBuffer:
1523 case BuiltinType::OCLImage2d:
1524 case BuiltinType::OCLImage2dArray:
1525 case BuiltinType::OCLImage3d:
1526 // Currently these types are pointers to opaque types.
1527 Width = Target->getPointerWidth(0);
1528 Align = Target->getPointerAlign(0);
1529 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001530 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001531 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001532 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001533 Width = Target->getPointerWidth(0);
1534 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001535 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001536 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001537 unsigned AS = getTargetAddressSpace(
1538 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001539 Width = Target->getPointerWidth(AS);
1540 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001541 break;
1542 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001543 case Type::LValueReference:
1544 case Type::RValueReference: {
1545 // alignof and sizeof should never enter this code path here, so we go
1546 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001547 unsigned AS = getTargetAddressSpace(
1548 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001549 Width = Target->getPointerWidth(AS);
1550 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001551 break;
1552 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001553 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001554 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001555 Width = Target->getPointerWidth(AS);
1556 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001557 break;
1558 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001559 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001560 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Reid Kleckner3a52abf2013-03-28 20:02:56 +00001561 llvm::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001562 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001563 }
Chris Lattner647fb222007-07-18 18:26:58 +00001564 case Type::Complex: {
1565 // Complex types have the same alignment as their elements, but twice the
1566 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001567 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001568 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001569 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001570 Align = EltInfo.second;
1571 break;
1572 }
John McCall8b07ec22010-05-15 11:32:37 +00001573 case Type::ObjCObject:
1574 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001575 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001576 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001577 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001578 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001579 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001580 break;
1581 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001582 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001583 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001584 const TagType *TT = cast<TagType>(T);
1585
1586 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001587 Width = 8;
1588 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001589 break;
1590 }
Mike Stump11289f42009-09-09 15:08:12 +00001591
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001592 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001593 return getTypeInfo(ET->getDecl()->getIntegerType());
1594
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001595 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001596 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001597 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001598 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001599 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001600 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001601
Chris Lattner63d2b362009-10-22 05:17:15 +00001602 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001603 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1604 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001605
Richard Smith30482bc2011-02-20 03:19:35 +00001606 case Type::Auto: {
1607 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001608 assert(!A->getDeducedType().isNull() &&
1609 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001610 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001611 }
1612
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001613 case Type::Paren:
1614 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1615
Douglas Gregoref462e62009-04-30 17:32:17 +00001616 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001617 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001618 std::pair<uint64_t, unsigned> Info
1619 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001620 // If the typedef has an aligned attribute on it, it overrides any computed
1621 // alignment we have. This violates the GCC documentation (which says that
1622 // attribute(aligned) can only round up) but matches its implementation.
1623 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1624 Align = AttrAlign;
1625 else
1626 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001627 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001628 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001629 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001630
1631 case Type::TypeOfExpr:
1632 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1633 .getTypePtr());
1634
1635 case Type::TypeOf:
1636 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1637
Anders Carlsson81df7b82009-06-24 19:06:50 +00001638 case Type::Decltype:
1639 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1640 .getTypePtr());
1641
Alexis Hunte852b102011-05-24 22:41:36 +00001642 case Type::UnaryTransform:
1643 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1644
Abramo Bagnara6150c882010-05-11 21:36:43 +00001645 case Type::Elaborated:
1646 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001647
John McCall81904512011-01-06 01:58:22 +00001648 case Type::Attributed:
1649 return getTypeInfo(
1650 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1651
Richard Smith3f1b5d02011-05-05 21:57:07 +00001652 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001653 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001654 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001655 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1656 // A type alias template specialization may refer to a typedef with the
1657 // aligned attribute on it.
1658 if (TST->isTypeAlias())
1659 return getTypeInfo(TST->getAliasedType().getTypePtr());
1660 else
1661 return getTypeInfo(getCanonicalType(T));
1662 }
1663
Eli Friedman0dfb8892011-10-06 23:00:33 +00001664 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001665 // Start with the base type information.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001666 std::pair<uint64_t, unsigned> Info
1667 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1668 Width = Info.first;
1669 Align = Info.second;
John McCalla8ec7eb2013-03-07 21:37:17 +00001670
1671 // If the size of the type doesn't exceed the platform's max
1672 // atomic promotion width, make the size and alignment more
1673 // favorable to atomic operations:
1674 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1675 // Round the size up to a power of 2.
1676 if (!llvm::isPowerOf2_64(Width))
1677 Width = llvm::NextPowerOf2(Width);
1678
1679 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001680 Align = static_cast<unsigned>(Width);
1681 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001682 }
1683
Douglas Gregoref462e62009-04-30 17:32:17 +00001684 }
Mike Stump11289f42009-09-09 15:08:12 +00001685
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001686 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001687 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001688}
1689
Ken Dyckcc56c542011-01-15 18:38:59 +00001690/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1691CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1692 return CharUnits::fromQuantity(BitSize / getCharWidth());
1693}
1694
Ken Dyckb0fcc592011-02-11 01:54:29 +00001695/// toBits - Convert a size in characters to a size in characters.
1696int64_t ASTContext::toBits(CharUnits CharSize) const {
1697 return CharSize.getQuantity() * getCharWidth();
1698}
1699
Ken Dyck8c89d592009-12-22 14:23:30 +00001700/// getTypeSizeInChars - Return the size of the specified type, in characters.
1701/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001702CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001703 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001704}
Jay Foad39c79802011-01-12 09:06:06 +00001705CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001706 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001707}
1708
Ken Dycka6046ab2010-01-26 17:25:18 +00001709/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001710/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001711CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001712 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001713}
Jay Foad39c79802011-01-12 09:06:06 +00001714CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001715 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001716}
1717
Chris Lattnera3402cd2009-01-27 18:08:34 +00001718/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1719/// type for the current target in bits. This can be different than the ABI
1720/// alignment in cases where it is beneficial for performance to overalign
1721/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001722unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001723 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001724
1725 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001726 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001727 T = CT->getElementType().getTypePtr();
1728 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001729 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1730 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001731 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1732
Chris Lattnera3402cd2009-01-27 18:08:34 +00001733 return ABIAlign;
1734}
1735
Ulrich Weigandfa806422013-05-06 16:23:57 +00001736/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1737/// to a global variable of the specified type.
1738unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1739 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1740}
1741
1742/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1743/// should be given to a global variable of the specified type.
1744CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1745 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1746}
1747
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001748/// DeepCollectObjCIvars -
1749/// This routine first collects all declared, but not synthesized, ivars in
1750/// super class and then collects all ivars, including those synthesized for
1751/// current class. This routine is used for implementation of current class
1752/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001753///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001754void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1755 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001756 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001757 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1758 DeepCollectObjCIvars(SuperClass, false, Ivars);
1759 if (!leafClass) {
1760 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1761 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001762 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001763 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001764 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001765 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001766 Iv= Iv->getNextIvar())
1767 Ivars.push_back(Iv);
1768 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001769}
1770
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001771/// CollectInheritedProtocols - Collect all protocols in current class and
1772/// those inherited by it.
1773void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001774 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001775 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001776 // We can use protocol_iterator here instead of
1777 // all_referenced_protocol_iterator since we are walking all categories.
1778 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1779 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001780 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001781 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001782 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001783 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001784 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001785 CollectInheritedProtocols(*P, Protocols);
1786 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001787 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001788
1789 // Categories of this Interface.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001790 for (ObjCInterfaceDecl::visible_categories_iterator
1791 Cat = OI->visible_categories_begin(),
1792 CatEnd = OI->visible_categories_end();
1793 Cat != CatEnd; ++Cat) {
1794 CollectInheritedProtocols(*Cat, Protocols);
1795 }
1796
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001797 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1798 while (SD) {
1799 CollectInheritedProtocols(SD, Protocols);
1800 SD = SD->getSuperClass();
1801 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001802 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001803 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001804 PE = OC->protocol_end(); P != PE; ++P) {
1805 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001806 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001807 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1808 PE = Proto->protocol_end(); P != PE; ++P)
1809 CollectInheritedProtocols(*P, Protocols);
1810 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001811 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001812 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1813 PE = OP->protocol_end(); P != PE; ++P) {
1814 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001815 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001816 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1817 PE = Proto->protocol_end(); P != PE; ++P)
1818 CollectInheritedProtocols(*P, Protocols);
1819 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001820 }
1821}
1822
Jay Foad39c79802011-01-12 09:06:06 +00001823unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001824 unsigned count = 0;
1825 // Count ivars declared in class extension.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001826 for (ObjCInterfaceDecl::known_extensions_iterator
1827 Ext = OI->known_extensions_begin(),
1828 ExtEnd = OI->known_extensions_end();
1829 Ext != ExtEnd; ++Ext) {
1830 count += Ext->ivar_size();
1831 }
1832
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001833 // Count ivar defined in this class's implementation. This
1834 // includes synthesized ivars.
1835 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001836 count += ImplDecl->ivar_size();
1837
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001838 return count;
1839}
1840
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001841bool ASTContext::isSentinelNullExpr(const Expr *E) {
1842 if (!E)
1843 return false;
1844
1845 // nullptr_t is always treated as null.
1846 if (E->getType()->isNullPtrType()) return true;
1847
1848 if (E->getType()->isAnyPointerType() &&
1849 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1850 Expr::NPC_ValueDependentIsNull))
1851 return true;
1852
1853 // Unfortunately, __null has type 'int'.
1854 if (isa<GNUNullExpr>(E)) return true;
1855
1856 return false;
1857}
1858
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001859/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1860ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1861 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1862 I = ObjCImpls.find(D);
1863 if (I != ObjCImpls.end())
1864 return cast<ObjCImplementationDecl>(I->second);
1865 return 0;
1866}
1867/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1868ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1869 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1870 I = ObjCImpls.find(D);
1871 if (I != ObjCImpls.end())
1872 return cast<ObjCCategoryImplDecl>(I->second);
1873 return 0;
1874}
1875
1876/// \brief Set the implementation of ObjCInterfaceDecl.
1877void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1878 ObjCImplementationDecl *ImplD) {
1879 assert(IFaceD && ImplD && "Passed null params");
1880 ObjCImpls[IFaceD] = ImplD;
1881}
1882/// \brief Set the implementation of ObjCCategoryDecl.
1883void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1884 ObjCCategoryImplDecl *ImplD) {
1885 assert(CatD && ImplD && "Passed null params");
1886 ObjCImpls[CatD] = ImplD;
1887}
1888
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001889const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1890 const NamedDecl *ND) const {
1891 if (const ObjCInterfaceDecl *ID =
1892 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001893 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001894 if (const ObjCCategoryDecl *CD =
1895 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001896 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001897 if (const ObjCImplDecl *IMD =
1898 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001899 return IMD->getClassInterface();
1900
1901 return 0;
1902}
1903
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001904/// \brief Get the copy initialization expression of VarDecl,or NULL if
1905/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001906Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001907 assert(VD && "Passed null params");
1908 assert(VD->hasAttr<BlocksAttr>() &&
1909 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001910 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001911 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001912 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1913}
1914
1915/// \brief Set the copy inialization expression of a block var decl.
1916void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1917 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001918 assert(VD->hasAttr<BlocksAttr>() &&
1919 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001920 BlockVarCopyInits[VD] = Init;
1921}
1922
John McCallbcd03502009-12-07 02:54:59 +00001923TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001924 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001925 if (!DataSize)
1926 DataSize = TypeLoc::getFullDataSizeForType(T);
1927 else
1928 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001929 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001930
John McCallbcd03502009-12-07 02:54:59 +00001931 TypeSourceInfo *TInfo =
1932 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1933 new (TInfo) TypeSourceInfo(T);
1934 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001935}
1936
John McCallbcd03502009-12-07 02:54:59 +00001937TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001938 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001939 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001940 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001941 return DI;
1942}
1943
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001944const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001945ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001946 return getObjCLayout(D, 0);
1947}
1948
1949const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001950ASTContext::getASTObjCImplementationLayout(
1951 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001952 return getObjCLayout(D->getClassInterface(), D);
1953}
1954
Chris Lattner983a8bb2007-07-13 22:13:22 +00001955//===----------------------------------------------------------------------===//
1956// Type creation/memoization methods
1957//===----------------------------------------------------------------------===//
1958
Jay Foad39c79802011-01-12 09:06:06 +00001959QualType
John McCall33ddac02011-01-19 10:06:00 +00001960ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1961 unsigned fastQuals = quals.getFastQualifiers();
1962 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001963
1964 // Check if we've already instantiated this type.
1965 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001966 ExtQuals::Profile(ID, baseType, quals);
1967 void *insertPos = 0;
1968 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1969 assert(eq->getQualifiers() == quals);
1970 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001971 }
1972
John McCall33ddac02011-01-19 10:06:00 +00001973 // If the base type is not canonical, make the appropriate canonical type.
1974 QualType canon;
1975 if (!baseType->isCanonicalUnqualified()) {
1976 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001977 canonSplit.Quals.addConsistentQualifiers(quals);
1978 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001979
1980 // Re-find the insert position.
1981 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1982 }
1983
1984 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1985 ExtQualNodes.InsertNode(eq, insertPos);
1986 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001987}
1988
Jay Foad39c79802011-01-12 09:06:06 +00001989QualType
1990ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001991 QualType CanT = getCanonicalType(T);
1992 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001993 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001994
John McCall8ccfcb52009-09-24 19:53:00 +00001995 // If we are composing extended qualifiers together, merge together
1996 // into one ExtQuals node.
1997 QualifierCollector Quals;
1998 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001999
John McCall8ccfcb52009-09-24 19:53:00 +00002000 // If this type already has an address space specified, it cannot get
2001 // another one.
2002 assert(!Quals.hasAddressSpace() &&
2003 "Type cannot be in multiple addr spaces!");
2004 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002005
John McCall8ccfcb52009-09-24 19:53:00 +00002006 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002007}
2008
Chris Lattnerd60183d2009-02-18 22:53:11 +00002009QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002010 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002011 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002012 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002013 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002014
John McCall53fa7142010-12-24 02:08:15 +00002015 if (const PointerType *ptr = T->getAs<PointerType>()) {
2016 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002017 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002018 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2019 return getPointerType(ResultType);
2020 }
2021 }
Mike Stump11289f42009-09-09 15:08:12 +00002022
John McCall8ccfcb52009-09-24 19:53:00 +00002023 // If we are composing extended qualifiers together, merge together
2024 // into one ExtQuals node.
2025 QualifierCollector Quals;
2026 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002027
John McCall8ccfcb52009-09-24 19:53:00 +00002028 // If this type already has an ObjCGC specified, it cannot get
2029 // another one.
2030 assert(!Quals.hasObjCGCAttr() &&
2031 "Type cannot have multiple ObjCGCs!");
2032 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002033
John McCall8ccfcb52009-09-24 19:53:00 +00002034 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002035}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002036
John McCall4f5019e2010-12-19 02:44:49 +00002037const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2038 FunctionType::ExtInfo Info) {
2039 if (T->getExtInfo() == Info)
2040 return T;
2041
2042 QualType Result;
2043 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2044 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
2045 } else {
2046 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2047 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2048 EPI.ExtInfo = Info;
Jordan Rose5c382722013-03-08 21:51:21 +00002049 Result = getFunctionType(FPT->getResultType(),
2050 ArrayRef<QualType>(FPT->arg_type_begin(),
2051 FPT->getNumArgs()),
2052 EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002053 }
2054
2055 return cast<FunctionType>(Result.getTypePtr());
2056}
2057
Richard Smith2a7d4812013-05-04 07:00:32 +00002058void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2059 QualType ResultType) {
2060 // FIXME: Need to inform serialization code about this!
2061 for (FD = FD->getMostRecentDecl(); FD; FD = FD->getPreviousDecl()) {
2062 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2063 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2064 FD->setType(getFunctionType(ResultType, FPT->getArgTypes(), EPI));
2065 }
2066}
2067
Chris Lattnerc6395932007-06-22 20:56:16 +00002068/// getComplexType - Return the uniqued reference to the type for a complex
2069/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002070QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002071 // Unique pointers, to guarantee there is only one pointer of a particular
2072 // structure.
2073 llvm::FoldingSetNodeID ID;
2074 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002075
Chris Lattnerc6395932007-06-22 20:56:16 +00002076 void *InsertPos = 0;
2077 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2078 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002079
Chris Lattnerc6395932007-06-22 20:56:16 +00002080 // If the pointee type isn't canonical, this won't be a canonical type either,
2081 // so fill in the canonical type field.
2082 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002083 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002084 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002085
Chris Lattnerc6395932007-06-22 20:56:16 +00002086 // Get the new insert position for the node we care about.
2087 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002088 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002089 }
John McCall90d1c2d2009-09-24 23:30:46 +00002090 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002091 Types.push_back(New);
2092 ComplexTypes.InsertNode(New, InsertPos);
2093 return QualType(New, 0);
2094}
2095
Chris Lattner970e54e2006-11-12 00:37:36 +00002096/// getPointerType - Return the uniqued reference to the type for a pointer to
2097/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002098QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002099 // Unique pointers, to guarantee there is only one pointer of a particular
2100 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002101 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002102 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002103
Chris Lattner67521df2007-01-27 01:29:36 +00002104 void *InsertPos = 0;
2105 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002106 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002107
Chris Lattner7ccecb92006-11-12 08:50:50 +00002108 // If the pointee type isn't canonical, this won't be a canonical type either,
2109 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002110 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002111 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002112 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002113
Bob Wilsonc8541f22013-03-15 17:12:43 +00002114 // Get the new insert position for the node we care about.
2115 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2116 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2117 }
John McCall90d1c2d2009-09-24 23:30:46 +00002118 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002119 Types.push_back(New);
2120 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002121 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002122}
2123
Mike Stump11289f42009-09-09 15:08:12 +00002124/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002125/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002126QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002127 assert(T->isFunctionType() && "block of function types only");
2128 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002129 // structure.
2130 llvm::FoldingSetNodeID ID;
2131 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002132
Steve Naroffec33ed92008-08-27 16:04:49 +00002133 void *InsertPos = 0;
2134 if (BlockPointerType *PT =
2135 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2136 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002137
2138 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002139 // type either so fill in the canonical type field.
2140 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002141 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002142 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002143
Steve Naroffec33ed92008-08-27 16:04:49 +00002144 // Get the new insert position for the node we care about.
2145 BlockPointerType *NewIP =
2146 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002147 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002148 }
John McCall90d1c2d2009-09-24 23:30:46 +00002149 BlockPointerType *New
2150 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002151 Types.push_back(New);
2152 BlockPointerTypes.InsertNode(New, InsertPos);
2153 return QualType(New, 0);
2154}
2155
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002156/// getLValueReferenceType - Return the uniqued reference to the type for an
2157/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002158QualType
2159ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002160 assert(getCanonicalType(T) != OverloadTy &&
2161 "Unresolved overloaded function type");
2162
Bill Wendling3708c182007-05-27 10:15:43 +00002163 // Unique pointers, to guarantee there is only one pointer of a particular
2164 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002165 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002166 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002167
2168 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002169 if (LValueReferenceType *RT =
2170 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002171 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002172
John McCallfc93cf92009-10-22 22:37:11 +00002173 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2174
Bill Wendling3708c182007-05-27 10:15:43 +00002175 // If the referencee type isn't canonical, this won't be a canonical type
2176 // either, so fill in the canonical type field.
2177 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002178 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2179 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2180 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002181
Bill Wendling3708c182007-05-27 10:15:43 +00002182 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002183 LValueReferenceType *NewIP =
2184 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002185 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002186 }
2187
John McCall90d1c2d2009-09-24 23:30:46 +00002188 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002189 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2190 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002191 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002192 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002193
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002194 return QualType(New, 0);
2195}
2196
2197/// getRValueReferenceType - Return the uniqued reference to the type for an
2198/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002199QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002200 // Unique pointers, to guarantee there is only one pointer of a particular
2201 // structure.
2202 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002203 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002204
2205 void *InsertPos = 0;
2206 if (RValueReferenceType *RT =
2207 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2208 return QualType(RT, 0);
2209
John McCallfc93cf92009-10-22 22:37:11 +00002210 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2211
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002212 // If the referencee type isn't canonical, this won't be a canonical type
2213 // either, so fill in the canonical type field.
2214 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002215 if (InnerRef || !T.isCanonical()) {
2216 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2217 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002218
2219 // Get the new insert position for the node we care about.
2220 RValueReferenceType *NewIP =
2221 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002222 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002223 }
2224
John McCall90d1c2d2009-09-24 23:30:46 +00002225 RValueReferenceType *New
2226 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002227 Types.push_back(New);
2228 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002229 return QualType(New, 0);
2230}
2231
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002232/// getMemberPointerType - Return the uniqued reference to the type for a
2233/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002234QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002235 // Unique pointers, to guarantee there is only one pointer of a particular
2236 // structure.
2237 llvm::FoldingSetNodeID ID;
2238 MemberPointerType::Profile(ID, T, Cls);
2239
2240 void *InsertPos = 0;
2241 if (MemberPointerType *PT =
2242 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2243 return QualType(PT, 0);
2244
2245 // If the pointee or class type isn't canonical, this won't be a canonical
2246 // type either, so fill in the canonical type field.
2247 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002248 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002249 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2250
2251 // Get the new insert position for the node we care about.
2252 MemberPointerType *NewIP =
2253 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002254 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002255 }
John McCall90d1c2d2009-09-24 23:30:46 +00002256 MemberPointerType *New
2257 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002258 Types.push_back(New);
2259 MemberPointerTypes.InsertNode(New, InsertPos);
2260 return QualType(New, 0);
2261}
2262
Mike Stump11289f42009-09-09 15:08:12 +00002263/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002264/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002265QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002266 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002267 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002268 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002269 assert((EltTy->isDependentType() ||
2270 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002271 "Constant array of VLAs is illegal!");
2272
Chris Lattnere2df3f92009-05-13 04:12:56 +00002273 // Convert the array size into a canonical width matching the pointer size for
2274 // the target.
2275 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002276 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002277 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002278
Chris Lattner23b7eb62007-06-15 23:05:46 +00002279 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002280 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002281
Chris Lattner36f8e652007-01-27 08:31:04 +00002282 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002283 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002284 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002285 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002286
John McCall33ddac02011-01-19 10:06:00 +00002287 // If the element type isn't canonical or has qualifiers, this won't
2288 // be a canonical type either, so fill in the canonical type field.
2289 QualType Canon;
2290 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2291 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002292 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002293 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002294 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002295
Chris Lattner36f8e652007-01-27 08:31:04 +00002296 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002297 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002298 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002299 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002300 }
Mike Stump11289f42009-09-09 15:08:12 +00002301
John McCall90d1c2d2009-09-24 23:30:46 +00002302 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002303 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002304 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002305 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002306 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002307}
2308
John McCall06549462011-01-18 08:40:38 +00002309/// getVariableArrayDecayedType - Turns the given type, which may be
2310/// variably-modified, into the corresponding type with all the known
2311/// sizes replaced with [*].
2312QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2313 // Vastly most common case.
2314 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002315
John McCall06549462011-01-18 08:40:38 +00002316 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002317
John McCall06549462011-01-18 08:40:38 +00002318 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002319 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002320 switch (ty->getTypeClass()) {
2321#define TYPE(Class, Base)
2322#define ABSTRACT_TYPE(Class, Base)
2323#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2324#include "clang/AST/TypeNodes.def"
2325 llvm_unreachable("didn't desugar past all non-canonical types?");
2326
2327 // These types should never be variably-modified.
2328 case Type::Builtin:
2329 case Type::Complex:
2330 case Type::Vector:
2331 case Type::ExtVector:
2332 case Type::DependentSizedExtVector:
2333 case Type::ObjCObject:
2334 case Type::ObjCInterface:
2335 case Type::ObjCObjectPointer:
2336 case Type::Record:
2337 case Type::Enum:
2338 case Type::UnresolvedUsing:
2339 case Type::TypeOfExpr:
2340 case Type::TypeOf:
2341 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002342 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002343 case Type::DependentName:
2344 case Type::InjectedClassName:
2345 case Type::TemplateSpecialization:
2346 case Type::DependentTemplateSpecialization:
2347 case Type::TemplateTypeParm:
2348 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002349 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002350 case Type::PackExpansion:
2351 llvm_unreachable("type should never be variably-modified");
2352
2353 // These types can be variably-modified but should never need to
2354 // further decay.
2355 case Type::FunctionNoProto:
2356 case Type::FunctionProto:
2357 case Type::BlockPointer:
2358 case Type::MemberPointer:
2359 return type;
2360
2361 // These types can be variably-modified. All these modifications
2362 // preserve structure except as noted by comments.
2363 // TODO: if we ever care about optimizing VLAs, there are no-op
2364 // optimizations available here.
2365 case Type::Pointer:
2366 result = getPointerType(getVariableArrayDecayedType(
2367 cast<PointerType>(ty)->getPointeeType()));
2368 break;
2369
2370 case Type::LValueReference: {
2371 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2372 result = getLValueReferenceType(
2373 getVariableArrayDecayedType(lv->getPointeeType()),
2374 lv->isSpelledAsLValue());
2375 break;
2376 }
2377
2378 case Type::RValueReference: {
2379 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2380 result = getRValueReferenceType(
2381 getVariableArrayDecayedType(lv->getPointeeType()));
2382 break;
2383 }
2384
Eli Friedman0dfb8892011-10-06 23:00:33 +00002385 case Type::Atomic: {
2386 const AtomicType *at = cast<AtomicType>(ty);
2387 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2388 break;
2389 }
2390
John McCall06549462011-01-18 08:40:38 +00002391 case Type::ConstantArray: {
2392 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2393 result = getConstantArrayType(
2394 getVariableArrayDecayedType(cat->getElementType()),
2395 cat->getSize(),
2396 cat->getSizeModifier(),
2397 cat->getIndexTypeCVRQualifiers());
2398 break;
2399 }
2400
2401 case Type::DependentSizedArray: {
2402 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2403 result = getDependentSizedArrayType(
2404 getVariableArrayDecayedType(dat->getElementType()),
2405 dat->getSizeExpr(),
2406 dat->getSizeModifier(),
2407 dat->getIndexTypeCVRQualifiers(),
2408 dat->getBracketsRange());
2409 break;
2410 }
2411
2412 // Turn incomplete types into [*] types.
2413 case Type::IncompleteArray: {
2414 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2415 result = getVariableArrayType(
2416 getVariableArrayDecayedType(iat->getElementType()),
2417 /*size*/ 0,
2418 ArrayType::Normal,
2419 iat->getIndexTypeCVRQualifiers(),
2420 SourceRange());
2421 break;
2422 }
2423
2424 // Turn VLA types into [*] types.
2425 case Type::VariableArray: {
2426 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2427 result = getVariableArrayType(
2428 getVariableArrayDecayedType(vat->getElementType()),
2429 /*size*/ 0,
2430 ArrayType::Star,
2431 vat->getIndexTypeCVRQualifiers(),
2432 vat->getBracketsRange());
2433 break;
2434 }
2435 }
2436
2437 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002438 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002439}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002440
Steve Naroffcadebd02007-08-30 18:14:25 +00002441/// getVariableArrayType - Returns a non-unique reference to the type for a
2442/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002443QualType ASTContext::getVariableArrayType(QualType EltTy,
2444 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002445 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002446 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002447 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002448 // Since we don't unique expressions, it isn't possible to unique VLA's
2449 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002450 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002451
John McCall33ddac02011-01-19 10:06:00 +00002452 // Be sure to pull qualifiers off the element type.
2453 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2454 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002455 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002456 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002457 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002458 }
2459
John McCall90d1c2d2009-09-24 23:30:46 +00002460 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002461 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002462
2463 VariableArrayTypes.push_back(New);
2464 Types.push_back(New);
2465 return QualType(New, 0);
2466}
2467
Douglas Gregor4619e432008-12-05 23:32:09 +00002468/// getDependentSizedArrayType - Returns a non-unique reference to
2469/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002470/// type.
John McCall33ddac02011-01-19 10:06:00 +00002471QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2472 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002473 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002474 unsigned elementTypeQuals,
2475 SourceRange brackets) const {
2476 assert((!numElements || numElements->isTypeDependent() ||
2477 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002478 "Size must be type- or value-dependent!");
2479
John McCall33ddac02011-01-19 10:06:00 +00002480 // Dependently-sized array types that do not have a specified number
2481 // of elements will have their sizes deduced from a dependent
2482 // initializer. We do no canonicalization here at all, which is okay
2483 // because they can't be used in most locations.
2484 if (!numElements) {
2485 DependentSizedArrayType *newType
2486 = new (*this, TypeAlignment)
2487 DependentSizedArrayType(*this, elementType, QualType(),
2488 numElements, ASM, elementTypeQuals,
2489 brackets);
2490 Types.push_back(newType);
2491 return QualType(newType, 0);
2492 }
2493
2494 // Otherwise, we actually build a new type every time, but we
2495 // also build a canonical type.
2496
2497 SplitQualType canonElementType = getCanonicalType(elementType).split();
2498
2499 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002500 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002501 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002502 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002503 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002504
John McCall33ddac02011-01-19 10:06:00 +00002505 // Look for an existing type with these properties.
2506 DependentSizedArrayType *canonTy =
2507 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002508
John McCall33ddac02011-01-19 10:06:00 +00002509 // If we don't have one, build one.
2510 if (!canonTy) {
2511 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002512 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002513 QualType(), numElements, ASM, elementTypeQuals,
2514 brackets);
2515 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2516 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002517 }
2518
John McCall33ddac02011-01-19 10:06:00 +00002519 // Apply qualifiers from the element type to the array.
2520 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002521 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002522
John McCall33ddac02011-01-19 10:06:00 +00002523 // If we didn't need extra canonicalization for the element type,
2524 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002525 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002526 return canon;
2527
2528 // Otherwise, we need to build a type which follows the spelling
2529 // of the element type.
2530 DependentSizedArrayType *sugaredType
2531 = new (*this, TypeAlignment)
2532 DependentSizedArrayType(*this, elementType, canon, numElements,
2533 ASM, elementTypeQuals, brackets);
2534 Types.push_back(sugaredType);
2535 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002536}
2537
John McCall33ddac02011-01-19 10:06:00 +00002538QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002539 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002540 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002541 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002542 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002543
John McCall33ddac02011-01-19 10:06:00 +00002544 void *insertPos = 0;
2545 if (IncompleteArrayType *iat =
2546 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2547 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002548
2549 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002550 // either, so fill in the canonical type field. We also have to pull
2551 // qualifiers off the element type.
2552 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002553
John McCall33ddac02011-01-19 10:06:00 +00002554 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2555 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002556 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002557 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002558 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002559
2560 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002561 IncompleteArrayType *existing =
2562 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2563 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002564 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002565
John McCall33ddac02011-01-19 10:06:00 +00002566 IncompleteArrayType *newType = new (*this, TypeAlignment)
2567 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002568
John McCall33ddac02011-01-19 10:06:00 +00002569 IncompleteArrayTypes.InsertNode(newType, insertPos);
2570 Types.push_back(newType);
2571 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002572}
2573
Steve Naroff91fcddb2007-07-18 18:00:27 +00002574/// getVectorType - Return the unique reference to a vector type of
2575/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002576QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002577 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002578 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002579
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002580 // Check if we've already instantiated a vector of this type.
2581 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002582 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002583
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002584 void *InsertPos = 0;
2585 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2586 return QualType(VTP, 0);
2587
2588 // If the element type isn't canonical, this won't be a canonical type either,
2589 // so fill in the canonical type field.
2590 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002591 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002592 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002593
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002594 // Get the new insert position for the node we care about.
2595 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002596 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002597 }
John McCall90d1c2d2009-09-24 23:30:46 +00002598 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002599 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002600 VectorTypes.InsertNode(New, InsertPos);
2601 Types.push_back(New);
2602 return QualType(New, 0);
2603}
2604
Nate Begemance4d7fc2008-04-18 23:10:10 +00002605/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002606/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002607QualType
2608ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002609 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002610
Steve Naroff91fcddb2007-07-18 18:00:27 +00002611 // Check if we've already instantiated a vector of this type.
2612 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002613 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002614 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002615 void *InsertPos = 0;
2616 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2617 return QualType(VTP, 0);
2618
2619 // If the element type isn't canonical, this won't be a canonical type either,
2620 // so fill in the canonical type field.
2621 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002622 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002623 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002624
Steve Naroff91fcddb2007-07-18 18:00:27 +00002625 // Get the new insert position for the node we care about.
2626 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002627 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002628 }
John McCall90d1c2d2009-09-24 23:30:46 +00002629 ExtVectorType *New = new (*this, TypeAlignment)
2630 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002631 VectorTypes.InsertNode(New, InsertPos);
2632 Types.push_back(New);
2633 return QualType(New, 0);
2634}
2635
Jay Foad39c79802011-01-12 09:06:06 +00002636QualType
2637ASTContext::getDependentSizedExtVectorType(QualType vecType,
2638 Expr *SizeExpr,
2639 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002640 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002641 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002642 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002643
Douglas Gregor352169a2009-07-31 03:54:25 +00002644 void *InsertPos = 0;
2645 DependentSizedExtVectorType *Canon
2646 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2647 DependentSizedExtVectorType *New;
2648 if (Canon) {
2649 // We already have a canonical version of this array type; use it as
2650 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002651 New = new (*this, TypeAlignment)
2652 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2653 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002654 } else {
2655 QualType CanonVecTy = getCanonicalType(vecType);
2656 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002657 New = new (*this, TypeAlignment)
2658 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2659 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002660
2661 DependentSizedExtVectorType *CanonCheck
2662 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2663 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2664 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002665 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2666 } else {
2667 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2668 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002669 New = new (*this, TypeAlignment)
2670 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002671 }
2672 }
Mike Stump11289f42009-09-09 15:08:12 +00002673
Douglas Gregor758a8692009-06-17 21:51:59 +00002674 Types.push_back(New);
2675 return QualType(New, 0);
2676}
2677
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002678/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002679///
Jay Foad39c79802011-01-12 09:06:06 +00002680QualType
2681ASTContext::getFunctionNoProtoType(QualType ResultTy,
2682 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002683 const CallingConv DefaultCC = Info.getCC();
2684 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2685 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002686 // Unique functions, to guarantee there is only one function of a particular
2687 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002688 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002689 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002690
Chris Lattner47955de2007-01-27 08:37:20 +00002691 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002692 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002693 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002694 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002695
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002696 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002697 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002698 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002699 Canonical =
2700 getFunctionNoProtoType(getCanonicalType(ResultTy),
2701 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002702
Chris Lattner47955de2007-01-27 08:37:20 +00002703 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002704 FunctionNoProtoType *NewIP =
2705 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002706 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002707 }
Mike Stump11289f42009-09-09 15:08:12 +00002708
Roman Divacky65b88cd2011-03-01 17:40:53 +00002709 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002710 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002711 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002712 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002713 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002714 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002715}
2716
Douglas Gregorcd780372013-01-17 23:36:45 +00002717/// \brief Determine whether \p T is canonical as the result type of a function.
2718static bool isCanonicalResultType(QualType T) {
2719 return T.isCanonical() &&
2720 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2721 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2722}
2723
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002724/// getFunctionType - Return a normal function type with a typed argument
2725/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002726QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002727ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002728 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002729 size_t NumArgs = ArgArray.size();
2730
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002731 // Unique functions, to guarantee there is only one function of a particular
2732 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002733 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002734 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2735 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002736
2737 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002738 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002739 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002740 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002741
2742 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002743 bool isCanonical =
Douglas Gregorcd780372013-01-17 23:36:45 +00002744 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002745 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002746 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002747 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002748 isCanonical = false;
2749
Roman Divacky65b88cd2011-03-01 17:40:53 +00002750 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2751 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2752 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002753
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002754 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002755 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002756 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002757 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002758 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002759 CanonicalArgs.reserve(NumArgs);
2760 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002761 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002762
John McCalldb40c7f2010-12-14 08:05:40 +00002763 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002764 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002765 CanonicalEPI.ExceptionSpecType = EST_None;
2766 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002767 CanonicalEPI.ExtInfo
2768 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2769
Douglas Gregorcd780372013-01-17 23:36:45 +00002770 // Result types do not have ARC lifetime qualifiers.
2771 QualType CanResultTy = getCanonicalType(ResultTy);
2772 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2773 Qualifiers Qs = CanResultTy.getQualifiers();
2774 Qs.removeObjCLifetime();
2775 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2776 }
2777
Jordan Rose5c382722013-03-08 21:51:21 +00002778 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002779
Chris Lattnerfd4de792007-01-27 01:15:32 +00002780 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002781 FunctionProtoType *NewIP =
2782 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002783 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002784 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002785
John McCall31168b02011-06-15 23:02:42 +00002786 // FunctionProtoType objects are allocated with extra bytes after
2787 // them for three variable size arrays at the end:
2788 // - parameter types
2789 // - exception types
2790 // - consumed-arguments flags
2791 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002792 // expression, or information used to resolve the exception
2793 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002794 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002795 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002796 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002797 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002798 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002799 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002800 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002801 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002802 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2803 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002804 }
John McCall31168b02011-06-15 23:02:42 +00002805 if (EPI.ConsumedArguments)
2806 Size += NumArgs * sizeof(bool);
2807
John McCalldb40c7f2010-12-14 08:05:40 +00002808 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002809 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2810 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Jordan Rose5c382722013-03-08 21:51:21 +00002811 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002812 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002813 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002814 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002815}
Chris Lattneref51c202006-11-10 07:17:23 +00002816
John McCalle78aac42010-03-10 03:28:59 +00002817#ifndef NDEBUG
2818static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2819 if (!isa<CXXRecordDecl>(D)) return false;
2820 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2821 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2822 return true;
2823 if (RD->getDescribedClassTemplate() &&
2824 !isa<ClassTemplateSpecializationDecl>(RD))
2825 return true;
2826 return false;
2827}
2828#endif
2829
2830/// getInjectedClassNameType - Return the unique reference to the
2831/// injected class name type for the specified templated declaration.
2832QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002833 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002834 assert(NeedsInjectedClassNameType(Decl));
2835 if (Decl->TypeForDecl) {
2836 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002837 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002838 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2839 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2840 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2841 } else {
John McCall424cec92011-01-19 06:33:43 +00002842 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002843 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002844 Decl->TypeForDecl = newType;
2845 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002846 }
2847 return QualType(Decl->TypeForDecl, 0);
2848}
2849
Douglas Gregor83a586e2008-04-13 21:07:44 +00002850/// getTypeDeclType - Return the unique reference to the type for the
2851/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002852QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002853 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002854 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002855
Richard Smithdda56e42011-04-15 14:24:37 +00002856 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002857 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002858
John McCall96f0b5f2010-03-10 06:48:02 +00002859 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2860 "Template type parameter types are always available.");
2861
John McCall81e38502010-02-16 03:57:14 +00002862 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002863 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002864 "struct/union has previous declaration");
2865 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002866 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002867 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002868 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002869 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002870 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002871 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002872 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002873 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2874 Decl->TypeForDecl = newType;
2875 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002876 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002877 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002878
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002879 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002880}
2881
Chris Lattner32d920b2007-01-26 02:01:53 +00002882/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002883/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002884QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002885ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2886 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002887 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002888
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002889 if (Canonical.isNull())
2890 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002891 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002892 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002893 Decl->TypeForDecl = newType;
2894 Types.push_back(newType);
2895 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002896}
2897
Jay Foad39c79802011-01-12 09:06:06 +00002898QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002899 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2900
Douglas Gregorec9fd132012-01-14 16:38:05 +00002901 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002902 if (PrevDecl->TypeForDecl)
2903 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2904
John McCall424cec92011-01-19 06:33:43 +00002905 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2906 Decl->TypeForDecl = newType;
2907 Types.push_back(newType);
2908 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002909}
2910
Jay Foad39c79802011-01-12 09:06:06 +00002911QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002912 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2913
Douglas Gregorec9fd132012-01-14 16:38:05 +00002914 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002915 if (PrevDecl->TypeForDecl)
2916 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2917
John McCall424cec92011-01-19 06:33:43 +00002918 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2919 Decl->TypeForDecl = newType;
2920 Types.push_back(newType);
2921 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002922}
2923
John McCall81904512011-01-06 01:58:22 +00002924QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2925 QualType modifiedType,
2926 QualType equivalentType) {
2927 llvm::FoldingSetNodeID id;
2928 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2929
2930 void *insertPos = 0;
2931 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2932 if (type) return QualType(type, 0);
2933
2934 QualType canon = getCanonicalType(equivalentType);
2935 type = new (*this, TypeAlignment)
2936 AttributedType(canon, attrKind, modifiedType, equivalentType);
2937
2938 Types.push_back(type);
2939 AttributedTypes.InsertNode(type, insertPos);
2940
2941 return QualType(type, 0);
2942}
2943
2944
John McCallcebee162009-10-18 09:09:24 +00002945/// \brief Retrieve a substitution-result type.
2946QualType
2947ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002948 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002949 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002950 && "replacement types must always be canonical");
2951
2952 llvm::FoldingSetNodeID ID;
2953 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2954 void *InsertPos = 0;
2955 SubstTemplateTypeParmType *SubstParm
2956 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2957
2958 if (!SubstParm) {
2959 SubstParm = new (*this, TypeAlignment)
2960 SubstTemplateTypeParmType(Parm, Replacement);
2961 Types.push_back(SubstParm);
2962 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2963 }
2964
2965 return QualType(SubstParm, 0);
2966}
2967
Douglas Gregorada4b792011-01-14 02:55:32 +00002968/// \brief Retrieve a
2969QualType ASTContext::getSubstTemplateTypeParmPackType(
2970 const TemplateTypeParmType *Parm,
2971 const TemplateArgument &ArgPack) {
2972#ifndef NDEBUG
2973 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2974 PEnd = ArgPack.pack_end();
2975 P != PEnd; ++P) {
2976 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2977 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2978 }
2979#endif
2980
2981 llvm::FoldingSetNodeID ID;
2982 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2983 void *InsertPos = 0;
2984 if (SubstTemplateTypeParmPackType *SubstParm
2985 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2986 return QualType(SubstParm, 0);
2987
2988 QualType Canon;
2989 if (!Parm->isCanonicalUnqualified()) {
2990 Canon = getCanonicalType(QualType(Parm, 0));
2991 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2992 ArgPack);
2993 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2994 }
2995
2996 SubstTemplateTypeParmPackType *SubstParm
2997 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2998 ArgPack);
2999 Types.push_back(SubstParm);
3000 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3001 return QualType(SubstParm, 0);
3002}
3003
Douglas Gregoreff93e02009-02-05 23:33:38 +00003004/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003005/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003006/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003007QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003008 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003009 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003010 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003011 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003012 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003013 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003014 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3015
3016 if (TypeParm)
3017 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003018
Chandler Carruth08836322011-05-01 00:51:33 +00003019 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003020 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003021 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003022
3023 TemplateTypeParmType *TypeCheck
3024 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3025 assert(!TypeCheck && "Template type parameter canonical type broken");
3026 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003027 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003028 TypeParm = new (*this, TypeAlignment)
3029 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003030
3031 Types.push_back(TypeParm);
3032 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3033
3034 return QualType(TypeParm, 0);
3035}
3036
John McCalle78aac42010-03-10 03:28:59 +00003037TypeSourceInfo *
3038ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3039 SourceLocation NameLoc,
3040 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003041 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003042 assert(!Name.getAsDependentTemplateName() &&
3043 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003044 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003045
3046 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003047 TemplateSpecializationTypeLoc TL =
3048 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003049 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003050 TL.setTemplateNameLoc(NameLoc);
3051 TL.setLAngleLoc(Args.getLAngleLoc());
3052 TL.setRAngleLoc(Args.getRAngleLoc());
3053 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3054 TL.setArgLocInfo(i, Args[i].getLocInfo());
3055 return DI;
3056}
3057
Mike Stump11289f42009-09-09 15:08:12 +00003058QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003059ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003060 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003061 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003062 assert(!Template.getAsDependentTemplateName() &&
3063 "No dependent template names here!");
3064
John McCall6b51f282009-11-23 01:53:49 +00003065 unsigned NumArgs = Args.size();
3066
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003067 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003068 ArgVec.reserve(NumArgs);
3069 for (unsigned i = 0; i != NumArgs; ++i)
3070 ArgVec.push_back(Args[i].getArgument());
3071
John McCall2408e322010-04-27 00:57:59 +00003072 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003073 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003074}
3075
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003076#ifndef NDEBUG
3077static bool hasAnyPackExpansions(const TemplateArgument *Args,
3078 unsigned NumArgs) {
3079 for (unsigned I = 0; I != NumArgs; ++I)
3080 if (Args[I].isPackExpansion())
3081 return true;
3082
3083 return true;
3084}
3085#endif
3086
John McCall0ad16662009-10-29 08:12:44 +00003087QualType
3088ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003089 const TemplateArgument *Args,
3090 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003091 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003092 assert(!Template.getAsDependentTemplateName() &&
3093 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003094 // Look through qualified template names.
3095 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3096 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003097
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003098 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003099 Template.getAsTemplateDecl() &&
3100 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003101 QualType CanonType;
3102 if (!Underlying.isNull())
3103 CanonType = getCanonicalType(Underlying);
3104 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003105 // We can get here with an alias template when the specialization contains
3106 // a pack expansion that does not match up with a parameter pack.
3107 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3108 "Caller must compute aliased type");
3109 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003110 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3111 NumArgs);
3112 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003113
Douglas Gregora8e02e72009-07-28 23:00:59 +00003114 // Allocate the (non-canonical) template specialization type, but don't
3115 // try to unique it: these types typically have location information that
3116 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003117 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3118 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003119 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003120 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003121 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003122 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3123 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003124
Douglas Gregor8bf42052009-02-09 18:46:07 +00003125 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003126 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003127}
3128
Mike Stump11289f42009-09-09 15:08:12 +00003129QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003130ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3131 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003132 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003133 assert(!Template.getAsDependentTemplateName() &&
3134 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003135
Douglas Gregore29139c2011-03-03 17:04:51 +00003136 // Look through qualified template names.
3137 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3138 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003139
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003140 // Build the canonical template specialization type.
3141 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003142 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003143 CanonArgs.reserve(NumArgs);
3144 for (unsigned I = 0; I != NumArgs; ++I)
3145 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3146
3147 // Determine whether this canonical template specialization type already
3148 // exists.
3149 llvm::FoldingSetNodeID ID;
3150 TemplateSpecializationType::Profile(ID, CanonTemplate,
3151 CanonArgs.data(), NumArgs, *this);
3152
3153 void *InsertPos = 0;
3154 TemplateSpecializationType *Spec
3155 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3156
3157 if (!Spec) {
3158 // Allocate a new canonical template specialization type.
3159 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3160 sizeof(TemplateArgument) * NumArgs),
3161 TypeAlignment);
3162 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3163 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003164 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003165 Types.push_back(Spec);
3166 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3167 }
3168
3169 assert(Spec->isDependentType() &&
3170 "Non-dependent template-id type must have a canonical type");
3171 return QualType(Spec, 0);
3172}
3173
3174QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003175ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3176 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003177 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003178 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003179 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003180
3181 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003182 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003183 if (T)
3184 return QualType(T, 0);
3185
Douglas Gregorc42075a2010-02-04 18:10:26 +00003186 QualType Canon = NamedType;
3187 if (!Canon.isCanonical()) {
3188 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003189 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3190 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003191 (void)CheckT;
3192 }
3193
Abramo Bagnara6150c882010-05-11 21:36:43 +00003194 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003195 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003196 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003197 return QualType(T, 0);
3198}
3199
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003200QualType
Jay Foad39c79802011-01-12 09:06:06 +00003201ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003202 llvm::FoldingSetNodeID ID;
3203 ParenType::Profile(ID, InnerType);
3204
3205 void *InsertPos = 0;
3206 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3207 if (T)
3208 return QualType(T, 0);
3209
3210 QualType Canon = InnerType;
3211 if (!Canon.isCanonical()) {
3212 Canon = getCanonicalType(InnerType);
3213 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3214 assert(!CheckT && "Paren canonical type broken");
3215 (void)CheckT;
3216 }
3217
3218 T = new (*this) ParenType(InnerType, Canon);
3219 Types.push_back(T);
3220 ParenTypes.InsertNode(T, InsertPos);
3221 return QualType(T, 0);
3222}
3223
Douglas Gregor02085352010-03-31 20:19:30 +00003224QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3225 NestedNameSpecifier *NNS,
3226 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003227 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003228 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3229
3230 if (Canon.isNull()) {
3231 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003232 ElaboratedTypeKeyword CanonKeyword = Keyword;
3233 if (Keyword == ETK_None)
3234 CanonKeyword = ETK_Typename;
3235
3236 if (CanonNNS != NNS || CanonKeyword != Keyword)
3237 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003238 }
3239
3240 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003241 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003242
3243 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003244 DependentNameType *T
3245 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003246 if (T)
3247 return QualType(T, 0);
3248
Douglas Gregor02085352010-03-31 20:19:30 +00003249 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003250 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003251 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003252 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003253}
3254
Mike Stump11289f42009-09-09 15:08:12 +00003255QualType
John McCallc392f372010-06-11 00:33:02 +00003256ASTContext::getDependentTemplateSpecializationType(
3257 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003258 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003259 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003260 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003261 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003262 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003263 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3264 ArgCopy.push_back(Args[I].getArgument());
3265 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3266 ArgCopy.size(),
3267 ArgCopy.data());
3268}
3269
3270QualType
3271ASTContext::getDependentTemplateSpecializationType(
3272 ElaboratedTypeKeyword Keyword,
3273 NestedNameSpecifier *NNS,
3274 const IdentifierInfo *Name,
3275 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003276 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003277 assert((!NNS || NNS->isDependent()) &&
3278 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003279
Douglas Gregorc42075a2010-02-04 18:10:26 +00003280 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003281 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3282 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003283
3284 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00003285 DependentTemplateSpecializationType *T
3286 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003287 if (T)
3288 return QualType(T, 0);
3289
John McCallc392f372010-06-11 00:33:02 +00003290 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003291
John McCallc392f372010-06-11 00:33:02 +00003292 ElaboratedTypeKeyword CanonKeyword = Keyword;
3293 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3294
3295 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003296 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003297 for (unsigned I = 0; I != NumArgs; ++I) {
3298 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3299 if (!CanonArgs[I].structurallyEquals(Args[I]))
3300 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003301 }
3302
John McCallc392f372010-06-11 00:33:02 +00003303 QualType Canon;
3304 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3305 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3306 Name, NumArgs,
3307 CanonArgs.data());
3308
3309 // Find the insert position again.
3310 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3311 }
3312
3313 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3314 sizeof(TemplateArgument) * NumArgs),
3315 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003316 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003317 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003318 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003319 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003320 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003321}
3322
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003323QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003324 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003325 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003326 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003327
3328 assert(Pattern->containsUnexpandedParameterPack() &&
3329 "Pack expansions must expand one or more parameter packs");
3330 void *InsertPos = 0;
3331 PackExpansionType *T
3332 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3333 if (T)
3334 return QualType(T, 0);
3335
3336 QualType Canon;
3337 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003338 Canon = getCanonicalType(Pattern);
3339 // The canonical type might not contain an unexpanded parameter pack, if it
3340 // contains an alias template specialization which ignores one of its
3341 // parameters.
3342 if (Canon->containsUnexpandedParameterPack()) {
3343 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003344
Richard Smith68eea502012-07-16 00:20:35 +00003345 // Find the insert position again, in case we inserted an element into
3346 // PackExpansionTypes and invalidated our insert position.
3347 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3348 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003349 }
3350
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003351 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003352 Types.push_back(T);
3353 PackExpansionTypes.InsertNode(T, InsertPos);
3354 return QualType(T, 0);
3355}
3356
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003357/// CmpProtocolNames - Comparison predicate for sorting protocols
3358/// alphabetically.
3359static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3360 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003361 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003362}
3363
John McCall8b07ec22010-05-15 11:32:37 +00003364static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003365 unsigned NumProtocols) {
3366 if (NumProtocols == 0) return true;
3367
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003368 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3369 return false;
3370
John McCallfc93cf92009-10-22 22:37:11 +00003371 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003372 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3373 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003374 return false;
3375 return true;
3376}
3377
3378static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003379 unsigned &NumProtocols) {
3380 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003381
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003382 // Sort protocols, keyed by name.
3383 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3384
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003385 // Canonicalize.
3386 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3387 Protocols[I] = Protocols[I]->getCanonicalDecl();
3388
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003389 // Remove duplicates.
3390 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3391 NumProtocols = ProtocolsEnd-Protocols;
3392}
3393
John McCall8b07ec22010-05-15 11:32:37 +00003394QualType ASTContext::getObjCObjectType(QualType BaseType,
3395 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003396 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003397 // If the base type is an interface and there aren't any protocols
3398 // to add, then the interface type will do just fine.
3399 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3400 return BaseType;
3401
3402 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003403 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003404 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003405 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003406 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3407 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003408
John McCall8b07ec22010-05-15 11:32:37 +00003409 // Build the canonical type, which has the canonical base type and
3410 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003411 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003412 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3413 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3414 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003415 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003416 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003417 unsigned UniqueCount = NumProtocols;
3418
John McCallfc93cf92009-10-22 22:37:11 +00003419 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003420 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3421 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003422 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003423 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3424 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003425 }
3426
3427 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003428 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3429 }
3430
3431 unsigned Size = sizeof(ObjCObjectTypeImpl);
3432 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3433 void *Mem = Allocate(Size, TypeAlignment);
3434 ObjCObjectTypeImpl *T =
3435 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3436
3437 Types.push_back(T);
3438 ObjCObjectTypes.InsertNode(T, InsertPos);
3439 return QualType(T, 0);
3440}
3441
3442/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3443/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003444QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003445 llvm::FoldingSetNodeID ID;
3446 ObjCObjectPointerType::Profile(ID, ObjectT);
3447
3448 void *InsertPos = 0;
3449 if (ObjCObjectPointerType *QT =
3450 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3451 return QualType(QT, 0);
3452
3453 // Find the canonical object type.
3454 QualType Canonical;
3455 if (!ObjectT.isCanonical()) {
3456 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3457
3458 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003459 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3460 }
3461
Douglas Gregorf85bee62010-02-08 22:59:26 +00003462 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003463 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3464 ObjCObjectPointerType *QType =
3465 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003466
Steve Narofffb4330f2009-06-17 22:40:22 +00003467 Types.push_back(QType);
3468 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003469 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003470}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003471
Douglas Gregor1c283312010-08-11 12:19:30 +00003472/// getObjCInterfaceType - Return the unique reference to the type for the
3473/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003474QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3475 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003476 if (Decl->TypeForDecl)
3477 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003478
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003479 if (PrevDecl) {
3480 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3481 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3482 return QualType(PrevDecl->TypeForDecl, 0);
3483 }
3484
Douglas Gregor7671e532011-12-16 16:34:57 +00003485 // Prefer the definition, if there is one.
3486 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3487 Decl = Def;
3488
Douglas Gregor1c283312010-08-11 12:19:30 +00003489 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3490 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3491 Decl->TypeForDecl = T;
3492 Types.push_back(T);
3493 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003494}
3495
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003496/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3497/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003498/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003499/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003500/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003501QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003502 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003503 if (tofExpr->isTypeDependent()) {
3504 llvm::FoldingSetNodeID ID;
3505 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003506
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003507 void *InsertPos = 0;
3508 DependentTypeOfExprType *Canon
3509 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3510 if (Canon) {
3511 // We already have a "canonical" version of an identical, dependent
3512 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003513 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003514 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003515 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003516 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003517 Canon
3518 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003519 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3520 toe = Canon;
3521 }
3522 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003523 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003524 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003525 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003526 Types.push_back(toe);
3527 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003528}
3529
Steve Naroffa773cd52007-08-01 18:02:17 +00003530/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3531/// TypeOfType AST's. The only motivation to unique these nodes would be
3532/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003533/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003534/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003535QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003536 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003537 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003538 Types.push_back(tot);
3539 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003540}
3541
Anders Carlssonad6bd352009-06-24 21:24:56 +00003542
Anders Carlsson81df7b82009-06-24 19:06:50 +00003543/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3544/// DecltypeType AST's. The only motivation to unique these nodes would be
3545/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003546/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003547/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003548QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003549 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003550
3551 // C++0x [temp.type]p2:
3552 // If an expression e involves a template parameter, decltype(e) denotes a
3553 // unique dependent type. Two such decltype-specifiers refer to the same
3554 // type only if their expressions are equivalent (14.5.6.1).
3555 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003556 llvm::FoldingSetNodeID ID;
3557 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003558
Douglas Gregora21f6c32009-07-30 23:36:40 +00003559 void *InsertPos = 0;
3560 DependentDecltypeType *Canon
3561 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3562 if (Canon) {
3563 // We already have a "canonical" version of an equivalent, dependent
3564 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003565 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003566 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003567 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003568 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003569 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003570 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3571 dt = Canon;
3572 }
3573 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003574 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3575 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003576 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003577 Types.push_back(dt);
3578 return QualType(dt, 0);
3579}
3580
Alexis Hunte852b102011-05-24 22:41:36 +00003581/// getUnaryTransformationType - We don't unique these, since the memory
3582/// savings are minimal and these are rare.
3583QualType ASTContext::getUnaryTransformType(QualType BaseType,
3584 QualType UnderlyingType,
3585 UnaryTransformType::UTTKind Kind)
3586 const {
3587 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003588 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3589 Kind,
3590 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003591 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003592 Types.push_back(Ty);
3593 return QualType(Ty, 0);
3594}
3595
Richard Smith2a7d4812013-05-04 07:00:32 +00003596/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3597/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3598/// canonical deduced-but-dependent 'auto' type.
3599QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Richard Smith27d807c2013-04-30 13:56:41 +00003600 bool IsDependent) const {
Richard Smith2a7d4812013-05-04 07:00:32 +00003601 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
3602 return getAutoDeductType();
3603
3604 // Look in the folding set for an existing type.
Richard Smithb2bc2e62011-02-21 20:05:19 +00003605 void *InsertPos = 0;
Richard Smith2a7d4812013-05-04 07:00:32 +00003606 llvm::FoldingSetNodeID ID;
3607 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
3608 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3609 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003610
Richard Smith74aeef52013-04-26 16:15:35 +00003611 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003612 IsDecltypeAuto,
3613 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003614 Types.push_back(AT);
3615 if (InsertPos)
3616 AutoTypes.InsertNode(AT, InsertPos);
3617 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003618}
3619
Eli Friedman0dfb8892011-10-06 23:00:33 +00003620/// getAtomicType - Return the uniqued reference to the atomic type for
3621/// the given value type.
3622QualType ASTContext::getAtomicType(QualType T) const {
3623 // Unique pointers, to guarantee there is only one pointer of a particular
3624 // structure.
3625 llvm::FoldingSetNodeID ID;
3626 AtomicType::Profile(ID, T);
3627
3628 void *InsertPos = 0;
3629 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3630 return QualType(AT, 0);
3631
3632 // If the atomic value type isn't canonical, this won't be a canonical type
3633 // either, so fill in the canonical type field.
3634 QualType Canonical;
3635 if (!T.isCanonical()) {
3636 Canonical = getAtomicType(getCanonicalType(T));
3637
3638 // Get the new insert position for the node we care about.
3639 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3640 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3641 }
3642 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3643 Types.push_back(New);
3644 AtomicTypes.InsertNode(New, InsertPos);
3645 return QualType(New, 0);
3646}
3647
Richard Smith02e85f32011-04-14 22:09:26 +00003648/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3649QualType ASTContext::getAutoDeductType() const {
3650 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00003651 AutoDeductTy = QualType(
3652 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
3653 /*dependent*/false),
3654 0);
Richard Smith02e85f32011-04-14 22:09:26 +00003655 return AutoDeductTy;
3656}
3657
3658/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3659QualType ASTContext::getAutoRRefDeductType() const {
3660 if (AutoRRefDeductTy.isNull())
3661 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3662 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3663 return AutoRRefDeductTy;
3664}
3665
Chris Lattnerfb072462007-01-23 05:45:31 +00003666/// getTagDeclType - Return the unique reference to the type for the
3667/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003668QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003669 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003670 // FIXME: What is the design on getTagDeclType when it requires casting
3671 // away const? mutable?
3672 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003673}
3674
Mike Stump11289f42009-09-09 15:08:12 +00003675/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3676/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3677/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003678CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003679 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003680}
Chris Lattnerfb072462007-01-23 05:45:31 +00003681
Hans Wennborg27541db2011-10-27 08:29:09 +00003682/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3683CanQualType ASTContext::getIntMaxType() const {
3684 return getFromTargetType(Target->getIntMaxType());
3685}
3686
3687/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3688CanQualType ASTContext::getUIntMaxType() const {
3689 return getFromTargetType(Target->getUIntMaxType());
3690}
3691
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003692/// getSignedWCharType - Return the type of "signed wchar_t".
3693/// Used when in C++, as a GCC extension.
3694QualType ASTContext::getSignedWCharType() const {
3695 // FIXME: derive from "Target" ?
3696 return WCharTy;
3697}
3698
3699/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3700/// Used when in C++, as a GCC extension.
3701QualType ASTContext::getUnsignedWCharType() const {
3702 // FIXME: derive from "Target" ?
3703 return UnsignedIntTy;
3704}
3705
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00003706QualType ASTContext::getIntPtrType() const {
3707 return getFromTargetType(Target->getIntPtrType());
3708}
3709
3710QualType ASTContext::getUIntPtrType() const {
3711 return getCorrespondingUnsignedType(getIntPtrType());
3712}
3713
Hans Wennborg27541db2011-10-27 08:29:09 +00003714/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003715/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3716QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003717 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003718}
3719
Eli Friedman4e91899e2012-11-27 02:58:24 +00003720/// \brief Return the unique type for "pid_t" defined in
3721/// <sys/types.h>. We need this to compute the correct type for vfork().
3722QualType ASTContext::getProcessIDType() const {
3723 return getFromTargetType(Target->getProcessIDType());
3724}
3725
Chris Lattnera21ad802008-04-02 05:18:44 +00003726//===----------------------------------------------------------------------===//
3727// Type Operators
3728//===----------------------------------------------------------------------===//
3729
Jay Foad39c79802011-01-12 09:06:06 +00003730CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003731 // Push qualifiers into arrays, and then discard any remaining
3732 // qualifiers.
3733 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003734 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003735 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003736 QualType Result;
3737 if (isa<ArrayType>(Ty)) {
3738 Result = getArrayDecayedType(QualType(Ty,0));
3739 } else if (isa<FunctionType>(Ty)) {
3740 Result = getPointerType(QualType(Ty, 0));
3741 } else {
3742 Result = QualType(Ty, 0);
3743 }
3744
3745 return CanQualType::CreateUnsafe(Result);
3746}
3747
John McCall6c9dd522011-01-18 07:41:22 +00003748QualType ASTContext::getUnqualifiedArrayType(QualType type,
3749 Qualifiers &quals) {
3750 SplitQualType splitType = type.getSplitUnqualifiedType();
3751
3752 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3753 // the unqualified desugared type and then drops it on the floor.
3754 // We then have to strip that sugar back off with
3755 // getUnqualifiedDesugaredType(), which is silly.
3756 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003757 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003758
3759 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003760 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003761 quals = splitType.Quals;
3762 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003763 }
3764
John McCall6c9dd522011-01-18 07:41:22 +00003765 // Otherwise, recurse on the array's element type.
3766 QualType elementType = AT->getElementType();
3767 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3768
3769 // If that didn't change the element type, AT has no qualifiers, so we
3770 // can just use the results in splitType.
3771 if (elementType == unqualElementType) {
3772 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003773 quals = splitType.Quals;
3774 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003775 }
3776
3777 // Otherwise, add in the qualifiers from the outermost type, then
3778 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003779 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003780
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003781 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003782 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003783 CAT->getSizeModifier(), 0);
3784 }
3785
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003786 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003787 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003788 }
3789
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003790 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003791 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003792 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003793 VAT->getSizeModifier(),
3794 VAT->getIndexTypeCVRQualifiers(),
3795 VAT->getBracketsRange());
3796 }
3797
3798 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003799 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003800 DSAT->getSizeModifier(), 0,
3801 SourceRange());
3802}
3803
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003804/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3805/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3806/// they point to and return true. If T1 and T2 aren't pointer types
3807/// or pointer-to-member types, or if they are not similar at this
3808/// level, returns false and leaves T1 and T2 unchanged. Top-level
3809/// qualifiers on T1 and T2 are ignored. This function will typically
3810/// be called in a loop that successively "unwraps" pointer and
3811/// pointer-to-member types to compare them at each level.
3812bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3813 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3814 *T2PtrType = T2->getAs<PointerType>();
3815 if (T1PtrType && T2PtrType) {
3816 T1 = T1PtrType->getPointeeType();
3817 T2 = T2PtrType->getPointeeType();
3818 return true;
3819 }
3820
3821 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3822 *T2MPType = T2->getAs<MemberPointerType>();
3823 if (T1MPType && T2MPType &&
3824 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3825 QualType(T2MPType->getClass(), 0))) {
3826 T1 = T1MPType->getPointeeType();
3827 T2 = T2MPType->getPointeeType();
3828 return true;
3829 }
3830
David Blaikiebbafb8a2012-03-11 07:00:24 +00003831 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003832 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3833 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3834 if (T1OPType && T2OPType) {
3835 T1 = T1OPType->getPointeeType();
3836 T2 = T2OPType->getPointeeType();
3837 return true;
3838 }
3839 }
3840
3841 // FIXME: Block pointers, too?
3842
3843 return false;
3844}
3845
Jay Foad39c79802011-01-12 09:06:06 +00003846DeclarationNameInfo
3847ASTContext::getNameForTemplate(TemplateName Name,
3848 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003849 switch (Name.getKind()) {
3850 case TemplateName::QualifiedTemplate:
3851 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003852 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003853 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3854 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003855
John McCalld9dfe3a2011-06-30 08:33:18 +00003856 case TemplateName::OverloadedTemplate: {
3857 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3858 // DNInfo work in progress: CHECKME: what about DNLoc?
3859 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3860 }
3861
3862 case TemplateName::DependentTemplate: {
3863 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003864 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003865 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003866 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3867 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003868 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003869 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3870 // DNInfo work in progress: FIXME: source locations?
3871 DeclarationNameLoc DNLoc;
3872 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3873 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3874 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003875 }
3876 }
3877
John McCalld9dfe3a2011-06-30 08:33:18 +00003878 case TemplateName::SubstTemplateTemplateParm: {
3879 SubstTemplateTemplateParmStorage *subst
3880 = Name.getAsSubstTemplateTemplateParm();
3881 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3882 NameLoc);
3883 }
3884
3885 case TemplateName::SubstTemplateTemplateParmPack: {
3886 SubstTemplateTemplateParmPackStorage *subst
3887 = Name.getAsSubstTemplateTemplateParmPack();
3888 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3889 NameLoc);
3890 }
3891 }
3892
3893 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003894}
3895
Jay Foad39c79802011-01-12 09:06:06 +00003896TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003897 switch (Name.getKind()) {
3898 case TemplateName::QualifiedTemplate:
3899 case TemplateName::Template: {
3900 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003901 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003902 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003903 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3904
3905 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003906 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003907 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003908
John McCalld9dfe3a2011-06-30 08:33:18 +00003909 case TemplateName::OverloadedTemplate:
3910 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003911
John McCalld9dfe3a2011-06-30 08:33:18 +00003912 case TemplateName::DependentTemplate: {
3913 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3914 assert(DTN && "Non-dependent template names must refer to template decls.");
3915 return DTN->CanonicalTemplateName;
3916 }
3917
3918 case TemplateName::SubstTemplateTemplateParm: {
3919 SubstTemplateTemplateParmStorage *subst
3920 = Name.getAsSubstTemplateTemplateParm();
3921 return getCanonicalTemplateName(subst->getReplacement());
3922 }
3923
3924 case TemplateName::SubstTemplateTemplateParmPack: {
3925 SubstTemplateTemplateParmPackStorage *subst
3926 = Name.getAsSubstTemplateTemplateParmPack();
3927 TemplateTemplateParmDecl *canonParameter
3928 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3929 TemplateArgument canonArgPack
3930 = getCanonicalTemplateArgument(subst->getArgumentPack());
3931 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3932 }
3933 }
3934
3935 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003936}
3937
Douglas Gregoradee3e32009-11-11 23:06:43 +00003938bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3939 X = getCanonicalTemplateName(X);
3940 Y = getCanonicalTemplateName(Y);
3941 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3942}
3943
Mike Stump11289f42009-09-09 15:08:12 +00003944TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003945ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003946 switch (Arg.getKind()) {
3947 case TemplateArgument::Null:
3948 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003949
Douglas Gregora8e02e72009-07-28 23:00:59 +00003950 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003951 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003952
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003953 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00003954 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
3955 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003956 }
Mike Stump11289f42009-09-09 15:08:12 +00003957
Eli Friedmanb826a002012-09-26 02:36:12 +00003958 case TemplateArgument::NullPtr:
3959 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
3960 /*isNullPtr*/true);
3961
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003962 case TemplateArgument::Template:
3963 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003964
3965 case TemplateArgument::TemplateExpansion:
3966 return TemplateArgument(getCanonicalTemplateName(
3967 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003968 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003969
Douglas Gregora8e02e72009-07-28 23:00:59 +00003970 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003971 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003972
Douglas Gregora8e02e72009-07-28 23:00:59 +00003973 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003974 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003975
Douglas Gregora8e02e72009-07-28 23:00:59 +00003976 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003977 if (Arg.pack_size() == 0)
3978 return Arg;
3979
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003980 TemplateArgument *CanonArgs
3981 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003982 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003983 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003984 AEnd = Arg.pack_end();
3985 A != AEnd; (void)++A, ++Idx)
3986 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003987
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003988 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003989 }
3990 }
3991
3992 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003993 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003994}
3995
Douglas Gregor333489b2009-03-27 23:10:48 +00003996NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003997ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003998 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003999 return 0;
4000
4001 switch (NNS->getKind()) {
4002 case NestedNameSpecifier::Identifier:
4003 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004004 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004005 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4006 NNS->getAsIdentifier());
4007
4008 case NestedNameSpecifier::Namespace:
4009 // A namespace is canonical; build a nested-name-specifier with
4010 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004011 return NestedNameSpecifier::Create(*this, 0,
4012 NNS->getAsNamespace()->getOriginalNamespace());
4013
4014 case NestedNameSpecifier::NamespaceAlias:
4015 // A namespace is canonical; build a nested-name-specifier with
4016 // this namespace and no prefix.
4017 return NestedNameSpecifier::Create(*this, 0,
4018 NNS->getAsNamespaceAlias()->getNamespace()
4019 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004020
4021 case NestedNameSpecifier::TypeSpec:
4022 case NestedNameSpecifier::TypeSpecWithTemplate: {
4023 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004024
4025 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4026 // break it apart into its prefix and identifier, then reconsititute those
4027 // as the canonical nested-name-specifier. This is required to canonicalize
4028 // a dependent nested-name-specifier involving typedefs of dependent-name
4029 // types, e.g.,
4030 // typedef typename T::type T1;
4031 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004032 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4033 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004034 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004035
Eli Friedman5358a0a2012-03-03 04:09:56 +00004036 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4037 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4038 // first place?
John McCall33ddac02011-01-19 10:06:00 +00004039 return NestedNameSpecifier::Create(*this, 0, false,
4040 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004041 }
4042
4043 case NestedNameSpecifier::Global:
4044 // The global specifier is canonical and unique.
4045 return NNS;
4046 }
4047
David Blaikie8a40f702012-01-17 06:56:22 +00004048 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004049}
4050
Chris Lattner7adf0762008-08-04 07:31:14 +00004051
Jay Foad39c79802011-01-12 09:06:06 +00004052const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004053 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004054 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004055 // Handle the common positive case fast.
4056 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4057 return AT;
4058 }
Mike Stump11289f42009-09-09 15:08:12 +00004059
John McCall8ccfcb52009-09-24 19:53:00 +00004060 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004061 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00004062 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004063
John McCall8ccfcb52009-09-24 19:53:00 +00004064 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004065 // implements C99 6.7.3p8: "If the specification of an array type includes
4066 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004067
Chris Lattner7adf0762008-08-04 07:31:14 +00004068 // If we get here, we either have type qualifiers on the type, or we have
4069 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004070 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004071
John McCall33ddac02011-01-19 10:06:00 +00004072 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004073 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004074
Chris Lattner7adf0762008-08-04 07:31:14 +00004075 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004076 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00004077 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004078 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004079
Chris Lattner7adf0762008-08-04 07:31:14 +00004080 // Otherwise, we have an array and we have qualifiers on it. Push the
4081 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004082 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004083
Chris Lattner7adf0762008-08-04 07:31:14 +00004084 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4085 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4086 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004087 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004088 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4089 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4090 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004091 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004092
Mike Stump11289f42009-09-09 15:08:12 +00004093 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004094 = dyn_cast<DependentSizedArrayType>(ATy))
4095 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004096 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004097 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004098 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004099 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004100 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004101
Chris Lattner7adf0762008-08-04 07:31:14 +00004102 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004103 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004104 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004105 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004106 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004107 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004108}
4109
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004110QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004111 // C99 6.7.5.3p7:
4112 // A declaration of a parameter as "array of type" shall be
4113 // adjusted to "qualified pointer to type", where the type
4114 // qualifiers (if any) are those specified within the [ and ] of
4115 // the array type derivation.
4116 if (T->isArrayType())
4117 return getArrayDecayedType(T);
4118
4119 // C99 6.7.5.3p8:
4120 // A declaration of a parameter as "function returning type"
4121 // shall be adjusted to "pointer to function returning type", as
4122 // in 6.3.2.1.
4123 if (T->isFunctionType())
4124 return getPointerType(T);
4125
4126 return T;
4127}
4128
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004129QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004130 T = getVariableArrayDecayedType(T);
4131 T = getAdjustedParameterType(T);
4132 return T.getUnqualifiedType();
4133}
4134
Chris Lattnera21ad802008-04-02 05:18:44 +00004135/// getArrayDecayedType - Return the properly qualified result of decaying the
4136/// specified array type to a pointer. This operation is non-trivial when
4137/// handling typedefs etc. The canonical type of "T" must be an array type,
4138/// this returns a pointer to a properly qualified element of the array.
4139///
4140/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004141QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004142 // Get the element type with 'getAsArrayType' so that we don't lose any
4143 // typedefs in the element type of the array. This also handles propagation
4144 // of type qualifiers from the array type into the element type if present
4145 // (C99 6.7.3p8).
4146 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4147 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004148
Chris Lattner7adf0762008-08-04 07:31:14 +00004149 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004150
4151 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004152 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004153}
4154
John McCall33ddac02011-01-19 10:06:00 +00004155QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4156 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004157}
4158
John McCall33ddac02011-01-19 10:06:00 +00004159QualType ASTContext::getBaseElementType(QualType type) const {
4160 Qualifiers qs;
4161 while (true) {
4162 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004163 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004164 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004165
John McCall33ddac02011-01-19 10:06:00 +00004166 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004167 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004168 }
Mike Stump11289f42009-09-09 15:08:12 +00004169
John McCall33ddac02011-01-19 10:06:00 +00004170 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004171}
4172
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004173/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004174uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004175ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4176 uint64_t ElementCount = 1;
4177 do {
4178 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004179 CA = dyn_cast_or_null<ConstantArrayType>(
4180 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004181 } while (CA);
4182 return ElementCount;
4183}
4184
Steve Naroff0af91202007-04-27 21:51:21 +00004185/// getFloatingRank - Return a relative rank for floating point types.
4186/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004187static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004188 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004189 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004190
John McCall9dd450b2009-09-21 23:43:11 +00004191 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4192 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004193 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004194 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004195 case BuiltinType::Float: return FloatRank;
4196 case BuiltinType::Double: return DoubleRank;
4197 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004198 }
4199}
4200
Mike Stump11289f42009-09-09 15:08:12 +00004201/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4202/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004203/// 'typeDomain' is a real floating point or complex type.
4204/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004205QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4206 QualType Domain) const {
4207 FloatingRank EltRank = getFloatingRank(Size);
4208 if (Domain->isComplexType()) {
4209 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004210 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004211 case FloatRank: return FloatComplexTy;
4212 case DoubleRank: return DoubleComplexTy;
4213 case LongDoubleRank: return LongDoubleComplexTy;
4214 }
Steve Naroff0af91202007-04-27 21:51:21 +00004215 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004216
4217 assert(Domain->isRealFloatingType() && "Unknown domain!");
4218 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004219 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004220 case FloatRank: return FloatTy;
4221 case DoubleRank: return DoubleTy;
4222 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004223 }
David Blaikief47fa302012-01-17 02:30:50 +00004224 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004225}
4226
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004227/// getFloatingTypeOrder - Compare the rank of the two specified floating
4228/// point types, ignoring the domain of the type (i.e. 'double' ==
4229/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004230/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004231int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004232 FloatingRank LHSR = getFloatingRank(LHS);
4233 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004234
Chris Lattnerb90739d2008-04-06 23:38:49 +00004235 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004236 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004237 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004238 return 1;
4239 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004240}
4241
Chris Lattner76a00cf2008-04-06 22:59:24 +00004242/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4243/// routine will assert if passed a built-in type that isn't an integer or enum,
4244/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004245unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004246 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004247
Chris Lattner76a00cf2008-04-06 22:59:24 +00004248 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004249 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004250 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004251 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004252 case BuiltinType::Char_S:
4253 case BuiltinType::Char_U:
4254 case BuiltinType::SChar:
4255 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004256 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004257 case BuiltinType::Short:
4258 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004259 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004260 case BuiltinType::Int:
4261 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004262 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004263 case BuiltinType::Long:
4264 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004265 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004266 case BuiltinType::LongLong:
4267 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004268 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004269 case BuiltinType::Int128:
4270 case BuiltinType::UInt128:
4271 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004272 }
4273}
4274
Eli Friedman629ffb92009-08-20 04:21:42 +00004275/// \brief Whether this is a promotable bitfield reference according
4276/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4277///
4278/// \returns the type this bit-field will promote to, or NULL if no
4279/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004280QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004281 if (E->isTypeDependent() || E->isValueDependent())
4282 return QualType();
4283
John McCalld25db7e2013-05-06 21:39:12 +00004284 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004285 if (!Field)
4286 return QualType();
4287
4288 QualType FT = Field->getType();
4289
Richard Smithcaf33902011-10-10 18:28:20 +00004290 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004291 uint64_t IntSize = getTypeSize(IntTy);
4292 // GCC extension compatibility: if the bit-field size is less than or equal
4293 // to the size of int, it gets promoted no matter what its type is.
4294 // For instance, unsigned long bf : 4 gets promoted to signed int.
4295 if (BitWidth < IntSize)
4296 return IntTy;
4297
4298 if (BitWidth == IntSize)
4299 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4300
4301 // Types bigger than int are not subject to promotions, and therefore act
4302 // like the base type.
4303 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4304 // is ridiculous.
4305 return QualType();
4306}
4307
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004308/// getPromotedIntegerType - Returns the type that Promotable will
4309/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4310/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004311QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004312 assert(!Promotable.isNull());
4313 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004314 if (const EnumType *ET = Promotable->getAs<EnumType>())
4315 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004316
4317 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4318 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4319 // (3.9.1) can be converted to a prvalue of the first of the following
4320 // types that can represent all the values of its underlying type:
4321 // int, unsigned int, long int, unsigned long int, long long int, or
4322 // unsigned long long int [...]
4323 // FIXME: Is there some better way to compute this?
4324 if (BT->getKind() == BuiltinType::WChar_S ||
4325 BT->getKind() == BuiltinType::WChar_U ||
4326 BT->getKind() == BuiltinType::Char16 ||
4327 BT->getKind() == BuiltinType::Char32) {
4328 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4329 uint64_t FromSize = getTypeSize(BT);
4330 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4331 LongLongTy, UnsignedLongLongTy };
4332 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4333 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4334 if (FromSize < ToSize ||
4335 (FromSize == ToSize &&
4336 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4337 return PromoteTypes[Idx];
4338 }
4339 llvm_unreachable("char type should fit into long long");
4340 }
4341 }
4342
4343 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004344 if (Promotable->isSignedIntegerType())
4345 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004346 uint64_t PromotableSize = getIntWidth(Promotable);
4347 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004348 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4349 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4350}
4351
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004352/// \brief Recurses in pointer/array types until it finds an objc retainable
4353/// type and returns its ownership.
4354Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4355 while (!T.isNull()) {
4356 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4357 return T.getObjCLifetime();
4358 if (T->isArrayType())
4359 T = getBaseElementType(T);
4360 else if (const PointerType *PT = T->getAs<PointerType>())
4361 T = PT->getPointeeType();
4362 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004363 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004364 else
4365 break;
4366 }
4367
4368 return Qualifiers::OCL_None;
4369}
4370
Mike Stump11289f42009-09-09 15:08:12 +00004371/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004372/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004373/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004374int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004375 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4376 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004377 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004378
Chris Lattner76a00cf2008-04-06 22:59:24 +00004379 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4380 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004381
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004382 unsigned LHSRank = getIntegerRank(LHSC);
4383 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004384
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004385 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4386 if (LHSRank == RHSRank) return 0;
4387 return LHSRank > RHSRank ? 1 : -1;
4388 }
Mike Stump11289f42009-09-09 15:08:12 +00004389
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004390 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4391 if (LHSUnsigned) {
4392 // If the unsigned [LHS] type is larger, return it.
4393 if (LHSRank >= RHSRank)
4394 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004395
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004396 // If the signed type can represent all values of the unsigned type, it
4397 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004398 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004399 return -1;
4400 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004401
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004402 // If the unsigned [RHS] type is larger, return it.
4403 if (RHSRank >= LHSRank)
4404 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004405
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004406 // If the signed type can represent all values of the unsigned type, it
4407 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004408 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004409 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004410}
Anders Carlsson98f07902007-08-17 05:31:46 +00004411
Anders Carlsson6d417272009-11-14 21:45:58 +00004412static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004413CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4414 DeclContext *DC, IdentifierInfo *Id) {
4415 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004416 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004417 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004418 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004419 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004420}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004421
Mike Stump11289f42009-09-09 15:08:12 +00004422// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004423QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004424 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00004425 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004426 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004427 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00004428 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004429
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004430 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004431
Anders Carlsson98f07902007-08-17 05:31:46 +00004432 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004433 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004434 // int flags;
4435 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004436 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004437 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004438 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004439 FieldTypes[3] = LongTy;
4440
Anders Carlsson98f07902007-08-17 05:31:46 +00004441 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004442 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004443 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004444 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004445 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004446 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004447 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004448 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004449 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004450 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004451 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004452 }
4453
Douglas Gregord5058122010-02-11 01:19:42 +00004454 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004455 }
Mike Stump11289f42009-09-09 15:08:12 +00004456
Anders Carlsson98f07902007-08-17 05:31:46 +00004457 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004458}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004459
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004460QualType ASTContext::getObjCSuperType() const {
4461 if (ObjCSuperType.isNull()) {
4462 RecordDecl *ObjCSuperTypeDecl =
4463 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4464 TUDecl->addDecl(ObjCSuperTypeDecl);
4465 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4466 }
4467 return ObjCSuperType;
4468}
4469
Douglas Gregor512b0772009-04-23 22:29:11 +00004470void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004471 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004472 assert(Rec && "Invalid CFConstantStringType");
4473 CFConstantStringTypeDecl = Rec->getDecl();
4474}
4475
Jay Foad39c79802011-01-12 09:06:06 +00004476QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004477 if (BlockDescriptorType)
4478 return getTagDeclType(BlockDescriptorType);
4479
4480 RecordDecl *T;
4481 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004482 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004483 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00004484 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004485
4486 QualType FieldTypes[] = {
4487 UnsignedLongTy,
4488 UnsignedLongTy,
4489 };
4490
4491 const char *FieldNames[] = {
4492 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004493 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004494 };
4495
4496 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004497 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00004498 SourceLocation(),
4499 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004500 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00004501 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004502 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004503 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004504 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00004505 T->addDecl(Field);
4506 }
4507
Douglas Gregord5058122010-02-11 01:19:42 +00004508 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004509
4510 BlockDescriptorType = T;
4511
4512 return getTagDeclType(BlockDescriptorType);
4513}
4514
Jay Foad39c79802011-01-12 09:06:06 +00004515QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004516 if (BlockDescriptorExtendedType)
4517 return getTagDeclType(BlockDescriptorExtendedType);
4518
4519 RecordDecl *T;
4520 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004521 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004522 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00004523 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004524
4525 QualType FieldTypes[] = {
4526 UnsignedLongTy,
4527 UnsignedLongTy,
4528 getPointerType(VoidPtrTy),
4529 getPointerType(VoidPtrTy)
4530 };
4531
4532 const char *FieldNames[] = {
4533 "reserved",
4534 "Size",
4535 "CopyFuncPtr",
4536 "DestroyFuncPtr"
4537 };
4538
4539 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004540 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004541 SourceLocation(),
4542 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004543 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004544 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004545 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004546 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004547 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004548 T->addDecl(Field);
4549 }
4550
Douglas Gregord5058122010-02-11 01:19:42 +00004551 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004552
4553 BlockDescriptorExtendedType = T;
4554
4555 return getTagDeclType(BlockDescriptorExtendedType);
4556}
4557
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004558/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4559/// requires copy/dispose. Note that this must match the logic
4560/// in buildByrefHelpers.
4561bool ASTContext::BlockRequiresCopying(QualType Ty,
4562 const VarDecl *D) {
4563 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4564 const Expr *copyExpr = getBlockVarCopyInits(D);
4565 if (!copyExpr && record->hasTrivialDestructor()) return false;
4566
Mike Stump94967902009-10-21 18:16:27 +00004567 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004568 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004569
4570 if (!Ty->isObjCRetainableType()) return false;
4571
4572 Qualifiers qs = Ty.getQualifiers();
4573
4574 // If we have lifetime, that dominates.
4575 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4576 assert(getLangOpts().ObjCAutoRefCount);
4577
4578 switch (lifetime) {
4579 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4580
4581 // These are just bits as far as the runtime is concerned.
4582 case Qualifiers::OCL_ExplicitNone:
4583 case Qualifiers::OCL_Autoreleasing:
4584 return false;
4585
4586 // Tell the runtime that this is ARC __weak, called by the
4587 // byref routines.
4588 case Qualifiers::OCL_Weak:
4589 // ARC __strong __block variables need to be retained.
4590 case Qualifiers::OCL_Strong:
4591 return true;
4592 }
4593 llvm_unreachable("fell out of lifetime switch!");
4594 }
4595 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4596 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004597}
4598
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004599bool ASTContext::getByrefLifetime(QualType Ty,
4600 Qualifiers::ObjCLifetime &LifeTime,
4601 bool &HasByrefExtendedLayout) const {
4602
4603 if (!getLangOpts().ObjC1 ||
4604 getLangOpts().getGC() != LangOptions::NonGC)
4605 return false;
4606
4607 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004608 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004609 HasByrefExtendedLayout = true;
4610 LifeTime = Qualifiers::OCL_None;
4611 }
4612 else if (getLangOpts().ObjCAutoRefCount)
4613 LifeTime = Ty.getObjCLifetime();
4614 // MRR.
4615 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4616 LifeTime = Qualifiers::OCL_ExplicitNone;
4617 else
4618 LifeTime = Qualifiers::OCL_None;
4619 return true;
4620}
4621
Douglas Gregorbab8a962011-09-08 01:46:34 +00004622TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4623 if (!ObjCInstanceTypeDecl)
4624 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4625 getTranslationUnitDecl(),
4626 SourceLocation(),
4627 SourceLocation(),
4628 &Idents.get("instancetype"),
4629 getTrivialTypeSourceInfo(getObjCIdType()));
4630 return ObjCInstanceTypeDecl;
4631}
4632
Anders Carlsson18acd442007-10-29 06:33:42 +00004633// This returns true if a type has been typedefed to BOOL:
4634// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004635static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004636 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004637 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4638 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004639
Anders Carlssond8499822007-10-29 05:01:08 +00004640 return false;
4641}
4642
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004643/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004644/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004645CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004646 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4647 return CharUnits::Zero();
4648
Ken Dyck40775002010-01-11 17:06:35 +00004649 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004650
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004651 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004652 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004653 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004654 // Treat arrays as pointers, since that's how they're passed in.
4655 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004656 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004657 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004658}
4659
4660static inline
4661std::string charUnitsToString(const CharUnits &CU) {
4662 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004663}
4664
John McCall351762c2011-02-07 10:33:21 +00004665/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004666/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004667std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4668 std::string S;
4669
David Chisnall950a9512009-11-17 19:33:30 +00004670 const BlockDecl *Decl = Expr->getBlockDecl();
4671 QualType BlockTy =
4672 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4673 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004674 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004675 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4676 BlockTy->getAs<FunctionType>()->getResultType(),
4677 S, true /*Extended*/);
4678 else
4679 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4680 S);
David Chisnall950a9512009-11-17 19:33:30 +00004681 // Compute size of all parameters.
4682 // Start with computing size of a pointer in number of bytes.
4683 // FIXME: There might(should) be a better way of doing this computation!
4684 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004685 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4686 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004687 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004688 E = Decl->param_end(); PI != E; ++PI) {
4689 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004690 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004691 if (sz.isZero())
4692 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004693 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004694 ParmOffset += sz;
4695 }
4696 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004697 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004698 // Block pointer and offset.
4699 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004700
4701 // Argument types.
4702 ParmOffset = PtrSize;
4703 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4704 Decl->param_end(); PI != E; ++PI) {
4705 ParmVarDecl *PVDecl = *PI;
4706 QualType PType = PVDecl->getOriginalType();
4707 if (const ArrayType *AT =
4708 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4709 // Use array's original type only if it has known number of
4710 // elements.
4711 if (!isa<ConstantArrayType>(AT))
4712 PType = PVDecl->getType();
4713 } else if (PType->isFunctionType())
4714 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004715 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004716 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4717 S, true /*Extended*/);
4718 else
4719 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004720 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004721 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004722 }
John McCall351762c2011-02-07 10:33:21 +00004723
4724 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004725}
4726
Douglas Gregora9d84932011-05-27 01:19:52 +00004727bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004728 std::string& S) {
4729 // Encode result type.
4730 getObjCEncodingForType(Decl->getResultType(), S);
4731 CharUnits ParmOffset;
4732 // Compute size of all parameters.
4733 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4734 E = Decl->param_end(); PI != E; ++PI) {
4735 QualType PType = (*PI)->getType();
4736 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004737 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004738 continue;
4739
David Chisnall50e4eba2010-12-30 14:05:53 +00004740 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004741 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004742 ParmOffset += sz;
4743 }
4744 S += charUnitsToString(ParmOffset);
4745 ParmOffset = CharUnits::Zero();
4746
4747 // Argument types.
4748 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4749 E = Decl->param_end(); PI != E; ++PI) {
4750 ParmVarDecl *PVDecl = *PI;
4751 QualType PType = PVDecl->getOriginalType();
4752 if (const ArrayType *AT =
4753 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4754 // Use array's original type only if it has known number of
4755 // elements.
4756 if (!isa<ConstantArrayType>(AT))
4757 PType = PVDecl->getType();
4758 } else if (PType->isFunctionType())
4759 PType = PVDecl->getType();
4760 getObjCEncodingForType(PType, S);
4761 S += charUnitsToString(ParmOffset);
4762 ParmOffset += getObjCEncodingTypeSize(PType);
4763 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004764
4765 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004766}
4767
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004768/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4769/// method parameter or return type. If Extended, include class names and
4770/// block object types.
4771void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4772 QualType T, std::string& S,
4773 bool Extended) const {
4774 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4775 getObjCEncodingForTypeQualifier(QT, S);
4776 // Encode parameter type.
4777 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4778 true /*OutermostType*/,
4779 false /*EncodingProperty*/,
4780 false /*StructField*/,
4781 Extended /*EncodeBlockParameters*/,
4782 Extended /*EncodeClassNames*/);
4783}
4784
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004785/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004786/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004787bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004788 std::string& S,
4789 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004790 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004791 // Encode return type.
4792 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4793 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004794 // Compute size of all parameters.
4795 // Start with computing size of a pointer in number of bytes.
4796 // FIXME: There might(should) be a better way of doing this computation!
4797 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004798 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004799 // The first two arguments (self and _cmd) are pointers; account for
4800 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004801 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004802 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004803 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004804 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004805 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004806 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004807 continue;
4808
Ken Dyck40775002010-01-11 17:06:35 +00004809 assert (sz.isPositive() &&
4810 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004811 ParmOffset += sz;
4812 }
Ken Dyck40775002010-01-11 17:06:35 +00004813 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004814 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004815 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004816
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004817 // Argument types.
4818 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004819 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004820 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004821 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004822 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004823 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004824 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4825 // Use array's original type only if it has known number of
4826 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004827 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004828 PType = PVDecl->getType();
4829 } else if (PType->isFunctionType())
4830 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004831 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4832 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004833 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004834 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004835 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004836
4837 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004838}
4839
Daniel Dunbar4932b362008-08-28 04:38:10 +00004840/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004841/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004842/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4843/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004844/// Property attributes are stored as a comma-delimited C string. The simple
4845/// attributes readonly and bycopy are encoded as single characters. The
4846/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4847/// encoded as single characters, followed by an identifier. Property types
4848/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004849/// these attributes are defined by the following enumeration:
4850/// @code
4851/// enum PropertyAttributes {
4852/// kPropertyReadOnly = 'R', // property is read-only.
4853/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4854/// kPropertyByref = '&', // property is a reference to the value last assigned
4855/// kPropertyDynamic = 'D', // property is dynamic
4856/// kPropertyGetter = 'G', // followed by getter selector name
4857/// kPropertySetter = 'S', // followed by setter selector name
4858/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004859/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004860/// kPropertyWeak = 'W' // 'weak' property
4861/// kPropertyStrong = 'P' // property GC'able
4862/// kPropertyNonAtomic = 'N' // property non-atomic
4863/// };
4864/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004865void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004866 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004867 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004868 // Collect information from the property implementation decl(s).
4869 bool Dynamic = false;
4870 ObjCPropertyImplDecl *SynthesizePID = 0;
4871
4872 // FIXME: Duplicated code due to poor abstraction.
4873 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004874 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004875 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4876 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004877 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004878 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004879 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004880 if (PID->getPropertyDecl() == PD) {
4881 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4882 Dynamic = true;
4883 } else {
4884 SynthesizePID = PID;
4885 }
4886 }
4887 }
4888 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004889 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004890 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004891 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004892 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004893 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004894 if (PID->getPropertyDecl() == PD) {
4895 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4896 Dynamic = true;
4897 } else {
4898 SynthesizePID = PID;
4899 }
4900 }
Mike Stump11289f42009-09-09 15:08:12 +00004901 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004902 }
4903 }
4904
4905 // FIXME: This is not very efficient.
4906 S = "T";
4907
4908 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004909 // GCC has some special rules regarding encoding of properties which
4910 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004911 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004912 true /* outermost type */,
4913 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004914
4915 if (PD->isReadOnly()) {
4916 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00004917 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
4918 S += ",C";
4919 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
4920 S += ",&";
Daniel Dunbar4932b362008-08-28 04:38:10 +00004921 } else {
4922 switch (PD->getSetterKind()) {
4923 case ObjCPropertyDecl::Assign: break;
4924 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004925 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004926 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004927 }
4928 }
4929
4930 // It really isn't clear at all what this means, since properties
4931 // are "dynamic by default".
4932 if (Dynamic)
4933 S += ",D";
4934
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004935 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4936 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004937
Daniel Dunbar4932b362008-08-28 04:38:10 +00004938 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4939 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004940 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004941 }
4942
4943 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4944 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004945 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004946 }
4947
4948 if (SynthesizePID) {
4949 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4950 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004951 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004952 }
4953
4954 // FIXME: OBJCGC: weak & strong
4955}
4956
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004957/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004958/// Another legacy compatibility encoding: 32-bit longs are encoded as
4959/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004960/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4961///
4962void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004963 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004964 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004965 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004966 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004967 else
Jay Foad39c79802011-01-12 09:06:06 +00004968 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004969 PointeeTy = IntTy;
4970 }
4971 }
4972}
4973
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004974void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004975 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004976 // We follow the behavior of gcc, expanding structures which are
4977 // directly pointed to, and expanding embedded structures. Note that
4978 // these rules are sufficient to prevent recursive encoding of the
4979 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004980 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004981 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004982}
4983
John McCall393a78d2012-12-20 02:45:14 +00004984static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
4985 BuiltinType::Kind kind) {
4986 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004987 case BuiltinType::Void: return 'v';
4988 case BuiltinType::Bool: return 'B';
4989 case BuiltinType::Char_U:
4990 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00004991 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00004992 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00004993 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00004994 case BuiltinType::UInt: return 'I';
4995 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00004996 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004997 case BuiltinType::UInt128: return 'T';
4998 case BuiltinType::ULongLong: return 'Q';
4999 case BuiltinType::Char_S:
5000 case BuiltinType::SChar: return 'c';
5001 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005002 case BuiltinType::WChar_S:
5003 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005004 case BuiltinType::Int: return 'i';
5005 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005006 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005007 case BuiltinType::LongLong: return 'q';
5008 case BuiltinType::Int128: return 't';
5009 case BuiltinType::Float: return 'f';
5010 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005011 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005012 case BuiltinType::NullPtr: return '*'; // like char*
5013
5014 case BuiltinType::Half:
5015 // FIXME: potentially need @encodes for these!
5016 return ' ';
5017
5018 case BuiltinType::ObjCId:
5019 case BuiltinType::ObjCClass:
5020 case BuiltinType::ObjCSel:
5021 llvm_unreachable("@encoding ObjC primitive type");
5022
5023 // OpenCL and placeholder types don't need @encodings.
5024 case BuiltinType::OCLImage1d:
5025 case BuiltinType::OCLImage1dArray:
5026 case BuiltinType::OCLImage1dBuffer:
5027 case BuiltinType::OCLImage2d:
5028 case BuiltinType::OCLImage2dArray:
5029 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005030 case BuiltinType::OCLEvent:
Guy Benyei61054192013-02-07 10:55:47 +00005031 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005032 case BuiltinType::Dependent:
5033#define BUILTIN_TYPE(KIND, ID)
5034#define PLACEHOLDER_TYPE(KIND, ID) \
5035 case BuiltinType::KIND:
5036#include "clang/AST/BuiltinTypes.def"
5037 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005038 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005039 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005040}
5041
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005042static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5043 EnumDecl *Enum = ET->getDecl();
5044
5045 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5046 if (!Enum->isFixed())
5047 return 'i';
5048
5049 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005050 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5051 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005052}
5053
Jay Foad39c79802011-01-12 09:06:06 +00005054static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005055 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005056 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005057 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005058 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5059 // The GNU runtime requires more information; bitfields are encoded as b,
5060 // then the offset (in bits) of the first element, then the type of the
5061 // bitfield, then the size in bits. For example, in this structure:
5062 //
5063 // struct
5064 // {
5065 // int integer;
5066 // int flags:2;
5067 // };
5068 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5069 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5070 // information is not especially sensible, but we're stuck with it for
5071 // compatibility with GCC, although providing it breaks anything that
5072 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005073 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005074 const RecordDecl *RD = FD->getParent();
5075 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005076 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005077 if (const EnumType *ET = T->getAs<EnumType>())
5078 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005079 else {
5080 const BuiltinType *BT = T->castAs<BuiltinType>();
5081 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5082 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005083 }
Richard Smithcaf33902011-10-10 18:28:20 +00005084 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005085}
5086
Daniel Dunbar07d07852009-10-18 21:17:35 +00005087// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005088void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5089 bool ExpandPointedToStructures,
5090 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005091 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005092 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005093 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005094 bool StructField,
5095 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005096 bool EncodeClassNames,
5097 bool EncodePointerToObjCTypedef) const {
John McCall393a78d2012-12-20 02:45:14 +00005098 CanQualType CT = getCanonicalType(T);
5099 switch (CT->getTypeClass()) {
5100 case Type::Builtin:
5101 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005102 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005103 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005104 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5105 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5106 else
5107 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005108 return;
Mike Stump11289f42009-09-09 15:08:12 +00005109
John McCall393a78d2012-12-20 02:45:14 +00005110 case Type::Complex: {
5111 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005112 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00005113 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00005114 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005115 return;
5116 }
John McCall393a78d2012-12-20 02:45:14 +00005117
5118 case Type::Atomic: {
5119 const AtomicType *AT = T->castAs<AtomicType>();
5120 S += 'A';
5121 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5122 false, false);
5123 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005124 }
John McCall393a78d2012-12-20 02:45:14 +00005125
5126 // encoding for pointer or reference types.
5127 case Type::Pointer:
5128 case Type::LValueReference:
5129 case Type::RValueReference: {
5130 QualType PointeeTy;
5131 if (isa<PointerType>(CT)) {
5132 const PointerType *PT = T->castAs<PointerType>();
5133 if (PT->isObjCSelType()) {
5134 S += ':';
5135 return;
5136 }
5137 PointeeTy = PT->getPointeeType();
5138 } else {
5139 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5140 }
5141
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005142 bool isReadOnly = false;
5143 // For historical/compatibility reasons, the read-only qualifier of the
5144 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5145 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005146 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005147 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005148 if (OutermostType && T.isConstQualified()) {
5149 isReadOnly = true;
5150 S += 'r';
5151 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005152 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005153 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005154 while (P->getAs<PointerType>())
5155 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005156 if (P.isConstQualified()) {
5157 isReadOnly = true;
5158 S += 'r';
5159 }
5160 }
5161 if (isReadOnly) {
5162 // Another legacy compatibility encoding. Some ObjC qualifier and type
5163 // combinations need to be rearranged.
5164 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005165 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005166 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005167 }
Mike Stump11289f42009-09-09 15:08:12 +00005168
Anders Carlssond8499822007-10-29 05:01:08 +00005169 if (PointeeTy->isCharType()) {
5170 // char pointer types should be encoded as '*' unless it is a
5171 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005172 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005173 S += '*';
5174 return;
5175 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005176 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005177 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5178 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5179 S += '#';
5180 return;
5181 }
5182 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5183 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5184 S += '@';
5185 return;
5186 }
5187 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005188 }
Anders Carlssond8499822007-10-29 05:01:08 +00005189 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005190 getLegacyIntegralTypeEncoding(PointeeTy);
5191
Mike Stump11289f42009-09-09 15:08:12 +00005192 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005193 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005194 return;
5195 }
John McCall393a78d2012-12-20 02:45:14 +00005196
5197 case Type::ConstantArray:
5198 case Type::IncompleteArray:
5199 case Type::VariableArray: {
5200 const ArrayType *AT = cast<ArrayType>(CT);
5201
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005202 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005203 // Incomplete arrays are encoded as a pointer to the array element.
5204 S += '^';
5205
Mike Stump11289f42009-09-09 15:08:12 +00005206 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005207 false, ExpandStructures, FD);
5208 } else {
5209 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005210
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005211 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
5212 if (getTypeSize(CAT->getElementType()) == 0)
5213 S += '0';
5214 else
5215 S += llvm::utostr(CAT->getSize().getZExtValue());
5216 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005217 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005218 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5219 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005220 S += '0';
5221 }
Mike Stump11289f42009-09-09 15:08:12 +00005222
5223 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005224 false, ExpandStructures, FD);
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::FunctionNoProto:
5231 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005232 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005233 return;
Mike Stump11289f42009-09-09 15:08:12 +00005234
John McCall393a78d2012-12-20 02:45:14 +00005235 case Type::Record: {
5236 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005237 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005238 // Anonymous structures print as '?'
5239 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5240 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005241 if (ClassTemplateSpecializationDecl *Spec
5242 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5243 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005244 llvm::raw_string_ostream OS(S);
5245 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005246 TemplateArgs.data(),
5247 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005248 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005249 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005250 } else {
5251 S += '?';
5252 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005253 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005254 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005255 if (!RDecl->isUnion()) {
5256 getObjCEncodingForStructureImpl(RDecl, S, FD);
5257 } else {
5258 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5259 FieldEnd = RDecl->field_end();
5260 Field != FieldEnd; ++Field) {
5261 if (FD) {
5262 S += '"';
5263 S += Field->getNameAsString();
5264 S += '"';
5265 }
Mike Stump11289f42009-09-09 15:08:12 +00005266
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005267 // Special case bit-fields.
5268 if (Field->isBitField()) {
5269 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00005270 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005271 } else {
5272 QualType qt = Field->getType();
5273 getLegacyIntegralTypeEncoding(qt);
5274 getObjCEncodingForTypeImpl(qt, S, false, true,
5275 FD, /*OutermostType*/false,
5276 /*EncodingProperty*/false,
5277 /*StructField*/true);
5278 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005279 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005280 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005281 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005282 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005283 return;
5284 }
Mike Stump11289f42009-09-09 15:08:12 +00005285
John McCall393a78d2012-12-20 02:45:14 +00005286 case Type::BlockPointer: {
5287 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005288 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005289 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005290 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005291
5292 S += '<';
5293 // Block return type
5294 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5295 ExpandPointedToStructures, ExpandStructures,
5296 FD,
5297 false /* OutermostType */,
5298 EncodingProperty,
5299 false /* StructField */,
5300 EncodeBlockParameters,
5301 EncodeClassNames);
5302 // Block self
5303 S += "@?";
5304 // Block parameters
5305 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5306 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5307 E = FPT->arg_type_end(); I && (I != E); ++I) {
5308 getObjCEncodingForTypeImpl(*I, S,
5309 ExpandPointedToStructures,
5310 ExpandStructures,
5311 FD,
5312 false /* OutermostType */,
5313 EncodingProperty,
5314 false /* StructField */,
5315 EncodeBlockParameters,
5316 EncodeClassNames);
5317 }
5318 }
5319 S += '>';
5320 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005321 return;
5322 }
Mike Stump11289f42009-09-09 15:08:12 +00005323
John McCall393a78d2012-12-20 02:45:14 +00005324 case Type::ObjCObject:
5325 case Type::ObjCInterface: {
5326 // Ignore protocol qualifiers when mangling at this level.
5327 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005328
John McCall393a78d2012-12-20 02:45:14 +00005329 // The assumption seems to be that this assert will succeed
5330 // because nested levels will have filtered out 'id' and 'Class'.
5331 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005332 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005333 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005334 S += '{';
5335 const IdentifierInfo *II = OI->getIdentifier();
5336 S += II->getName();
5337 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005338 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005339 DeepCollectObjCIvars(OI, true, Ivars);
5340 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005341 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005342 if (Field->isBitField())
5343 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005344 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005345 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5346 false, false, false, false, false,
5347 EncodePointerToObjCTypedef);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005348 }
5349 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005350 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005351 }
Mike Stump11289f42009-09-09 15:08:12 +00005352
John McCall393a78d2012-12-20 02:45:14 +00005353 case Type::ObjCObjectPointer: {
5354 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005355 if (OPT->isObjCIdType()) {
5356 S += '@';
5357 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005358 }
Mike Stump11289f42009-09-09 15:08:12 +00005359
Steve Narofff0c86112009-10-28 22:03:49 +00005360 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5361 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5362 // Since this is a binary compatibility issue, need to consult with runtime
5363 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005364 S += '#';
5365 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005366 }
Mike Stump11289f42009-09-09 15:08:12 +00005367
Chris Lattnere7cabb92009-07-13 00:10:46 +00005368 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005369 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005370 ExpandPointedToStructures,
5371 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005372 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005373 // Note that we do extended encoding of protocol qualifer list
5374 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005375 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00005376 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5377 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005378 S += '<';
5379 S += (*I)->getNameAsString();
5380 S += '>';
5381 }
5382 S += '"';
5383 }
5384 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005385 }
Mike Stump11289f42009-09-09 15:08:12 +00005386
Chris Lattnere7cabb92009-07-13 00:10:46 +00005387 QualType PointeeTy = OPT->getPointeeType();
5388 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005389 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5390 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005391 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005392 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005393 // {...};
5394 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00005395 getObjCEncodingForTypeImpl(PointeeTy, S,
5396 false, ExpandPointedToStructures,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005397 NULL,
5398 false, false, false, false, false,
5399 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005400 return;
5401 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005402
5403 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005404 if (OPT->getInterfaceDecl() &&
5405 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005406 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005407 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00005408 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5409 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005410 S += '<';
5411 S += (*I)->getNameAsString();
5412 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005413 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005414 S += '"';
5415 }
5416 return;
5417 }
Mike Stump11289f42009-09-09 15:08:12 +00005418
John McCalla9e6e8d2010-05-17 23:56:34 +00005419 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005420 // FIXME: we shoul do better than that. 'M' is available.
5421 case Type::MemberPointer:
John McCalla9e6e8d2010-05-17 23:56:34 +00005422 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005423
John McCall393a78d2012-12-20 02:45:14 +00005424 case Type::Vector:
5425 case Type::ExtVector:
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005426 // This matches gcc's encoding, even though technically it is
5427 // insufficient.
5428 // FIXME. We should do a better job than gcc.
5429 return;
John McCall393a78d2012-12-20 02:45:14 +00005430
Richard Smith27d807c2013-04-30 13:56:41 +00005431 case Type::Auto:
5432 // We could see an undeduced auto type here during error recovery.
5433 // Just ignore it.
5434 return;
5435
John McCall393a78d2012-12-20 02:45:14 +00005436#define ABSTRACT_TYPE(KIND, BASE)
5437#define TYPE(KIND, BASE)
5438#define DEPENDENT_TYPE(KIND, BASE) \
5439 case Type::KIND:
5440#define NON_CANONICAL_TYPE(KIND, BASE) \
5441 case Type::KIND:
5442#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5443 case Type::KIND:
5444#include "clang/AST/TypeNodes.def"
5445 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005446 }
John McCall393a78d2012-12-20 02:45:14 +00005447 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005448}
5449
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005450void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5451 std::string &S,
5452 const FieldDecl *FD,
5453 bool includeVBases) const {
5454 assert(RDecl && "Expected non-null RecordDecl");
5455 assert(!RDecl->isUnion() && "Should not be called for unions");
5456 if (!RDecl->getDefinition())
5457 return;
5458
5459 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5460 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5461 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5462
5463 if (CXXRec) {
5464 for (CXXRecordDecl::base_class_iterator
5465 BI = CXXRec->bases_begin(),
5466 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5467 if (!BI->isVirtual()) {
5468 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005469 if (base->isEmpty())
5470 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005471 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005472 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5473 std::make_pair(offs, base));
5474 }
5475 }
5476 }
5477
5478 unsigned i = 0;
5479 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5480 FieldEnd = RDecl->field_end();
5481 Field != FieldEnd; ++Field, ++i) {
5482 uint64_t offs = layout.getFieldOffset(i);
5483 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005484 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005485 }
5486
5487 if (CXXRec && includeVBases) {
5488 for (CXXRecordDecl::base_class_iterator
5489 BI = CXXRec->vbases_begin(),
5490 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5491 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005492 if (base->isEmpty())
5493 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005494 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005495 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5496 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5497 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005498 }
5499 }
5500
5501 CharUnits size;
5502 if (CXXRec) {
5503 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5504 } else {
5505 size = layout.getSize();
5506 }
5507
5508 uint64_t CurOffs = 0;
5509 std::multimap<uint64_t, NamedDecl *>::iterator
5510 CurLayObj = FieldOrBaseOffsets.begin();
5511
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005512 if (CXXRec && CXXRec->isDynamicClass() &&
5513 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005514 if (FD) {
5515 S += "\"_vptr$";
5516 std::string recname = CXXRec->getNameAsString();
5517 if (recname.empty()) recname = "?";
5518 S += recname;
5519 S += '"';
5520 }
5521 S += "^^?";
5522 CurOffs += getTypeSize(VoidPtrTy);
5523 }
5524
5525 if (!RDecl->hasFlexibleArrayMember()) {
5526 // Mark the end of the structure.
5527 uint64_t offs = toBits(size);
5528 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5529 std::make_pair(offs, (NamedDecl*)0));
5530 }
5531
5532 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5533 assert(CurOffs <= CurLayObj->first);
5534
5535 if (CurOffs < CurLayObj->first) {
5536 uint64_t padding = CurLayObj->first - CurOffs;
5537 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5538 // packing/alignment of members is different that normal, in which case
5539 // the encoding will be out-of-sync with the real layout.
5540 // If the runtime switches to just consider the size of types without
5541 // taking into account alignment, we could make padding explicit in the
5542 // encoding (e.g. using arrays of chars). The encoding strings would be
5543 // longer then though.
5544 CurOffs += padding;
5545 }
5546
5547 NamedDecl *dcl = CurLayObj->second;
5548 if (dcl == 0)
5549 break; // reached end of structure.
5550
5551 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5552 // We expand the bases without their virtual bases since those are going
5553 // in the initial structure. Note that this differs from gcc which
5554 // expands virtual bases each time one is encountered in the hierarchy,
5555 // making the encoding type bigger than it really is.
5556 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005557 assert(!base->isEmpty());
5558 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005559 } else {
5560 FieldDecl *field = cast<FieldDecl>(dcl);
5561 if (FD) {
5562 S += '"';
5563 S += field->getNameAsString();
5564 S += '"';
5565 }
5566
5567 if (field->isBitField()) {
5568 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00005569 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005570 } else {
5571 QualType qt = field->getType();
5572 getLegacyIntegralTypeEncoding(qt);
5573 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5574 /*OutermostType*/false,
5575 /*EncodingProperty*/false,
5576 /*StructField*/true);
5577 CurOffs += getTypeSize(field->getType());
5578 }
5579 }
5580 }
5581}
5582
Mike Stump11289f42009-09-09 15:08:12 +00005583void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005584 std::string& S) const {
5585 if (QT & Decl::OBJC_TQ_In)
5586 S += 'n';
5587 if (QT & Decl::OBJC_TQ_Inout)
5588 S += 'N';
5589 if (QT & Decl::OBJC_TQ_Out)
5590 S += 'o';
5591 if (QT & Decl::OBJC_TQ_Bycopy)
5592 S += 'O';
5593 if (QT & Decl::OBJC_TQ_Byref)
5594 S += 'R';
5595 if (QT & Decl::OBJC_TQ_Oneway)
5596 S += 'V';
5597}
5598
Douglas Gregor3ea72692011-08-12 05:46:01 +00005599TypedefDecl *ASTContext::getObjCIdDecl() const {
5600 if (!ObjCIdDecl) {
5601 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5602 T = getObjCObjectPointerType(T);
5603 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5604 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5605 getTranslationUnitDecl(),
5606 SourceLocation(), SourceLocation(),
5607 &Idents.get("id"), IdInfo);
5608 }
5609
5610 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005611}
5612
Douglas Gregor52e02802011-08-12 06:17:30 +00005613TypedefDecl *ASTContext::getObjCSelDecl() const {
5614 if (!ObjCSelDecl) {
5615 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5616 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5617 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5618 getTranslationUnitDecl(),
5619 SourceLocation(), SourceLocation(),
5620 &Idents.get("SEL"), SelInfo);
5621 }
5622 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005623}
5624
Douglas Gregor0a586182011-08-12 05:59:41 +00005625TypedefDecl *ASTContext::getObjCClassDecl() const {
5626 if (!ObjCClassDecl) {
5627 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5628 T = getObjCObjectPointerType(T);
5629 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5630 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5631 getTranslationUnitDecl(),
5632 SourceLocation(), SourceLocation(),
5633 &Idents.get("Class"), ClassInfo);
5634 }
5635
5636 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005637}
5638
Douglas Gregord53ae832012-01-17 18:09:05 +00005639ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5640 if (!ObjCProtocolClassDecl) {
5641 ObjCProtocolClassDecl
5642 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5643 SourceLocation(),
5644 &Idents.get("Protocol"),
5645 /*PrevDecl=*/0,
5646 SourceLocation(), true);
5647 }
5648
5649 return ObjCProtocolClassDecl;
5650}
5651
Meador Inge5d3fb222012-06-16 03:34:49 +00005652//===----------------------------------------------------------------------===//
5653// __builtin_va_list Construction Functions
5654//===----------------------------------------------------------------------===//
5655
5656static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5657 // typedef char* __builtin_va_list;
5658 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5659 TypeSourceInfo *TInfo
5660 = Context->getTrivialTypeSourceInfo(CharPtrType);
5661
5662 TypedefDecl *VaListTypeDecl
5663 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5664 Context->getTranslationUnitDecl(),
5665 SourceLocation(), SourceLocation(),
5666 &Context->Idents.get("__builtin_va_list"),
5667 TInfo);
5668 return VaListTypeDecl;
5669}
5670
5671static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5672 // typedef void* __builtin_va_list;
5673 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5674 TypeSourceInfo *TInfo
5675 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5676
5677 TypedefDecl *VaListTypeDecl
5678 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5679 Context->getTranslationUnitDecl(),
5680 SourceLocation(), SourceLocation(),
5681 &Context->Idents.get("__builtin_va_list"),
5682 TInfo);
5683 return VaListTypeDecl;
5684}
5685
Tim Northover9bb857a2013-01-31 12:13:10 +00005686static TypedefDecl *
5687CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5688 RecordDecl *VaListTagDecl;
5689 if (Context->getLangOpts().CPlusPlus) {
5690 // namespace std { struct __va_list {
5691 NamespaceDecl *NS;
5692 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5693 Context->getTranslationUnitDecl(),
5694 /*Inline*/false, SourceLocation(),
5695 SourceLocation(), &Context->Idents.get("std"),
5696 /*PrevDecl*/0);
5697
5698 VaListTagDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5699 Context->getTranslationUnitDecl(),
5700 SourceLocation(), SourceLocation(),
5701 &Context->Idents.get("__va_list"));
5702 VaListTagDecl->setDeclContext(NS);
5703 } else {
5704 // struct __va_list
5705 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5706 Context->getTranslationUnitDecl(),
5707 &Context->Idents.get("__va_list"));
5708 }
5709
5710 VaListTagDecl->startDefinition();
5711
5712 const size_t NumFields = 5;
5713 QualType FieldTypes[NumFields];
5714 const char *FieldNames[NumFields];
5715
5716 // void *__stack;
5717 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5718 FieldNames[0] = "__stack";
5719
5720 // void *__gr_top;
5721 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5722 FieldNames[1] = "__gr_top";
5723
5724 // void *__vr_top;
5725 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5726 FieldNames[2] = "__vr_top";
5727
5728 // int __gr_offs;
5729 FieldTypes[3] = Context->IntTy;
5730 FieldNames[3] = "__gr_offs";
5731
5732 // int __vr_offs;
5733 FieldTypes[4] = Context->IntTy;
5734 FieldNames[4] = "__vr_offs";
5735
5736 // Create fields
5737 for (unsigned i = 0; i < NumFields; ++i) {
5738 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5739 VaListTagDecl,
5740 SourceLocation(),
5741 SourceLocation(),
5742 &Context->Idents.get(FieldNames[i]),
5743 FieldTypes[i], /*TInfo=*/0,
5744 /*BitWidth=*/0,
5745 /*Mutable=*/false,
5746 ICIS_NoInit);
5747 Field->setAccess(AS_public);
5748 VaListTagDecl->addDecl(Field);
5749 }
5750 VaListTagDecl->completeDefinition();
5751 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5752 Context->VaListTagTy = VaListTagType;
5753
5754 // } __builtin_va_list;
5755 TypedefDecl *VaListTypedefDecl
5756 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5757 Context->getTranslationUnitDecl(),
5758 SourceLocation(), SourceLocation(),
5759 &Context->Idents.get("__builtin_va_list"),
5760 Context->getTrivialTypeSourceInfo(VaListTagType));
5761
5762 return VaListTypedefDecl;
5763}
5764
Meador Inge5d3fb222012-06-16 03:34:49 +00005765static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5766 // typedef struct __va_list_tag {
5767 RecordDecl *VaListTagDecl;
5768
5769 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5770 Context->getTranslationUnitDecl(),
5771 &Context->Idents.get("__va_list_tag"));
5772 VaListTagDecl->startDefinition();
5773
5774 const size_t NumFields = 5;
5775 QualType FieldTypes[NumFields];
5776 const char *FieldNames[NumFields];
5777
5778 // unsigned char gpr;
5779 FieldTypes[0] = Context->UnsignedCharTy;
5780 FieldNames[0] = "gpr";
5781
5782 // unsigned char fpr;
5783 FieldTypes[1] = Context->UnsignedCharTy;
5784 FieldNames[1] = "fpr";
5785
5786 // unsigned short reserved;
5787 FieldTypes[2] = Context->UnsignedShortTy;
5788 FieldNames[2] = "reserved";
5789
5790 // void* overflow_arg_area;
5791 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5792 FieldNames[3] = "overflow_arg_area";
5793
5794 // void* reg_save_area;
5795 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5796 FieldNames[4] = "reg_save_area";
5797
5798 // Create fields
5799 for (unsigned i = 0; i < NumFields; ++i) {
5800 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5801 SourceLocation(),
5802 SourceLocation(),
5803 &Context->Idents.get(FieldNames[i]),
5804 FieldTypes[i], /*TInfo=*/0,
5805 /*BitWidth=*/0,
5806 /*Mutable=*/false,
5807 ICIS_NoInit);
5808 Field->setAccess(AS_public);
5809 VaListTagDecl->addDecl(Field);
5810 }
5811 VaListTagDecl->completeDefinition();
5812 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005813 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005814
5815 // } __va_list_tag;
5816 TypedefDecl *VaListTagTypedefDecl
5817 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5818 Context->getTranslationUnitDecl(),
5819 SourceLocation(), SourceLocation(),
5820 &Context->Idents.get("__va_list_tag"),
5821 Context->getTrivialTypeSourceInfo(VaListTagType));
5822 QualType VaListTagTypedefType =
5823 Context->getTypedefType(VaListTagTypedefDecl);
5824
5825 // typedef __va_list_tag __builtin_va_list[1];
5826 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5827 QualType VaListTagArrayType
5828 = Context->getConstantArrayType(VaListTagTypedefType,
5829 Size, ArrayType::Normal, 0);
5830 TypeSourceInfo *TInfo
5831 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5832 TypedefDecl *VaListTypedefDecl
5833 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5834 Context->getTranslationUnitDecl(),
5835 SourceLocation(), SourceLocation(),
5836 &Context->Idents.get("__builtin_va_list"),
5837 TInfo);
5838
5839 return VaListTypedefDecl;
5840}
5841
5842static TypedefDecl *
5843CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5844 // typedef struct __va_list_tag {
5845 RecordDecl *VaListTagDecl;
5846 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5847 Context->getTranslationUnitDecl(),
5848 &Context->Idents.get("__va_list_tag"));
5849 VaListTagDecl->startDefinition();
5850
5851 const size_t NumFields = 4;
5852 QualType FieldTypes[NumFields];
5853 const char *FieldNames[NumFields];
5854
5855 // unsigned gp_offset;
5856 FieldTypes[0] = Context->UnsignedIntTy;
5857 FieldNames[0] = "gp_offset";
5858
5859 // unsigned fp_offset;
5860 FieldTypes[1] = Context->UnsignedIntTy;
5861 FieldNames[1] = "fp_offset";
5862
5863 // void* overflow_arg_area;
5864 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5865 FieldNames[2] = "overflow_arg_area";
5866
5867 // void* reg_save_area;
5868 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5869 FieldNames[3] = "reg_save_area";
5870
5871 // Create fields
5872 for (unsigned i = 0; i < NumFields; ++i) {
5873 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5874 VaListTagDecl,
5875 SourceLocation(),
5876 SourceLocation(),
5877 &Context->Idents.get(FieldNames[i]),
5878 FieldTypes[i], /*TInfo=*/0,
5879 /*BitWidth=*/0,
5880 /*Mutable=*/false,
5881 ICIS_NoInit);
5882 Field->setAccess(AS_public);
5883 VaListTagDecl->addDecl(Field);
5884 }
5885 VaListTagDecl->completeDefinition();
5886 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005887 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005888
5889 // } __va_list_tag;
5890 TypedefDecl *VaListTagTypedefDecl
5891 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5892 Context->getTranslationUnitDecl(),
5893 SourceLocation(), SourceLocation(),
5894 &Context->Idents.get("__va_list_tag"),
5895 Context->getTrivialTypeSourceInfo(VaListTagType));
5896 QualType VaListTagTypedefType =
5897 Context->getTypedefType(VaListTagTypedefDecl);
5898
5899 // typedef __va_list_tag __builtin_va_list[1];
5900 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5901 QualType VaListTagArrayType
5902 = Context->getConstantArrayType(VaListTagTypedefType,
5903 Size, ArrayType::Normal,0);
5904 TypeSourceInfo *TInfo
5905 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5906 TypedefDecl *VaListTypedefDecl
5907 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5908 Context->getTranslationUnitDecl(),
5909 SourceLocation(), SourceLocation(),
5910 &Context->Idents.get("__builtin_va_list"),
5911 TInfo);
5912
5913 return VaListTypedefDecl;
5914}
5915
5916static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5917 // typedef int __builtin_va_list[4];
5918 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5919 QualType IntArrayType
5920 = Context->getConstantArrayType(Context->IntTy,
5921 Size, ArrayType::Normal, 0);
5922 TypedefDecl *VaListTypedefDecl
5923 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5924 Context->getTranslationUnitDecl(),
5925 SourceLocation(), SourceLocation(),
5926 &Context->Idents.get("__builtin_va_list"),
5927 Context->getTrivialTypeSourceInfo(IntArrayType));
5928
5929 return VaListTypedefDecl;
5930}
5931
Logan Chien57086ce2012-10-10 06:56:20 +00005932static TypedefDecl *
5933CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5934 RecordDecl *VaListDecl;
5935 if (Context->getLangOpts().CPlusPlus) {
5936 // namespace std { struct __va_list {
5937 NamespaceDecl *NS;
5938 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5939 Context->getTranslationUnitDecl(),
5940 /*Inline*/false, SourceLocation(),
5941 SourceLocation(), &Context->Idents.get("std"),
5942 /*PrevDecl*/0);
5943
5944 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5945 Context->getTranslationUnitDecl(),
5946 SourceLocation(), SourceLocation(),
5947 &Context->Idents.get("__va_list"));
5948
5949 VaListDecl->setDeclContext(NS);
5950
5951 } else {
5952 // struct __va_list {
5953 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
5954 Context->getTranslationUnitDecl(),
5955 &Context->Idents.get("__va_list"));
5956 }
5957
5958 VaListDecl->startDefinition();
5959
5960 // void * __ap;
5961 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5962 VaListDecl,
5963 SourceLocation(),
5964 SourceLocation(),
5965 &Context->Idents.get("__ap"),
5966 Context->getPointerType(Context->VoidTy),
5967 /*TInfo=*/0,
5968 /*BitWidth=*/0,
5969 /*Mutable=*/false,
5970 ICIS_NoInit);
5971 Field->setAccess(AS_public);
5972 VaListDecl->addDecl(Field);
5973
5974 // };
5975 VaListDecl->completeDefinition();
5976
5977 // typedef struct __va_list __builtin_va_list;
5978 TypeSourceInfo *TInfo
5979 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
5980
5981 TypedefDecl *VaListTypeDecl
5982 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5983 Context->getTranslationUnitDecl(),
5984 SourceLocation(), SourceLocation(),
5985 &Context->Idents.get("__builtin_va_list"),
5986 TInfo);
5987
5988 return VaListTypeDecl;
5989}
5990
Ulrich Weigand47445072013-05-06 16:26:41 +00005991static TypedefDecl *
5992CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
5993 // typedef struct __va_list_tag {
5994 RecordDecl *VaListTagDecl;
5995 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5996 Context->getTranslationUnitDecl(),
5997 &Context->Idents.get("__va_list_tag"));
5998 VaListTagDecl->startDefinition();
5999
6000 const size_t NumFields = 4;
6001 QualType FieldTypes[NumFields];
6002 const char *FieldNames[NumFields];
6003
6004 // long __gpr;
6005 FieldTypes[0] = Context->LongTy;
6006 FieldNames[0] = "__gpr";
6007
6008 // long __fpr;
6009 FieldTypes[1] = Context->LongTy;
6010 FieldNames[1] = "__fpr";
6011
6012 // void *__overflow_arg_area;
6013 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6014 FieldNames[2] = "__overflow_arg_area";
6015
6016 // void *__reg_save_area;
6017 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6018 FieldNames[3] = "__reg_save_area";
6019
6020 // Create fields
6021 for (unsigned i = 0; i < NumFields; ++i) {
6022 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6023 VaListTagDecl,
6024 SourceLocation(),
6025 SourceLocation(),
6026 &Context->Idents.get(FieldNames[i]),
6027 FieldTypes[i], /*TInfo=*/0,
6028 /*BitWidth=*/0,
6029 /*Mutable=*/false,
6030 ICIS_NoInit);
6031 Field->setAccess(AS_public);
6032 VaListTagDecl->addDecl(Field);
6033 }
6034 VaListTagDecl->completeDefinition();
6035 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6036 Context->VaListTagTy = VaListTagType;
6037
6038 // } __va_list_tag;
6039 TypedefDecl *VaListTagTypedefDecl
6040 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6041 Context->getTranslationUnitDecl(),
6042 SourceLocation(), SourceLocation(),
6043 &Context->Idents.get("__va_list_tag"),
6044 Context->getTrivialTypeSourceInfo(VaListTagType));
6045 QualType VaListTagTypedefType =
6046 Context->getTypedefType(VaListTagTypedefDecl);
6047
6048 // typedef __va_list_tag __builtin_va_list[1];
6049 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6050 QualType VaListTagArrayType
6051 = Context->getConstantArrayType(VaListTagTypedefType,
6052 Size, ArrayType::Normal,0);
6053 TypeSourceInfo *TInfo
6054 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
6055 TypedefDecl *VaListTypedefDecl
6056 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6057 Context->getTranslationUnitDecl(),
6058 SourceLocation(), SourceLocation(),
6059 &Context->Idents.get("__builtin_va_list"),
6060 TInfo);
6061
6062 return VaListTypedefDecl;
6063}
6064
Meador Inge5d3fb222012-06-16 03:34:49 +00006065static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6066 TargetInfo::BuiltinVaListKind Kind) {
6067 switch (Kind) {
6068 case TargetInfo::CharPtrBuiltinVaList:
6069 return CreateCharPtrBuiltinVaListDecl(Context);
6070 case TargetInfo::VoidPtrBuiltinVaList:
6071 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006072 case TargetInfo::AArch64ABIBuiltinVaList:
6073 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006074 case TargetInfo::PowerABIBuiltinVaList:
6075 return CreatePowerABIBuiltinVaListDecl(Context);
6076 case TargetInfo::X86_64ABIBuiltinVaList:
6077 return CreateX86_64ABIBuiltinVaListDecl(Context);
6078 case TargetInfo::PNaClABIBuiltinVaList:
6079 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006080 case TargetInfo::AAPCSABIBuiltinVaList:
6081 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006082 case TargetInfo::SystemZBuiltinVaList:
6083 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006084 }
6085
6086 llvm_unreachable("Unhandled __builtin_va_list type kind");
6087}
6088
6089TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6090 if (!BuiltinVaListDecl)
6091 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6092
6093 return BuiltinVaListDecl;
6094}
6095
Meador Ingecfb60902012-07-01 15:57:25 +00006096QualType ASTContext::getVaListTagType() const {
6097 // Force the creation of VaListTagTy by building the __builtin_va_list
6098 // declaration.
6099 if (VaListTagTy.isNull())
6100 (void) getBuiltinVaListDecl();
6101
6102 return VaListTagTy;
6103}
6104
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006105void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006106 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006107 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006108
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006109 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006110}
6111
John McCalld28ae272009-12-02 08:04:21 +00006112/// \brief Retrieve the template name that corresponds to a non-empty
6113/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006114TemplateName
6115ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6116 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006117 unsigned size = End - Begin;
6118 assert(size > 1 && "set is not overloaded!");
6119
6120 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6121 size * sizeof(FunctionTemplateDecl*));
6122 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6123
6124 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006125 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006126 NamedDecl *D = *I;
6127 assert(isa<FunctionTemplateDecl>(D) ||
6128 (isa<UsingShadowDecl>(D) &&
6129 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6130 *Storage++ = D;
6131 }
6132
6133 return TemplateName(OT);
6134}
6135
Douglas Gregordc572a32009-03-30 22:58:21 +00006136/// \brief Retrieve the template name that represents a qualified
6137/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006138TemplateName
6139ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6140 bool TemplateKeyword,
6141 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006142 assert(NNS && "Missing nested-name-specifier in qualified template name");
6143
Douglas Gregorc42075a2010-02-04 18:10:26 +00006144 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006145 llvm::FoldingSetNodeID ID;
6146 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6147
6148 void *InsertPos = 0;
6149 QualifiedTemplateName *QTN =
6150 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6151 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006152 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6153 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006154 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6155 }
6156
6157 return TemplateName(QTN);
6158}
6159
6160/// \brief Retrieve the template name that represents a dependent
6161/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006162TemplateName
6163ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6164 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006165 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006166 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006167
6168 llvm::FoldingSetNodeID ID;
6169 DependentTemplateName::Profile(ID, NNS, Name);
6170
6171 void *InsertPos = 0;
6172 DependentTemplateName *QTN =
6173 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6174
6175 if (QTN)
6176 return TemplateName(QTN);
6177
6178 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6179 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006180 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6181 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006182 } else {
6183 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006184 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6185 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006186 DependentTemplateName *CheckQTN =
6187 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6188 assert(!CheckQTN && "Dependent type name canonicalization broken");
6189 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006190 }
6191
6192 DependentTemplateNames.InsertNode(QTN, InsertPos);
6193 return TemplateName(QTN);
6194}
6195
Douglas Gregor71395fa2009-11-04 00:56:37 +00006196/// \brief Retrieve the template name that represents a dependent
6197/// template name such as \c MetaFun::template operator+.
6198TemplateName
6199ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006200 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006201 assert((!NNS || NNS->isDependent()) &&
6202 "Nested name specifier must be dependent");
6203
6204 llvm::FoldingSetNodeID ID;
6205 DependentTemplateName::Profile(ID, NNS, Operator);
6206
6207 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006208 DependentTemplateName *QTN
6209 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006210
6211 if (QTN)
6212 return TemplateName(QTN);
6213
6214 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6215 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006216 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6217 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006218 } else {
6219 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006220 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6221 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006222
6223 DependentTemplateName *CheckQTN
6224 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6225 assert(!CheckQTN && "Dependent template name canonicalization broken");
6226 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006227 }
6228
6229 DependentTemplateNames.InsertNode(QTN, InsertPos);
6230 return TemplateName(QTN);
6231}
6232
Douglas Gregor5590be02011-01-15 06:45:20 +00006233TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006234ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6235 TemplateName replacement) const {
6236 llvm::FoldingSetNodeID ID;
6237 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6238
6239 void *insertPos = 0;
6240 SubstTemplateTemplateParmStorage *subst
6241 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6242
6243 if (!subst) {
6244 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6245 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6246 }
6247
6248 return TemplateName(subst);
6249}
6250
6251TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006252ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6253 const TemplateArgument &ArgPack) const {
6254 ASTContext &Self = const_cast<ASTContext &>(*this);
6255 llvm::FoldingSetNodeID ID;
6256 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6257
6258 void *InsertPos = 0;
6259 SubstTemplateTemplateParmPackStorage *Subst
6260 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6261
6262 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006263 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006264 ArgPack.pack_size(),
6265 ArgPack.pack_begin());
6266 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6267 }
6268
6269 return TemplateName(Subst);
6270}
6271
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006272/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006273/// TargetInfo, produce the corresponding type. The unsigned @p Type
6274/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006275CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006276 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006277 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006278 case TargetInfo::SignedShort: return ShortTy;
6279 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6280 case TargetInfo::SignedInt: return IntTy;
6281 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6282 case TargetInfo::SignedLong: return LongTy;
6283 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6284 case TargetInfo::SignedLongLong: return LongLongTy;
6285 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6286 }
6287
David Blaikie83d382b2011-09-23 05:06:16 +00006288 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006289}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006290
6291//===----------------------------------------------------------------------===//
6292// Type Predicates.
6293//===----------------------------------------------------------------------===//
6294
Fariborz Jahanian96207692009-02-18 21:49:28 +00006295/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6296/// garbage collection attribute.
6297///
John McCall553d45a2011-01-12 00:34:59 +00006298Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006299 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006300 return Qualifiers::GCNone;
6301
David Blaikiebbafb8a2012-03-11 07:00:24 +00006302 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006303 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6304
6305 // Default behaviour under objective-C's gc is for ObjC pointers
6306 // (or pointers to them) be treated as though they were declared
6307 // as __strong.
6308 if (GCAttrs == Qualifiers::GCNone) {
6309 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6310 return Qualifiers::Strong;
6311 else if (Ty->isPointerType())
6312 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6313 } else {
6314 // It's not valid to set GC attributes on anything that isn't a
6315 // pointer.
6316#ifndef NDEBUG
6317 QualType CT = Ty->getCanonicalTypeInternal();
6318 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6319 CT = AT->getElementType();
6320 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6321#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006322 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006323 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006324}
6325
Chris Lattner49af6a42008-04-07 06:51:04 +00006326//===----------------------------------------------------------------------===//
6327// Type Compatibility Testing
6328//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006329
Mike Stump11289f42009-09-09 15:08:12 +00006330/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006331/// compatible.
6332static bool areCompatVectorTypes(const VectorType *LHS,
6333 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006334 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006335 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006336 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006337}
6338
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006339bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6340 QualType SecondVec) {
6341 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6342 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6343
6344 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6345 return true;
6346
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006347 // Treat Neon vector types and most AltiVec vector types as if they are the
6348 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006349 const VectorType *First = FirstVec->getAs<VectorType>();
6350 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006351 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006352 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006353 First->getVectorKind() != VectorType::AltiVecPixel &&
6354 First->getVectorKind() != VectorType::AltiVecBool &&
6355 Second->getVectorKind() != VectorType::AltiVecPixel &&
6356 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006357 return true;
6358
6359 return false;
6360}
6361
Steve Naroff8e6aee52009-07-23 01:01:38 +00006362//===----------------------------------------------------------------------===//
6363// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6364//===----------------------------------------------------------------------===//
6365
6366/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6367/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006368bool
6369ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6370 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006371 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006372 return true;
6373 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6374 E = rProto->protocol_end(); PI != E; ++PI)
6375 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6376 return true;
6377 return false;
6378}
6379
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006380/// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
Steve Naroff8e6aee52009-07-23 01:01:38 +00006381/// return true if lhs's protocols conform to rhs's protocol; false
6382/// otherwise.
6383bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
6384 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
6385 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
6386 return false;
6387}
6388
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006389/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6390/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006391bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6392 QualType rhs) {
6393 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6394 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6395 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6396
6397 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6398 E = lhsQID->qual_end(); I != E; ++I) {
6399 bool match = false;
6400 ObjCProtocolDecl *lhsProto = *I;
6401 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6402 E = rhsOPT->qual_end(); J != E; ++J) {
6403 ObjCProtocolDecl *rhsProto = *J;
6404 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6405 match = true;
6406 break;
6407 }
6408 }
6409 if (!match)
6410 return false;
6411 }
6412 return true;
6413}
6414
Steve Naroff8e6aee52009-07-23 01:01:38 +00006415/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6416/// ObjCQualifiedIDType.
6417bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6418 bool compare) {
6419 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006420 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006421 lhs->isObjCIdType() || lhs->isObjCClassType())
6422 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006423 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006424 rhs->isObjCIdType() || rhs->isObjCClassType())
6425 return true;
6426
6427 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006428 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006429
Steve Naroff8e6aee52009-07-23 01:01:38 +00006430 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006431
Steve Naroff8e6aee52009-07-23 01:01:38 +00006432 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006433 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006434 // make sure we check the class hierarchy.
6435 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6436 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6437 E = lhsQID->qual_end(); I != E; ++I) {
6438 // when comparing an id<P> on lhs with a static type on rhs,
6439 // see if static class implements all of id's protocols, directly or
6440 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006441 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006442 return false;
6443 }
6444 }
6445 // If there are no qualifiers and no interface, we have an 'id'.
6446 return true;
6447 }
Mike Stump11289f42009-09-09 15:08:12 +00006448 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006449 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6450 E = lhsQID->qual_end(); I != E; ++I) {
6451 ObjCProtocolDecl *lhsProto = *I;
6452 bool match = false;
6453
6454 // when comparing an id<P> on lhs with a static type on rhs,
6455 // see if static class implements all of id's protocols, directly or
6456 // through its super class and categories.
6457 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6458 E = rhsOPT->qual_end(); J != E; ++J) {
6459 ObjCProtocolDecl *rhsProto = *J;
6460 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6461 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6462 match = true;
6463 break;
6464 }
6465 }
Mike Stump11289f42009-09-09 15:08:12 +00006466 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006467 // make sure we check the class hierarchy.
6468 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6469 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6470 E = lhsQID->qual_end(); I != E; ++I) {
6471 // when comparing an id<P> on lhs with a static type on rhs,
6472 // see if static class implements all of id's protocols, directly or
6473 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006474 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006475 match = true;
6476 break;
6477 }
6478 }
6479 }
6480 if (!match)
6481 return false;
6482 }
Mike Stump11289f42009-09-09 15:08:12 +00006483
Steve Naroff8e6aee52009-07-23 01:01:38 +00006484 return true;
6485 }
Mike Stump11289f42009-09-09 15:08:12 +00006486
Steve Naroff8e6aee52009-07-23 01:01:38 +00006487 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6488 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6489
Mike Stump11289f42009-09-09 15:08:12 +00006490 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006491 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006492 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006493 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6494 E = lhsOPT->qual_end(); I != E; ++I) {
6495 ObjCProtocolDecl *lhsProto = *I;
6496 bool match = false;
6497
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006498 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006499 // see if static class implements all of id's protocols, directly or
6500 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006501 // First, lhs protocols in the qualifier list must be found, direct
6502 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006503 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6504 E = rhsQID->qual_end(); J != E; ++J) {
6505 ObjCProtocolDecl *rhsProto = *J;
6506 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6507 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6508 match = true;
6509 break;
6510 }
6511 }
6512 if (!match)
6513 return false;
6514 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006515
6516 // Static class's protocols, or its super class or category protocols
6517 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6518 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6519 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6520 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6521 // This is rather dubious but matches gcc's behavior. If lhs has
6522 // no type qualifier and its class has no static protocol(s)
6523 // assume that it is mismatch.
6524 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6525 return false;
6526 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6527 LHSInheritedProtocols.begin(),
6528 E = LHSInheritedProtocols.end(); I != E; ++I) {
6529 bool match = false;
6530 ObjCProtocolDecl *lhsProto = (*I);
6531 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6532 E = rhsQID->qual_end(); J != E; ++J) {
6533 ObjCProtocolDecl *rhsProto = *J;
6534 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6535 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6536 match = true;
6537 break;
6538 }
6539 }
6540 if (!match)
6541 return false;
6542 }
6543 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006544 return true;
6545 }
6546 return false;
6547}
6548
Eli Friedman47f77112008-08-22 00:56:42 +00006549/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006550/// compatible for assignment from RHS to LHS. This handles validation of any
6551/// protocol qualifiers on the LHS or RHS.
6552///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006553bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6554 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006555 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6556 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6557
Steve Naroff1329fa02009-07-15 18:40:39 +00006558 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006559 if (LHS->isObjCUnqualifiedIdOrClass() ||
6560 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006561 return true;
6562
John McCall8b07ec22010-05-15 11:32:37 +00006563 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006564 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6565 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006566 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006567
6568 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6569 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6570 QualType(RHSOPT,0));
6571
John McCall8b07ec22010-05-15 11:32:37 +00006572 // If we have 2 user-defined types, fall into that path.
6573 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006574 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006575
Steve Naroff8e6aee52009-07-23 01:01:38 +00006576 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006577}
6578
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006579/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006580/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006581/// arguments in block literals. When passed as arguments, passing 'A*' where
6582/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6583/// not OK. For the return type, the opposite is not OK.
6584bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6585 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006586 const ObjCObjectPointerType *RHSOPT,
6587 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006588 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006589 return true;
6590
6591 if (LHSOPT->isObjCBuiltinType()) {
6592 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6593 }
6594
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006595 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006596 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6597 QualType(RHSOPT,0),
6598 false);
6599
6600 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6601 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6602 if (LHS && RHS) { // We have 2 user-defined types.
6603 if (LHS != RHS) {
6604 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006605 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006606 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006607 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006608 }
6609 else
6610 return true;
6611 }
6612 return false;
6613}
6614
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006615/// getIntersectionOfProtocols - This routine finds the intersection of set
6616/// of protocols inherited from two distinct objective-c pointer objects.
6617/// It is used to build composite qualifier list of the composite type of
6618/// the conditional expression involving two objective-c pointer objects.
6619static
6620void getIntersectionOfProtocols(ASTContext &Context,
6621 const ObjCObjectPointerType *LHSOPT,
6622 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006623 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006624
John McCall8b07ec22010-05-15 11:32:37 +00006625 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6626 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6627 assert(LHS->getInterface() && "LHS must have an interface base");
6628 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006629
6630 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6631 unsigned LHSNumProtocols = LHS->getNumProtocols();
6632 if (LHSNumProtocols > 0)
6633 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6634 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006635 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006636 Context.CollectInheritedProtocols(LHS->getInterface(),
6637 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006638 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6639 LHSInheritedProtocols.end());
6640 }
6641
6642 unsigned RHSNumProtocols = RHS->getNumProtocols();
6643 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006644 ObjCProtocolDecl **RHSProtocols =
6645 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006646 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6647 if (InheritedProtocolSet.count(RHSProtocols[i]))
6648 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006649 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006650 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006651 Context.CollectInheritedProtocols(RHS->getInterface(),
6652 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006653 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6654 RHSInheritedProtocols.begin(),
6655 E = RHSInheritedProtocols.end(); I != E; ++I)
6656 if (InheritedProtocolSet.count((*I)))
6657 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006658 }
6659}
6660
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006661/// areCommonBaseCompatible - Returns common base class of the two classes if
6662/// one found. Note that this is O'2 algorithm. But it will be called as the
6663/// last type comparison in a ?-exp of ObjC pointer types before a
6664/// warning is issued. So, its invokation is extremely rare.
6665QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006666 const ObjCObjectPointerType *Lptr,
6667 const ObjCObjectPointerType *Rptr) {
6668 const ObjCObjectType *LHS = Lptr->getObjectType();
6669 const ObjCObjectType *RHS = Rptr->getObjectType();
6670 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6671 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006672 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006673 return QualType();
6674
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006675 do {
John McCall8b07ec22010-05-15 11:32:37 +00006676 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006677 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006678 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006679 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6680
6681 QualType Result = QualType(LHS, 0);
6682 if (!Protocols.empty())
6683 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6684 Result = getObjCObjectPointerType(Result);
6685 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006686 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006687 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006688
6689 return QualType();
6690}
6691
John McCall8b07ec22010-05-15 11:32:37 +00006692bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6693 const ObjCObjectType *RHS) {
6694 assert(LHS->getInterface() && "LHS is not an interface type");
6695 assert(RHS->getInterface() && "RHS is not an interface type");
6696
Chris Lattner49af6a42008-04-07 06:51:04 +00006697 // Verify that the base decls are compatible: the RHS must be a subclass of
6698 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006699 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006700 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006701
Chris Lattner49af6a42008-04-07 06:51:04 +00006702 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6703 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006704 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006705 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006706
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006707 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6708 // more detailed analysis is required.
6709 if (RHS->getNumProtocols() == 0) {
6710 // OK, if LHS is a superclass of RHS *and*
6711 // this superclass is assignment compatible with LHS.
6712 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006713 bool IsSuperClass =
6714 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6715 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006716 // OK if conversion of LHS to SuperClass results in narrowing of types
6717 // ; i.e., SuperClass may implement at least one of the protocols
6718 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6719 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6720 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006721 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006722 // If super class has no protocols, it is not a match.
6723 if (SuperClassInheritedProtocols.empty())
6724 return false;
6725
6726 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6727 LHSPE = LHS->qual_end();
6728 LHSPI != LHSPE; LHSPI++) {
6729 bool SuperImplementsProtocol = false;
6730 ObjCProtocolDecl *LHSProto = (*LHSPI);
6731
6732 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6733 SuperClassInheritedProtocols.begin(),
6734 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6735 ObjCProtocolDecl *SuperClassProto = (*I);
6736 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6737 SuperImplementsProtocol = true;
6738 break;
6739 }
6740 }
6741 if (!SuperImplementsProtocol)
6742 return false;
6743 }
6744 return true;
6745 }
6746 return false;
6747 }
Mike Stump11289f42009-09-09 15:08:12 +00006748
John McCall8b07ec22010-05-15 11:32:37 +00006749 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6750 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006751 LHSPI != LHSPE; LHSPI++) {
6752 bool RHSImplementsProtocol = false;
6753
6754 // If the RHS doesn't implement the protocol on the left, the types
6755 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006756 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6757 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006758 RHSPI != RHSPE; RHSPI++) {
6759 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006760 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006761 break;
6762 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006763 }
6764 // FIXME: For better diagnostics, consider passing back the protocol name.
6765 if (!RHSImplementsProtocol)
6766 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006767 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006768 // The RHS implements all protocols listed on the LHS.
6769 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006770}
6771
Steve Naroffb7605152009-02-12 17:52:19 +00006772bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6773 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006774 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6775 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006776
Steve Naroff7cae42b2009-07-10 23:34:53 +00006777 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006778 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006779
6780 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6781 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006782}
6783
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006784bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6785 return canAssignObjCInterfaces(
6786 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6787 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6788}
6789
Mike Stump11289f42009-09-09 15:08:12 +00006790/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006791/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006792/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006793/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006794bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6795 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006796 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006797 return hasSameType(LHS, RHS);
6798
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006799 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006800}
6801
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006802bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006803 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006804}
6805
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006806bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6807 return !mergeTypes(LHS, RHS, true).isNull();
6808}
6809
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006810/// mergeTransparentUnionType - if T is a transparent union type and a member
6811/// of T is compatible with SubType, return the merged type, else return
6812/// QualType()
6813QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6814 bool OfBlockPointer,
6815 bool Unqualified) {
6816 if (const RecordType *UT = T->getAsUnionType()) {
6817 RecordDecl *UD = UT->getDecl();
6818 if (UD->hasAttr<TransparentUnionAttr>()) {
6819 for (RecordDecl::field_iterator it = UD->field_begin(),
6820 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006821 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006822 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6823 if (!MT.isNull())
6824 return MT;
6825 }
6826 }
6827 }
6828
6829 return QualType();
6830}
6831
6832/// mergeFunctionArgumentTypes - merge two types which appear as function
6833/// argument types
6834QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6835 bool OfBlockPointer,
6836 bool Unqualified) {
6837 // GNU extension: two types are compatible if they appear as a function
6838 // argument, one of the types is a transparent union type and the other
6839 // type is compatible with a union member
6840 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6841 Unqualified);
6842 if (!lmerge.isNull())
6843 return lmerge;
6844
6845 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6846 Unqualified);
6847 if (!rmerge.isNull())
6848 return rmerge;
6849
6850 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6851}
6852
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006853QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006854 bool OfBlockPointer,
6855 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006856 const FunctionType *lbase = lhs->getAs<FunctionType>();
6857 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006858 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6859 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006860 bool allLTypes = true;
6861 bool allRTypes = true;
6862
6863 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006864 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006865 if (OfBlockPointer) {
6866 QualType RHS = rbase->getResultType();
6867 QualType LHS = lbase->getResultType();
6868 bool UnqualifiedResult = Unqualified;
6869 if (!UnqualifiedResult)
6870 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006871 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006872 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006873 else
John McCall8c6b56f2010-12-15 01:06:38 +00006874 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6875 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006876 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006877
6878 if (Unqualified)
6879 retType = retType.getUnqualifiedType();
6880
6881 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6882 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6883 if (Unqualified) {
6884 LRetType = LRetType.getUnqualifiedType();
6885 RRetType = RRetType.getUnqualifiedType();
6886 }
6887
6888 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006889 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006890 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006891 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006892
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006893 // FIXME: double check this
6894 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6895 // rbase->getRegParmAttr() != 0 &&
6896 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006897 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6898 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006899
Douglas Gregor8c940862010-01-18 17:14:39 +00006900 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00006901 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00006902 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006903
John McCall8c6b56f2010-12-15 01:06:38 +00006904 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006905 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6906 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006907 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6908 return QualType();
6909
John McCall31168b02011-06-15 23:02:42 +00006910 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6911 return QualType();
6912
John McCall8c6b56f2010-12-15 01:06:38 +00006913 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6914 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006915
Rafael Espindola8778c282012-11-29 16:09:03 +00006916 if (lbaseInfo.getNoReturn() != NoReturn)
6917 allLTypes = false;
6918 if (rbaseInfo.getNoReturn() != NoReturn)
6919 allRTypes = false;
6920
John McCall31168b02011-06-15 23:02:42 +00006921 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006922
Eli Friedman47f77112008-08-22 00:56:42 +00006923 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006924 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6925 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006926 unsigned lproto_nargs = lproto->getNumArgs();
6927 unsigned rproto_nargs = rproto->getNumArgs();
6928
6929 // Compatible functions must have the same number of arguments
6930 if (lproto_nargs != rproto_nargs)
6931 return QualType();
6932
6933 // Variadic and non-variadic functions aren't compatible
6934 if (lproto->isVariadic() != rproto->isVariadic())
6935 return QualType();
6936
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006937 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6938 return QualType();
6939
Fariborz Jahanian97676972011-09-28 21:52:05 +00006940 if (LangOpts.ObjCAutoRefCount &&
6941 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6942 return QualType();
6943
Eli Friedman47f77112008-08-22 00:56:42 +00006944 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006945 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00006946 for (unsigned i = 0; i < lproto_nargs; i++) {
6947 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6948 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006949 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6950 OfBlockPointer,
6951 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006952 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006953
6954 if (Unqualified)
6955 argtype = argtype.getUnqualifiedType();
6956
Eli Friedman47f77112008-08-22 00:56:42 +00006957 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006958 if (Unqualified) {
6959 largtype = largtype.getUnqualifiedType();
6960 rargtype = rargtype.getUnqualifiedType();
6961 }
6962
Chris Lattner465fa322008-10-05 17:34:18 +00006963 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6964 allLTypes = false;
6965 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6966 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006967 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006968
Eli Friedman47f77112008-08-22 00:56:42 +00006969 if (allLTypes) return lhs;
6970 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006971
6972 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6973 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00006974 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006975 }
6976
6977 if (lproto) allRTypes = false;
6978 if (rproto) allLTypes = false;
6979
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006980 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006981 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006982 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006983 if (proto->isVariadic()) return QualType();
6984 // Check that the types are compatible with the types that
6985 // would result from default argument promotions (C99 6.7.5.3p15).
6986 // The only types actually affected are promotable integer
6987 // types and floats, which would be passed as a different
6988 // type depending on whether the prototype is visible.
6989 unsigned proto_nargs = proto->getNumArgs();
6990 for (unsigned i = 0; i < proto_nargs; ++i) {
6991 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00006992
Eli Friedman448ce402012-08-30 00:44:15 +00006993 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00006994 // to pass enum values.
Eli Friedman448ce402012-08-30 00:44:15 +00006995 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
6996 argTy = Enum->getDecl()->getIntegerType();
6997 if (argTy.isNull())
6998 return QualType();
6999 }
Douglas Gregor2973d402010-02-03 19:27:29 +00007000
Eli Friedman47f77112008-08-22 00:56:42 +00007001 if (argTy->isPromotableIntegerType() ||
7002 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
7003 return QualType();
7004 }
7005
7006 if (allLTypes) return lhs;
7007 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007008
7009 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7010 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007011 return getFunctionType(retType,
7012 ArrayRef<QualType>(proto->arg_type_begin(),
7013 proto->getNumArgs()),
7014 EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007015 }
7016
7017 if (allLTypes) return lhs;
7018 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007019 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007020}
7021
John McCall433c2e62013-03-21 00:10:07 +00007022/// Given that we have an enum type and a non-enum type, try to merge them.
7023static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7024 QualType other, bool isBlockReturnType) {
7025 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7026 // a signed integer type, or an unsigned integer type.
7027 // Compatibility is based on the underlying type, not the promotion
7028 // type.
7029 QualType underlyingType = ET->getDecl()->getIntegerType();
7030 if (underlyingType.isNull()) return QualType();
7031 if (Context.hasSameType(underlyingType, other))
7032 return other;
7033
7034 // In block return types, we're more permissive and accept any
7035 // integral type of the same size.
7036 if (isBlockReturnType && other->isIntegerType() &&
7037 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7038 return other;
7039
7040 return QualType();
7041}
7042
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007043QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007044 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007045 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007046 // C++ [expr]: If an expression initially has the type "reference to T", the
7047 // type is adjusted to "T" prior to any further analysis, the expression
7048 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007049 // expression is an lvalue unless the reference is an rvalue reference and
7050 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007051 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7052 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007053
7054 if (Unqualified) {
7055 LHS = LHS.getUnqualifiedType();
7056 RHS = RHS.getUnqualifiedType();
7057 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007058
Eli Friedman47f77112008-08-22 00:56:42 +00007059 QualType LHSCan = getCanonicalType(LHS),
7060 RHSCan = getCanonicalType(RHS);
7061
7062 // If two types are identical, they are compatible.
7063 if (LHSCan == RHSCan)
7064 return LHS;
7065
John McCall8ccfcb52009-09-24 19:53:00 +00007066 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007067 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7068 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007069 if (LQuals != RQuals) {
7070 // If any of these qualifiers are different, we have a type
7071 // mismatch.
7072 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007073 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7074 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007075 return QualType();
7076
7077 // Exactly one GC qualifier difference is allowed: __strong is
7078 // okay if the other type has no GC qualifier but is an Objective
7079 // C object pointer (i.e. implicitly strong by default). We fix
7080 // this by pretending that the unqualified type was actually
7081 // qualified __strong.
7082 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7083 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7084 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7085
7086 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7087 return QualType();
7088
7089 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7090 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7091 }
7092 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7093 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7094 }
Eli Friedman47f77112008-08-22 00:56:42 +00007095 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007096 }
7097
7098 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007099
Eli Friedmandcca6332009-06-01 01:22:52 +00007100 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7101 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007102
Chris Lattnerfd652912008-01-14 05:45:46 +00007103 // We want to consider the two function types to be the same for these
7104 // comparisons, just force one to the other.
7105 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7106 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007107
7108 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007109 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7110 LHSClass = Type::ConstantArray;
7111 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7112 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007113
John McCall8b07ec22010-05-15 11:32:37 +00007114 // ObjCInterfaces are just specialized ObjCObjects.
7115 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7116 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7117
Nate Begemance4d7fc2008-04-18 23:10:10 +00007118 // Canonicalize ExtVector -> Vector.
7119 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7120 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007121
Chris Lattner95554662008-04-07 05:43:21 +00007122 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007123 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007124 // Note that we only have special rules for turning block enum
7125 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007126 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007127 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007128 }
John McCall9dd450b2009-09-21 23:43:11 +00007129 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007130 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007131 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007132 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007133 if (OfBlockPointer && !BlockReturnType) {
7134 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7135 return LHS;
7136 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7137 return RHS;
7138 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007139
Eli Friedman47f77112008-08-22 00:56:42 +00007140 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007141 }
Eli Friedman47f77112008-08-22 00:56:42 +00007142
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007143 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007144 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007145#define TYPE(Class, Base)
7146#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007147#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007148#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7149#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7150#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007151 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007152
Richard Smith27d807c2013-04-30 13:56:41 +00007153 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007154 case Type::LValueReference:
7155 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007156 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007157 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007158
John McCall8b07ec22010-05-15 11:32:37 +00007159 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007160 case Type::IncompleteArray:
7161 case Type::VariableArray:
7162 case Type::FunctionProto:
7163 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007164 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007165
Chris Lattnerfd652912008-01-14 05:45:46 +00007166 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007167 {
7168 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007169 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7170 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007171 if (Unqualified) {
7172 LHSPointee = LHSPointee.getUnqualifiedType();
7173 RHSPointee = RHSPointee.getUnqualifiedType();
7174 }
7175 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7176 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007177 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007178 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007179 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007180 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007181 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007182 return getPointerType(ResultType);
7183 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007184 case Type::BlockPointer:
7185 {
7186 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007187 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7188 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007189 if (Unqualified) {
7190 LHSPointee = LHSPointee.getUnqualifiedType();
7191 RHSPointee = RHSPointee.getUnqualifiedType();
7192 }
7193 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7194 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007195 if (ResultType.isNull()) return QualType();
7196 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7197 return LHS;
7198 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7199 return RHS;
7200 return getBlockPointerType(ResultType);
7201 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007202 case Type::Atomic:
7203 {
7204 // Merge two pointer types, while trying to preserve typedef info
7205 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7206 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7207 if (Unqualified) {
7208 LHSValue = LHSValue.getUnqualifiedType();
7209 RHSValue = RHSValue.getUnqualifiedType();
7210 }
7211 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7212 Unqualified);
7213 if (ResultType.isNull()) return QualType();
7214 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7215 return LHS;
7216 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7217 return RHS;
7218 return getAtomicType(ResultType);
7219 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007220 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007221 {
7222 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7223 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7224 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7225 return QualType();
7226
7227 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7228 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007229 if (Unqualified) {
7230 LHSElem = LHSElem.getUnqualifiedType();
7231 RHSElem = RHSElem.getUnqualifiedType();
7232 }
7233
7234 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007235 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007236 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7237 return LHS;
7238 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7239 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007240 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7241 ArrayType::ArraySizeModifier(), 0);
7242 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7243 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007244 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7245 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007246 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7247 return LHS;
7248 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7249 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007250 if (LVAT) {
7251 // FIXME: This isn't correct! But tricky to implement because
7252 // the array's size has to be the size of LHS, but the type
7253 // has to be different.
7254 return LHS;
7255 }
7256 if (RVAT) {
7257 // FIXME: This isn't correct! But tricky to implement because
7258 // the array's size has to be the size of RHS, but the type
7259 // has to be different.
7260 return RHS;
7261 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007262 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7263 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007264 return getIncompleteArrayType(ResultType,
7265 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007266 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007267 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007268 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007269 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007270 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007271 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007272 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007273 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007274 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007275 case Type::Complex:
7276 // Distinct complex types are incompatible.
7277 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007278 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007279 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007280 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7281 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007282 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007283 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007284 case Type::ObjCObject: {
7285 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007286 // FIXME: This should be type compatibility, e.g. whether
7287 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007288 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7289 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7290 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007291 return LHS;
7292
Eli Friedman47f77112008-08-22 00:56:42 +00007293 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007294 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007295 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007296 if (OfBlockPointer) {
7297 if (canAssignObjCInterfacesInBlockPointer(
7298 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007299 RHS->getAs<ObjCObjectPointerType>(),
7300 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007301 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007302 return QualType();
7303 }
John McCall9dd450b2009-09-21 23:43:11 +00007304 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7305 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007306 return LHS;
7307
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007308 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007309 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007310 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007311
David Blaikie8a40f702012-01-17 06:56:22 +00007312 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007313}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007314
Fariborz Jahanian97676972011-09-28 21:52:05 +00007315bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7316 const FunctionProtoType *FromFunctionType,
7317 const FunctionProtoType *ToFunctionType) {
7318 if (FromFunctionType->hasAnyConsumedArgs() !=
7319 ToFunctionType->hasAnyConsumedArgs())
7320 return false;
7321 FunctionProtoType::ExtProtoInfo FromEPI =
7322 FromFunctionType->getExtProtoInfo();
7323 FunctionProtoType::ExtProtoInfo ToEPI =
7324 ToFunctionType->getExtProtoInfo();
7325 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
7326 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
7327 ArgIdx != NumArgs; ++ArgIdx) {
7328 if (FromEPI.ConsumedArguments[ArgIdx] !=
7329 ToEPI.ConsumedArguments[ArgIdx])
7330 return false;
7331 }
7332 return true;
7333}
7334
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007335/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7336/// 'RHS' attributes and returns the merged version; including for function
7337/// return types.
7338QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7339 QualType LHSCan = getCanonicalType(LHS),
7340 RHSCan = getCanonicalType(RHS);
7341 // If two types are identical, they are compatible.
7342 if (LHSCan == RHSCan)
7343 return LHS;
7344 if (RHSCan->isFunctionType()) {
7345 if (!LHSCan->isFunctionType())
7346 return QualType();
7347 QualType OldReturnType =
7348 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7349 QualType NewReturnType =
7350 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7351 QualType ResReturnType =
7352 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7353 if (ResReturnType.isNull())
7354 return QualType();
7355 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7356 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7357 // In either case, use OldReturnType to build the new function type.
7358 const FunctionType *F = LHS->getAs<FunctionType>();
7359 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007360 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7361 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007362 QualType ResultType
Jordan Rose5c382722013-03-08 21:51:21 +00007363 = getFunctionType(OldReturnType,
7364 ArrayRef<QualType>(FPT->arg_type_begin(),
7365 FPT->getNumArgs()),
7366 EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007367 return ResultType;
7368 }
7369 }
7370 return QualType();
7371 }
7372
7373 // If the qualifiers are different, the types can still be merged.
7374 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7375 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7376 if (LQuals != RQuals) {
7377 // If any of these qualifiers are different, we have a type mismatch.
7378 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7379 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7380 return QualType();
7381
7382 // Exactly one GC qualifier difference is allowed: __strong is
7383 // okay if the other type has no GC qualifier but is an Objective
7384 // C object pointer (i.e. implicitly strong by default). We fix
7385 // this by pretending that the unqualified type was actually
7386 // qualified __strong.
7387 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7388 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7389 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7390
7391 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7392 return QualType();
7393
7394 if (GC_L == Qualifiers::Strong)
7395 return LHS;
7396 if (GC_R == Qualifiers::Strong)
7397 return RHS;
7398 return QualType();
7399 }
7400
7401 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7402 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7403 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7404 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7405 if (ResQT == LHSBaseQT)
7406 return LHS;
7407 if (ResQT == RHSBaseQT)
7408 return RHS;
7409 }
7410 return QualType();
7411}
7412
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007413//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007414// Integer Predicates
7415//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007416
Jay Foad39c79802011-01-12 09:06:06 +00007417unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00007418 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00007419 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007420 if (T->isBooleanType())
7421 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007422 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007423 return (unsigned)getTypeSize(T);
7424}
7425
Abramo Bagnara13640492012-09-09 10:21:24 +00007426QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007427 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007428
7429 // Turn <4 x signed int> -> <4 x unsigned int>
7430 if (const VectorType *VTy = T->getAs<VectorType>())
7431 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007432 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007433
7434 // For enums, we return the unsigned version of the base type.
7435 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007436 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007437
7438 const BuiltinType *BTy = T->getAs<BuiltinType>();
7439 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007440 switch (BTy->getKind()) {
7441 case BuiltinType::Char_S:
7442 case BuiltinType::SChar:
7443 return UnsignedCharTy;
7444 case BuiltinType::Short:
7445 return UnsignedShortTy;
7446 case BuiltinType::Int:
7447 return UnsignedIntTy;
7448 case BuiltinType::Long:
7449 return UnsignedLongTy;
7450 case BuiltinType::LongLong:
7451 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007452 case BuiltinType::Int128:
7453 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007454 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007455 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007456 }
7457}
7458
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007459ASTMutationListener::~ASTMutationListener() { }
7460
Chris Lattnerecd79c62009-06-14 00:45:47 +00007461
7462//===----------------------------------------------------------------------===//
7463// Builtin Type Computation
7464//===----------------------------------------------------------------------===//
7465
7466/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007467/// pointer over the consumed characters. This returns the resultant type. If
7468/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7469/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7470/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007471///
7472/// RequiresICE is filled in on return to indicate whether the value is required
7473/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007474static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007475 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007476 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007477 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007478 // Modifiers.
7479 int HowLong = 0;
7480 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007481 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007482
Chris Lattnerdc226c22010-10-01 22:42:38 +00007483 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007484 bool Done = false;
7485 while (!Done) {
7486 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007487 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007488 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007489 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007490 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007491 case 'S':
7492 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7493 assert(!Signed && "Can't use 'S' modifier multiple times!");
7494 Signed = true;
7495 break;
7496 case 'U':
7497 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7498 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7499 Unsigned = true;
7500 break;
7501 case 'L':
7502 assert(HowLong <= 2 && "Can't have LLLL modifier");
7503 ++HowLong;
7504 break;
7505 }
7506 }
7507
7508 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007509
Chris Lattnerecd79c62009-06-14 00:45:47 +00007510 // Read the base type.
7511 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007512 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007513 case 'v':
7514 assert(HowLong == 0 && !Signed && !Unsigned &&
7515 "Bad modifiers used with 'v'!");
7516 Type = Context.VoidTy;
7517 break;
7518 case 'f':
7519 assert(HowLong == 0 && !Signed && !Unsigned &&
7520 "Bad modifiers used with 'f'!");
7521 Type = Context.FloatTy;
7522 break;
7523 case 'd':
7524 assert(HowLong < 2 && !Signed && !Unsigned &&
7525 "Bad modifiers used with 'd'!");
7526 if (HowLong)
7527 Type = Context.LongDoubleTy;
7528 else
7529 Type = Context.DoubleTy;
7530 break;
7531 case 's':
7532 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7533 if (Unsigned)
7534 Type = Context.UnsignedShortTy;
7535 else
7536 Type = Context.ShortTy;
7537 break;
7538 case 'i':
7539 if (HowLong == 3)
7540 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7541 else if (HowLong == 2)
7542 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7543 else if (HowLong == 1)
7544 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7545 else
7546 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7547 break;
7548 case 'c':
7549 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7550 if (Signed)
7551 Type = Context.SignedCharTy;
7552 else if (Unsigned)
7553 Type = Context.UnsignedCharTy;
7554 else
7555 Type = Context.CharTy;
7556 break;
7557 case 'b': // boolean
7558 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7559 Type = Context.BoolTy;
7560 break;
7561 case 'z': // size_t.
7562 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7563 Type = Context.getSizeType();
7564 break;
7565 case 'F':
7566 Type = Context.getCFConstantStringType();
7567 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007568 case 'G':
7569 Type = Context.getObjCIdType();
7570 break;
7571 case 'H':
7572 Type = Context.getObjCSelType();
7573 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007574 case 'M':
7575 Type = Context.getObjCSuperType();
7576 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007577 case 'a':
7578 Type = Context.getBuiltinVaListType();
7579 assert(!Type.isNull() && "builtin va list type not initialized!");
7580 break;
7581 case 'A':
7582 // This is a "reference" to a va_list; however, what exactly
7583 // this means depends on how va_list is defined. There are two
7584 // different kinds of va_list: ones passed by value, and ones
7585 // passed by reference. An example of a by-value va_list is
7586 // x86, where va_list is a char*. An example of by-ref va_list
7587 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7588 // we want this argument to be a char*&; for x86-64, we want
7589 // it to be a __va_list_tag*.
7590 Type = Context.getBuiltinVaListType();
7591 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007592 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007593 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007594 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007595 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007596 break;
7597 case 'V': {
7598 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007599 unsigned NumElements = strtoul(Str, &End, 10);
7600 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007601 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007602
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007603 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7604 RequiresICE, false);
7605 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007606
7607 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007608 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007609 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007610 break;
7611 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007612 case 'E': {
7613 char *End;
7614
7615 unsigned NumElements = strtoul(Str, &End, 10);
7616 assert(End != Str && "Missing vector size");
7617
7618 Str = End;
7619
7620 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7621 false);
7622 Type = Context.getExtVectorType(ElementType, NumElements);
7623 break;
7624 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007625 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007626 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7627 false);
7628 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007629 Type = Context.getComplexType(ElementType);
7630 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007631 }
7632 case 'Y' : {
7633 Type = Context.getPointerDiffType();
7634 break;
7635 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007636 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007637 Type = Context.getFILEType();
7638 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007639 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007640 return QualType();
7641 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007642 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007643 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007644 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007645 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007646 else
7647 Type = Context.getjmp_bufType();
7648
Mike Stump2adb4da2009-07-28 23:47:15 +00007649 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007650 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007651 return QualType();
7652 }
7653 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007654 case 'K':
7655 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7656 Type = Context.getucontext_tType();
7657
7658 if (Type.isNull()) {
7659 Error = ASTContext::GE_Missing_ucontext;
7660 return QualType();
7661 }
7662 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007663 case 'p':
7664 Type = Context.getProcessIDType();
7665 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007666 }
Mike Stump11289f42009-09-09 15:08:12 +00007667
Chris Lattnerdc226c22010-10-01 22:42:38 +00007668 // If there are modifiers and if we're allowed to parse them, go for it.
7669 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007670 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007671 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007672 default: Done = true; --Str; break;
7673 case '*':
7674 case '&': {
7675 // Both pointers and references can have their pointee types
7676 // qualified with an address space.
7677 char *End;
7678 unsigned AddrSpace = strtoul(Str, &End, 10);
7679 if (End != Str && AddrSpace != 0) {
7680 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7681 Str = End;
7682 }
7683 if (c == '*')
7684 Type = Context.getPointerType(Type);
7685 else
7686 Type = Context.getLValueReferenceType(Type);
7687 break;
7688 }
7689 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7690 case 'C':
7691 Type = Type.withConst();
7692 break;
7693 case 'D':
7694 Type = Context.getVolatileType(Type);
7695 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007696 case 'R':
7697 Type = Type.withRestrict();
7698 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007699 }
7700 }
Chris Lattner84733392010-10-01 07:13:18 +00007701
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007702 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007703 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007704
Chris Lattnerecd79c62009-06-14 00:45:47 +00007705 return Type;
7706}
7707
7708/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007709QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007710 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007711 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007712 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007713
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007714 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007715
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007716 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007717 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007718 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7719 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007720 if (Error != GE_None)
7721 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007722
7723 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7724
Chris Lattnerecd79c62009-06-14 00:45:47 +00007725 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007726 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007727 if (Error != GE_None)
7728 return QualType();
7729
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007730 // If this argument is required to be an IntegerConstantExpression and the
7731 // caller cares, fill in the bitmask we return.
7732 if (RequiresICE && IntegerConstantArgs)
7733 *IntegerConstantArgs |= 1 << ArgTypes.size();
7734
Chris Lattnerecd79c62009-06-14 00:45:47 +00007735 // Do array -> pointer decay. The builtin should use the decayed type.
7736 if (Ty->isArrayType())
7737 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007738
Chris Lattnerecd79c62009-06-14 00:45:47 +00007739 ArgTypes.push_back(Ty);
7740 }
7741
7742 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7743 "'.' should only occur at end of builtin type list!");
7744
John McCall991eb4b2010-12-21 00:44:39 +00007745 FunctionType::ExtInfo EI;
7746 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7747
7748 bool Variadic = (TypeStr[0] == '.');
7749
7750 // We really shouldn't be making a no-proto type here, especially in C++.
7751 if (ArgTypes.empty() && Variadic)
7752 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007753
John McCalldb40c7f2010-12-14 08:05:40 +00007754 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007755 EPI.ExtInfo = EI;
7756 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007757
Jordan Rose5c382722013-03-08 21:51:21 +00007758 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007759}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007760
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007761GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
7762 GVALinkage External = GVA_StrongExternal;
7763
7764 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007765 switch (L) {
7766 case NoLinkage:
7767 case InternalLinkage:
7768 case UniqueExternalLinkage:
7769 return GVA_Internal;
7770
7771 case ExternalLinkage:
7772 switch (FD->getTemplateSpecializationKind()) {
7773 case TSK_Undeclared:
7774 case TSK_ExplicitSpecialization:
7775 External = GVA_StrongExternal;
7776 break;
7777
7778 case TSK_ExplicitInstantiationDefinition:
7779 return GVA_ExplicitTemplateInstantiation;
7780
7781 case TSK_ExplicitInstantiationDeclaration:
7782 case TSK_ImplicitInstantiation:
7783 External = GVA_TemplateInstantiation;
7784 break;
7785 }
7786 }
7787
7788 if (!FD->isInlined())
7789 return External;
7790
David Blaikiebbafb8a2012-03-11 07:00:24 +00007791 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007792 // GNU or C99 inline semantics. Determine whether this symbol should be
7793 // externally visible.
7794 if (FD->isInlineDefinitionExternallyVisible())
7795 return External;
7796
7797 // C99 inline semantics, where the symbol is not externally visible.
7798 return GVA_C99Inline;
7799 }
7800
7801 // C++0x [temp.explicit]p9:
7802 // [ Note: The intent is that an inline function that is the subject of
7803 // an explicit instantiation declaration will still be implicitly
7804 // instantiated when used so that the body can be considered for
7805 // inlining, but that no out-of-line copy of the inline function would be
7806 // generated in the translation unit. -- end note ]
7807 if (FD->getTemplateSpecializationKind()
7808 == TSK_ExplicitInstantiationDeclaration)
7809 return GVA_C99Inline;
7810
7811 return GVA_CXXInline;
7812}
7813
7814GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7815 // If this is a static data member, compute the kind of template
7816 // specialization. Otherwise, this variable is not part of a
7817 // template.
7818 TemplateSpecializationKind TSK = TSK_Undeclared;
7819 if (VD->isStaticDataMember())
7820 TSK = VD->getTemplateSpecializationKind();
7821
7822 Linkage L = VD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007823
7824 switch (L) {
7825 case NoLinkage:
7826 case InternalLinkage:
7827 case UniqueExternalLinkage:
7828 return GVA_Internal;
7829
7830 case ExternalLinkage:
7831 switch (TSK) {
7832 case TSK_Undeclared:
7833 case TSK_ExplicitSpecialization:
7834 return GVA_StrongExternal;
7835
7836 case TSK_ExplicitInstantiationDeclaration:
7837 llvm_unreachable("Variable should not be instantiated");
7838 // Fall through to treat this like any other instantiation.
7839
7840 case TSK_ExplicitInstantiationDefinition:
7841 return GVA_ExplicitTemplateInstantiation;
7842
7843 case TSK_ImplicitInstantiation:
7844 return GVA_TemplateInstantiation;
7845 }
7846 }
7847
David Blaikie8a40f702012-01-17 06:56:22 +00007848 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007849}
7850
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007851bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007852 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7853 if (!VD->isFileVarDecl())
7854 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00007855 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7856 // We never need to emit an uninstantiated function template.
7857 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7858 return false;
7859 } else
7860 return false;
7861
7862 // If this is a member of a class template, we do not need to emit it.
7863 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007864 return false;
7865
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007866 // Weak references don't produce any output by themselves.
7867 if (D->hasAttr<WeakRefAttr>())
7868 return false;
7869
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007870 // Aliases and used decls are required.
7871 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7872 return true;
7873
7874 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7875 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007876 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007877 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007878
7879 // Constructors and destructors are required.
7880 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7881 return true;
7882
John McCall6bd2a892013-01-25 22:31:03 +00007883 // The key function for a class is required. This rule only comes
7884 // into play when inline functions can be key functions, though.
7885 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7886 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7887 const CXXRecordDecl *RD = MD->getParent();
7888 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7889 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7890 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7891 return true;
7892 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007893 }
7894 }
7895
7896 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7897
7898 // static, static inline, always_inline, and extern inline functions can
7899 // always be deferred. Normal inline functions can be deferred in C99/C++.
7900 // Implicit template instantiations can also be deferred in C++.
7901 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007902 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007903 return false;
7904 return true;
7905 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007906
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007907 const VarDecl *VD = cast<VarDecl>(D);
7908 assert(VD->isFileVarDecl() && "Expected file scoped var");
7909
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007910 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7911 return false;
7912
Richard Smitha0e5e542012-11-12 21:38:00 +00007913 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007914 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smitha0e5e542012-11-12 21:38:00 +00007915 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7916 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007917
Richard Smitha0e5e542012-11-12 21:38:00 +00007918 // Variables that have destruction with side-effects are required.
7919 if (VD->getType().isDestructedType())
7920 return true;
7921
7922 // Variables that have initialization with side-effects are required.
7923 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7924 return true;
7925
7926 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007927}
Charles Davis53c59df2010-08-16 03:33:14 +00007928
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007929CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davis99202b32010-11-09 18:04:24 +00007930 // Pass through to the C++ ABI object
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007931 return ABI->getDefaultMethodCallConv(isVariadic);
7932}
7933
7934CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
John McCall359b8852013-01-25 22:30:49 +00007935 if (CC == CC_C && !LangOpts.MRTD &&
7936 getTargetInfo().getCXXABI().isMemberFunctionCCDefault())
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007937 return CC_Default;
7938 return CC;
Charles Davis99202b32010-11-09 18:04:24 +00007939}
7940
Jay Foad39c79802011-01-12 09:06:06 +00007941bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007942 // Pass through to the C++ ABI object
7943 return ABI->isNearlyEmpty(RD);
7944}
7945
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007946MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00007947 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00007948 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00007949 case TargetCXXABI::GenericItanium:
7950 case TargetCXXABI::GenericARM:
7951 case TargetCXXABI::iOS:
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007952 return createItaniumMangleContext(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00007953 case TargetCXXABI::Microsoft:
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007954 return createMicrosoftMangleContext(*this, getDiagnostics());
7955 }
David Blaikie83d382b2011-09-23 05:06:16 +00007956 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007957}
7958
Charles Davis53c59df2010-08-16 03:33:14 +00007959CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007960
7961size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00007962 return ASTRecordLayouts.getMemorySize()
7963 + llvm::capacity_in_bytes(ObjCLayouts)
7964 + llvm::capacity_in_bytes(KeyFunctions)
7965 + llvm::capacity_in_bytes(ObjCImpls)
7966 + llvm::capacity_in_bytes(BlockVarCopyInits)
7967 + llvm::capacity_in_bytes(DeclAttrs)
7968 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7969 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7970 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7971 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7972 + llvm::capacity_in_bytes(OverriddenMethods)
7973 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007974 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00007975 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007976}
Ted Kremenek540017e2011-10-06 05:00:56 +00007977
David Blaikie095deba2012-11-14 01:52:05 +00007978void ASTContext::addUnnamedTag(const TagDecl *Tag) {
7979 // FIXME: This mangling should be applied to function local classes too
7980 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl() ||
7981 !isa<CXXRecordDecl>(Tag->getParent()) || Tag->getLinkage() != ExternalLinkage)
7982 return;
7983
7984 std::pair<llvm::DenseMap<const DeclContext *, unsigned>::iterator, bool> P =
7985 UnnamedMangleContexts.insert(std::make_pair(Tag->getParent(), 0));
7986 UnnamedMangleNumbers.insert(std::make_pair(Tag, P.first->second++));
7987}
7988
7989int ASTContext::getUnnamedTagManglingNumber(const TagDecl *Tag) const {
7990 llvm::DenseMap<const TagDecl *, unsigned>::const_iterator I =
7991 UnnamedMangleNumbers.find(Tag);
7992 return I != UnnamedMangleNumbers.end() ? I->second : -1;
7993}
7994
Douglas Gregor63798542012-02-20 19:44:39 +00007995unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7996 CXXRecordDecl *Lambda = CallOperator->getParent();
7997 return LambdaMangleContexts[Lambda->getDeclContext()]
7998 .getManglingNumber(CallOperator);
7999}
8000
8001
Ted Kremenek540017e2011-10-06 05:00:56 +00008002void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8003 ParamIndices[D] = index;
8004}
8005
8006unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8007 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8008 assert(I != ParamIndices.end() &&
8009 "ParmIndices lacks entry set by ParmVarDecl");
8010 return I->second;
8011}