blob: b827dc1080aea38a1f62068b44a52e4c2e25d337 [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 Wennborgcadd77c2013-05-03 09:10:16 +0000900 if ((LangOpts.CPlusPlus && LangOpts.WChar) || LangOpts.MicrosoftMode) {
901 // C++ 3.9.1p5 or -fms-compatibility.
Eli Friedman786d0872011-04-30 19:24:24 +0000902 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000903 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
904 else // -fshort-wchar makes wchar_t be unsigned.
905 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
Hans Wennborgcadd77c2013-05-03 09:10:16 +0000906 } else // C99 (or C++ using -fno-wchar) in non-MicrosoftMode.
Chris Lattner007cb022009-02-26 23:43:47 +0000907 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000908
James Molloy36365542012-05-04 10:55:22 +0000909 WIntTy = getFromTargetType(Target.getWIntType());
910
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000911 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
912 InitBuiltinType(Char16Ty, BuiltinType::Char16);
913 else // C99
914 Char16Ty = getFromTargetType(Target.getChar16Type());
915
916 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
917 InitBuiltinType(Char32Ty, BuiltinType::Char32);
918 else // C99
919 Char32Ty = getFromTargetType(Target.getChar32Type());
920
Douglas Gregor4619e432008-12-05 23:32:09 +0000921 // Placeholder type for type-dependent expressions whose type is
922 // completely unknown. No code should ever check a type against
923 // DependentTy and users should never see it; however, it is here to
924 // help diagnose failures to properly check for type-dependent
925 // expressions.
926 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000927
John McCall36e7fe32010-10-12 00:20:44 +0000928 // Placeholder type for functions.
929 InitBuiltinType(OverloadTy, BuiltinType::Overload);
930
John McCall0009fcc2011-04-26 20:42:42 +0000931 // Placeholder type for bound members.
932 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
933
John McCall526ab472011-10-25 17:37:35 +0000934 // Placeholder type for pseudo-objects.
935 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
936
John McCall31996342011-04-07 08:22:57 +0000937 // "any" type; useful for debugger-like clients.
938 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
939
John McCall8a6b59a2011-10-17 18:09:15 +0000940 // Placeholder type for unbridged ARC casts.
941 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
942
Eli Friedman34866c72012-08-31 00:14:07 +0000943 // Placeholder type for builtin functions.
944 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
945
Chris Lattner970e54e2006-11-12 00:37:36 +0000946 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000947 FloatComplexTy = getComplexType(FloatTy);
948 DoubleComplexTy = getComplexType(DoubleTy);
949 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000950
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000951 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000952 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
953 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000954 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000955
956 if (LangOpts.OpenCL) {
957 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
958 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
959 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
960 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
961 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
962 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000963
Guy Benyei61054192013-02-07 10:55:47 +0000964 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000965 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000966 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000967
968 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000969 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
970 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000971
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000972 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +0000973
974 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000975
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000976 // void * type
977 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000978
979 // nullptr type (C++0x 2.14.7)
980 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000981
982 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
983 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +0000984
985 // Builtin type used to help define __builtin_va_list.
986 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +0000987}
988
David Blaikie9c902b52011-09-25 23:23:43 +0000989DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000990 return SourceMgr.getDiagnostics();
991}
992
Douglas Gregor561eceb2010-08-30 16:49:28 +0000993AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
994 AttrVec *&Result = DeclAttrs[D];
995 if (!Result) {
996 void *Mem = Allocate(sizeof(AttrVec));
997 Result = new (Mem) AttrVec;
998 }
999
1000 return *Result;
1001}
1002
1003/// \brief Erase the attributes corresponding to the given declaration.
1004void ASTContext::eraseDeclAttrs(const Decl *D) {
1005 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1006 if (Pos != DeclAttrs.end()) {
1007 Pos->second->~AttrVec();
1008 DeclAttrs.erase(Pos);
1009 }
1010}
1011
Douglas Gregor86d142a2009-10-08 07:24:58 +00001012MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001013ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001014 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +00001015 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001016 = InstantiatedFromStaticDataMember.find(Var);
1017 if (Pos == InstantiatedFromStaticDataMember.end())
1018 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001019
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001020 return Pos->second;
1021}
1022
Mike Stump11289f42009-09-09 15:08:12 +00001023void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001024ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001025 TemplateSpecializationKind TSK,
1026 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001027 assert(Inst->isStaticDataMember() && "Not a static data member");
1028 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1029 assert(!InstantiatedFromStaticDataMember[Inst] &&
1030 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +00001031 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001032 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001033}
1034
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001035FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1036 const FunctionDecl *FD){
1037 assert(FD && "Specialization is 0");
1038 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001039 = ClassScopeSpecializationPattern.find(FD);
1040 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001041 return 0;
1042
1043 return Pos->second;
1044}
1045
1046void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1047 FunctionDecl *Pattern) {
1048 assert(FD && "Specialization is 0");
1049 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001050 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001051}
1052
John McCalle61f2ba2009-11-18 02:36:19 +00001053NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001054ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001055 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001056 = InstantiatedFromUsingDecl.find(UUD);
1057 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001058 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001059
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001060 return Pos->second;
1061}
1062
1063void
John McCallb96ec562009-12-04 22:46:56 +00001064ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1065 assert((isa<UsingDecl>(Pattern) ||
1066 isa<UnresolvedUsingValueDecl>(Pattern) ||
1067 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1068 "pattern decl is not a using decl");
1069 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1070 InstantiatedFromUsingDecl[Inst] = Pattern;
1071}
1072
1073UsingShadowDecl *
1074ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1075 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1076 = InstantiatedFromUsingShadowDecl.find(Inst);
1077 if (Pos == InstantiatedFromUsingShadowDecl.end())
1078 return 0;
1079
1080 return Pos->second;
1081}
1082
1083void
1084ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1085 UsingShadowDecl *Pattern) {
1086 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1087 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001088}
1089
Anders Carlsson5da84842009-09-01 04:26:58 +00001090FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1091 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1092 = InstantiatedFromUnnamedFieldDecl.find(Field);
1093 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1094 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001095
Anders Carlsson5da84842009-09-01 04:26:58 +00001096 return Pos->second;
1097}
1098
1099void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1100 FieldDecl *Tmpl) {
1101 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1102 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1103 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1104 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001105
Anders Carlsson5da84842009-09-01 04:26:58 +00001106 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1107}
1108
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +00001109bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
1110 const FieldDecl *LastFD) const {
1111 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001112 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +00001113}
1114
Fariborz Jahanianeb397412011-05-02 17:20:56 +00001115bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
1116 const FieldDecl *LastFD) const {
1117 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001118 FD->getBitWidthValue(*this) == 0 &&
1119 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +00001120}
1121
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001122bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
1123 const FieldDecl *LastFD) const {
1124 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001125 FD->getBitWidthValue(*this) &&
1126 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001127}
1128
Chad Rosierf01a7dd2011-08-04 23:34:15 +00001129bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001130 const FieldDecl *LastFD) const {
1131 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001132 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001133}
1134
Chad Rosierf01a7dd2011-08-04 23:34:15 +00001135bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001136 const FieldDecl *LastFD) const {
1137 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001138 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001139}
1140
Douglas Gregor832940b2010-03-02 23:58:15 +00001141ASTContext::overridden_cxx_method_iterator
1142ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1143 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001144 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001145 if (Pos == OverriddenMethods.end())
1146 return 0;
1147
1148 return Pos->second.begin();
1149}
1150
1151ASTContext::overridden_cxx_method_iterator
1152ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1153 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001154 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001155 if (Pos == OverriddenMethods.end())
1156 return 0;
1157
1158 return Pos->second.end();
1159}
1160
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001161unsigned
1162ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1163 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001164 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001165 if (Pos == OverriddenMethods.end())
1166 return 0;
1167
1168 return Pos->second.size();
1169}
1170
Douglas Gregor832940b2010-03-02 23:58:15 +00001171void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1172 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001173 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001174 OverriddenMethods[Method].push_back(Overridden);
1175}
1176
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001177void ASTContext::getOverriddenMethods(
1178 const NamedDecl *D,
1179 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001180 assert(D);
1181
1182 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001183 Overridden.append(overridden_methods_begin(CXXMethod),
1184 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001185 return;
1186 }
1187
1188 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1189 if (!Method)
1190 return;
1191
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001192 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1193 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001194 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001195}
1196
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001197void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1198 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1199 assert(!Import->isFromASTFile() && "Non-local import declaration");
1200 if (!FirstLocalImport) {
1201 FirstLocalImport = Import;
1202 LastLocalImport = Import;
1203 return;
1204 }
1205
1206 LastLocalImport->NextLocalImport = Import;
1207 LastLocalImport = Import;
1208}
1209
Chris Lattner53cfe802007-07-18 17:52:12 +00001210//===----------------------------------------------------------------------===//
1211// Type Sizing and Analysis
1212//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001213
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001214/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1215/// scalar floating point type.
1216const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001217 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001218 assert(BT && "Not a floating point type!");
1219 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001220 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001221 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001222 case BuiltinType::Float: return Target->getFloatFormat();
1223 case BuiltinType::Double: return Target->getDoubleFormat();
1224 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001225 }
1226}
1227
Ken Dyck160146e2010-01-27 17:10:57 +00001228/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +00001229/// specified decl. Note that bitfields do not have a valid alignment, so
1230/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001231/// If @p RefAsPointee, references are treated like their underlying type
1232/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +00001233CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001234 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001235
John McCall94268702010-10-08 18:24:19 +00001236 bool UseAlignAttrOnly = false;
1237 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1238 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001239
John McCall94268702010-10-08 18:24:19 +00001240 // __attribute__((aligned)) can increase or decrease alignment
1241 // *except* on a struct or struct member, where it only increases
1242 // alignment unless 'packed' is also specified.
1243 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001244 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001245 // ignore that possibility; Sema should diagnose it.
1246 if (isa<FieldDecl>(D)) {
1247 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1248 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1249 } else {
1250 UseAlignAttrOnly = true;
1251 }
1252 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001253 else if (isa<FieldDecl>(D))
1254 UseAlignAttrOnly =
1255 D->hasAttr<PackedAttr>() ||
1256 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001257
John McCall4e819612011-01-20 07:57:12 +00001258 // If we're using the align attribute only, just ignore everything
1259 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001260 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001261 // do nothing
1262
John McCall94268702010-10-08 18:24:19 +00001263 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001264 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001265 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001266 if (RefAsPointee)
1267 T = RT->getPointeeType();
1268 else
1269 T = getPointerType(RT->getPointeeType());
1270 }
1271 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001272 // Adjust alignments of declarations with array type by the
1273 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +00001274 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +00001275 const ArrayType *arrayType;
1276 if (MinWidth && (arrayType = getAsArrayType(T))) {
1277 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001278 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +00001279 else if (isa<ConstantArrayType>(arrayType) &&
1280 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001281 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +00001282
John McCall33ddac02011-01-19 10:06:00 +00001283 // Walk through any array types while we're at it.
1284 T = getBaseElementType(arrayType);
1285 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001286 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +00001287 }
John McCall4e819612011-01-20 07:57:12 +00001288
1289 // Fields can be subject to extra alignment constraints, like if
1290 // the field is packed, the struct is packed, or the struct has a
1291 // a max-field-alignment constraint (#pragma pack). So calculate
1292 // the actual alignment of the field within the struct, and then
1293 // (as we're expected to) constrain that by the alignment of the type.
1294 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1295 // So calculate the alignment of the field.
1296 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1297
1298 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +00001299 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001300
1301 // Use the GCD of that and the offset within the record.
1302 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1303 if (offset > 0) {
1304 // Alignment is always a power of 2, so the GCD will be a power of 2,
1305 // which means we get to do this crazy thing instead of Euclid's.
1306 uint64_t lowBitOfOffset = offset & (~offset + 1);
1307 if (lowBitOfOffset < fieldAlign)
1308 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1309 }
1310
1311 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +00001312 }
Chris Lattner68061312009-01-24 21:53:27 +00001313 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001314
Ken Dyckcc56c542011-01-15 18:38:59 +00001315 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001316}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001317
John McCallf1249922012-08-21 04:10:00 +00001318// getTypeInfoDataSizeInChars - Return the size of a type, in
1319// chars. If the type is a record, its data size is returned. This is
1320// the size of the memcpy that's performed when assigning this type
1321// using a trivial copy/move assignment operator.
1322std::pair<CharUnits, CharUnits>
1323ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1324 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1325
1326 // In C++, objects can sometimes be allocated into the tail padding
1327 // of a base-class subobject. We decide whether that's possible
1328 // during class layout, so here we can just trust the layout results.
1329 if (getLangOpts().CPlusPlus) {
1330 if (const RecordType *RT = T->getAs<RecordType>()) {
1331 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1332 sizeAndAlign.first = layout.getDataSize();
1333 }
1334 }
1335
1336 return sizeAndAlign;
1337}
1338
John McCall87fe5d52010-05-20 01:18:31 +00001339std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001340ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001341 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +00001342 return std::make_pair(toCharUnitsFromBits(Info.first),
1343 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +00001344}
1345
1346std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001347ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001348 return getTypeInfoInChars(T.getTypePtr());
1349}
1350
Daniel Dunbarc6475872012-03-09 04:12:54 +00001351std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1352 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1353 if (it != MemoizedTypeInfo.end())
1354 return it->second;
1355
1356 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1357 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1358 return Info;
1359}
1360
1361/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1362/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001363///
1364/// FIXME: Pointers into different addr spaces could have different sizes and
1365/// alignment requirements: getPointerInfo should take an AddrSpace, this
1366/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001367std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001368ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001369 uint64_t Width=0;
1370 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001371 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001372#define TYPE(Class, Base)
1373#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001374#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001375#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1376#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001377 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001378
Chris Lattner355332d2007-07-13 22:27:08 +00001379 case Type::FunctionNoProto:
1380 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001381 // GCC extension: alignof(function) = 32 bits
1382 Width = 0;
1383 Align = 32;
1384 break;
1385
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001386 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001387 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001388 Width = 0;
1389 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1390 break;
1391
Steve Naroff5c131802007-08-30 01:06:46 +00001392 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001393 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001394
Chris Lattner37e05872008-03-05 18:54:05 +00001395 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001396 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001397 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1398 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001399 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001400 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +00001401 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001402 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001403 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001404 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001405 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001406 const VectorType *VT = cast<VectorType>(T);
1407 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1408 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001409 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001410 // If the alignment is not a power of 2, round up to the next power of 2.
1411 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001412 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001413 Align = llvm::NextPowerOf2(Align);
1414 Width = llvm::RoundUpToAlignment(Width, Align);
1415 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001416 // Adjust the alignment based on the target max.
1417 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1418 if (TargetVectorAlign && TargetVectorAlign < Align)
1419 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001420 break;
1421 }
Chris Lattner647fb222007-07-18 18:26:58 +00001422
Chris Lattner7570e9c2008-03-08 08:52:55 +00001423 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001424 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001425 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001426 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001427 // GCC extension: alignof(void) = 8 bits.
1428 Width = 0;
1429 Align = 8;
1430 break;
1431
Chris Lattner6a4f7452007-12-19 19:23:28 +00001432 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001433 Width = Target->getBoolWidth();
1434 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001435 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001436 case BuiltinType::Char_S:
1437 case BuiltinType::Char_U:
1438 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001439 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001440 Width = Target->getCharWidth();
1441 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001442 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001443 case BuiltinType::WChar_S:
1444 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001445 Width = Target->getWCharWidth();
1446 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001447 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001448 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001449 Width = Target->getChar16Width();
1450 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001451 break;
1452 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001453 Width = Target->getChar32Width();
1454 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001455 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001456 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001457 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001458 Width = Target->getShortWidth();
1459 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001460 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001461 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001462 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001463 Width = Target->getIntWidth();
1464 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001465 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001466 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001467 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001468 Width = Target->getLongWidth();
1469 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001470 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001471 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001472 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001473 Width = Target->getLongLongWidth();
1474 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001475 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001476 case BuiltinType::Int128:
1477 case BuiltinType::UInt128:
1478 Width = 128;
1479 Align = 128; // int128_t is 128-bit aligned on all targets.
1480 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001481 case BuiltinType::Half:
1482 Width = Target->getHalfWidth();
1483 Align = Target->getHalfAlign();
1484 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001485 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001486 Width = Target->getFloatWidth();
1487 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001488 break;
1489 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001490 Width = Target->getDoubleWidth();
1491 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001492 break;
1493 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001494 Width = Target->getLongDoubleWidth();
1495 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001496 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001497 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001498 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1499 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001500 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001501 case BuiltinType::ObjCId:
1502 case BuiltinType::ObjCClass:
1503 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001504 Width = Target->getPointerWidth(0);
1505 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001506 break;
Guy Benyei61054192013-02-07 10:55:47 +00001507 case BuiltinType::OCLSampler:
1508 // Samplers are modeled as integers.
1509 Width = Target->getIntWidth();
1510 Align = Target->getIntAlign();
1511 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001512 case BuiltinType::OCLEvent:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001513 case BuiltinType::OCLImage1d:
1514 case BuiltinType::OCLImage1dArray:
1515 case BuiltinType::OCLImage1dBuffer:
1516 case BuiltinType::OCLImage2d:
1517 case BuiltinType::OCLImage2dArray:
1518 case BuiltinType::OCLImage3d:
1519 // Currently these types are pointers to opaque types.
1520 Width = Target->getPointerWidth(0);
1521 Align = Target->getPointerAlign(0);
1522 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001523 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001524 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001525 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001526 Width = Target->getPointerWidth(0);
1527 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001528 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001529 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001530 unsigned AS = getTargetAddressSpace(
1531 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001532 Width = Target->getPointerWidth(AS);
1533 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001534 break;
1535 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001536 case Type::LValueReference:
1537 case Type::RValueReference: {
1538 // alignof and sizeof should never enter this code path here, so we go
1539 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001540 unsigned AS = getTargetAddressSpace(
1541 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001542 Width = Target->getPointerWidth(AS);
1543 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001544 break;
1545 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001546 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001547 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001548 Width = Target->getPointerWidth(AS);
1549 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001550 break;
1551 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001552 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001553 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Reid Kleckner3a52abf2013-03-28 20:02:56 +00001554 llvm::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001555 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001556 }
Chris Lattner647fb222007-07-18 18:26:58 +00001557 case Type::Complex: {
1558 // Complex types have the same alignment as their elements, but twice the
1559 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001560 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001561 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001562 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001563 Align = EltInfo.second;
1564 break;
1565 }
John McCall8b07ec22010-05-15 11:32:37 +00001566 case Type::ObjCObject:
1567 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001568 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001569 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001570 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001571 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001572 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001573 break;
1574 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001575 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001576 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001577 const TagType *TT = cast<TagType>(T);
1578
1579 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001580 Width = 8;
1581 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001582 break;
1583 }
Mike Stump11289f42009-09-09 15:08:12 +00001584
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001585 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001586 return getTypeInfo(ET->getDecl()->getIntegerType());
1587
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001588 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001589 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001590 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001591 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001592 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001593 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001594
Chris Lattner63d2b362009-10-22 05:17:15 +00001595 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001596 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1597 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001598
Richard Smith30482bc2011-02-20 03:19:35 +00001599 case Type::Auto: {
1600 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001601 assert(!A->getDeducedType().isNull() &&
1602 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001603 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001604 }
1605
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001606 case Type::Paren:
1607 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1608
Douglas Gregoref462e62009-04-30 17:32:17 +00001609 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001610 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001611 std::pair<uint64_t, unsigned> Info
1612 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001613 // If the typedef has an aligned attribute on it, it overrides any computed
1614 // alignment we have. This violates the GCC documentation (which says that
1615 // attribute(aligned) can only round up) but matches its implementation.
1616 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1617 Align = AttrAlign;
1618 else
1619 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001620 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001621 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001622 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001623
1624 case Type::TypeOfExpr:
1625 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1626 .getTypePtr());
1627
1628 case Type::TypeOf:
1629 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1630
Anders Carlsson81df7b82009-06-24 19:06:50 +00001631 case Type::Decltype:
1632 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1633 .getTypePtr());
1634
Alexis Hunte852b102011-05-24 22:41:36 +00001635 case Type::UnaryTransform:
1636 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1637
Abramo Bagnara6150c882010-05-11 21:36:43 +00001638 case Type::Elaborated:
1639 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001640
John McCall81904512011-01-06 01:58:22 +00001641 case Type::Attributed:
1642 return getTypeInfo(
1643 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1644
Richard Smith3f1b5d02011-05-05 21:57:07 +00001645 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001646 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001647 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001648 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1649 // A type alias template specialization may refer to a typedef with the
1650 // aligned attribute on it.
1651 if (TST->isTypeAlias())
1652 return getTypeInfo(TST->getAliasedType().getTypePtr());
1653 else
1654 return getTypeInfo(getCanonicalType(T));
1655 }
1656
Eli Friedman0dfb8892011-10-06 23:00:33 +00001657 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001658 // Start with the base type information.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001659 std::pair<uint64_t, unsigned> Info
1660 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1661 Width = Info.first;
1662 Align = Info.second;
John McCalla8ec7eb2013-03-07 21:37:17 +00001663
1664 // If the size of the type doesn't exceed the platform's max
1665 // atomic promotion width, make the size and alignment more
1666 // favorable to atomic operations:
1667 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1668 // Round the size up to a power of 2.
1669 if (!llvm::isPowerOf2_64(Width))
1670 Width = llvm::NextPowerOf2(Width);
1671
1672 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001673 Align = static_cast<unsigned>(Width);
1674 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001675 }
1676
Douglas Gregoref462e62009-04-30 17:32:17 +00001677 }
Mike Stump11289f42009-09-09 15:08:12 +00001678
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001679 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001680 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001681}
1682
Ken Dyckcc56c542011-01-15 18:38:59 +00001683/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1684CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1685 return CharUnits::fromQuantity(BitSize / getCharWidth());
1686}
1687
Ken Dyckb0fcc592011-02-11 01:54:29 +00001688/// toBits - Convert a size in characters to a size in characters.
1689int64_t ASTContext::toBits(CharUnits CharSize) const {
1690 return CharSize.getQuantity() * getCharWidth();
1691}
1692
Ken Dyck8c89d592009-12-22 14:23:30 +00001693/// getTypeSizeInChars - Return the size of the specified type, in characters.
1694/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001695CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001696 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001697}
Jay Foad39c79802011-01-12 09:06:06 +00001698CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001699 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001700}
1701
Ken Dycka6046ab2010-01-26 17:25:18 +00001702/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001703/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001704CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001705 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001706}
Jay Foad39c79802011-01-12 09:06:06 +00001707CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001708 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001709}
1710
Chris Lattnera3402cd2009-01-27 18:08:34 +00001711/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1712/// type for the current target in bits. This can be different than the ABI
1713/// alignment in cases where it is beneficial for performance to overalign
1714/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001715unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001716 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001717
1718 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001719 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001720 T = CT->getElementType().getTypePtr();
1721 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001722 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1723 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001724 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1725
Chris Lattnera3402cd2009-01-27 18:08:34 +00001726 return ABIAlign;
1727}
1728
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001729/// DeepCollectObjCIvars -
1730/// This routine first collects all declared, but not synthesized, ivars in
1731/// super class and then collects all ivars, including those synthesized for
1732/// current class. This routine is used for implementation of current class
1733/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001734///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001735void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1736 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001737 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001738 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1739 DeepCollectObjCIvars(SuperClass, false, Ivars);
1740 if (!leafClass) {
1741 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1742 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001743 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001744 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001745 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001746 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001747 Iv= Iv->getNextIvar())
1748 Ivars.push_back(Iv);
1749 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001750}
1751
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001752/// CollectInheritedProtocols - Collect all protocols in current class and
1753/// those inherited by it.
1754void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001755 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001756 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001757 // We can use protocol_iterator here instead of
1758 // all_referenced_protocol_iterator since we are walking all categories.
1759 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1760 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001761 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001762 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001763 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001764 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001765 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001766 CollectInheritedProtocols(*P, Protocols);
1767 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001768 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001769
1770 // Categories of this Interface.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001771 for (ObjCInterfaceDecl::visible_categories_iterator
1772 Cat = OI->visible_categories_begin(),
1773 CatEnd = OI->visible_categories_end();
1774 Cat != CatEnd; ++Cat) {
1775 CollectInheritedProtocols(*Cat, Protocols);
1776 }
1777
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001778 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1779 while (SD) {
1780 CollectInheritedProtocols(SD, Protocols);
1781 SD = SD->getSuperClass();
1782 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001783 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001784 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001785 PE = OC->protocol_end(); P != PE; ++P) {
1786 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001787 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001788 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1789 PE = Proto->protocol_end(); P != PE; ++P)
1790 CollectInheritedProtocols(*P, Protocols);
1791 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001792 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001793 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1794 PE = OP->protocol_end(); P != PE; ++P) {
1795 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001796 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001797 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1798 PE = Proto->protocol_end(); P != PE; ++P)
1799 CollectInheritedProtocols(*P, Protocols);
1800 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001801 }
1802}
1803
Jay Foad39c79802011-01-12 09:06:06 +00001804unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001805 unsigned count = 0;
1806 // Count ivars declared in class extension.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001807 for (ObjCInterfaceDecl::known_extensions_iterator
1808 Ext = OI->known_extensions_begin(),
1809 ExtEnd = OI->known_extensions_end();
1810 Ext != ExtEnd; ++Ext) {
1811 count += Ext->ivar_size();
1812 }
1813
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001814 // Count ivar defined in this class's implementation. This
1815 // includes synthesized ivars.
1816 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001817 count += ImplDecl->ivar_size();
1818
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001819 return count;
1820}
1821
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001822bool ASTContext::isSentinelNullExpr(const Expr *E) {
1823 if (!E)
1824 return false;
1825
1826 // nullptr_t is always treated as null.
1827 if (E->getType()->isNullPtrType()) return true;
1828
1829 if (E->getType()->isAnyPointerType() &&
1830 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1831 Expr::NPC_ValueDependentIsNull))
1832 return true;
1833
1834 // Unfortunately, __null has type 'int'.
1835 if (isa<GNUNullExpr>(E)) return true;
1836
1837 return false;
1838}
1839
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001840/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1841ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1842 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1843 I = ObjCImpls.find(D);
1844 if (I != ObjCImpls.end())
1845 return cast<ObjCImplementationDecl>(I->second);
1846 return 0;
1847}
1848/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1849ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1850 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1851 I = ObjCImpls.find(D);
1852 if (I != ObjCImpls.end())
1853 return cast<ObjCCategoryImplDecl>(I->second);
1854 return 0;
1855}
1856
1857/// \brief Set the implementation of ObjCInterfaceDecl.
1858void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1859 ObjCImplementationDecl *ImplD) {
1860 assert(IFaceD && ImplD && "Passed null params");
1861 ObjCImpls[IFaceD] = ImplD;
1862}
1863/// \brief Set the implementation of ObjCCategoryDecl.
1864void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1865 ObjCCategoryImplDecl *ImplD) {
1866 assert(CatD && ImplD && "Passed null params");
1867 ObjCImpls[CatD] = ImplD;
1868}
1869
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001870const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1871 const NamedDecl *ND) const {
1872 if (const ObjCInterfaceDecl *ID =
1873 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001874 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001875 if (const ObjCCategoryDecl *CD =
1876 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001877 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001878 if (const ObjCImplDecl *IMD =
1879 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001880 return IMD->getClassInterface();
1881
1882 return 0;
1883}
1884
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001885/// \brief Get the copy initialization expression of VarDecl,or NULL if
1886/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001887Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001888 assert(VD && "Passed null params");
1889 assert(VD->hasAttr<BlocksAttr>() &&
1890 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001891 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001892 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001893 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1894}
1895
1896/// \brief Set the copy inialization expression of a block var decl.
1897void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1898 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001899 assert(VD->hasAttr<BlocksAttr>() &&
1900 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001901 BlockVarCopyInits[VD] = Init;
1902}
1903
John McCallbcd03502009-12-07 02:54:59 +00001904TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001905 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001906 if (!DataSize)
1907 DataSize = TypeLoc::getFullDataSizeForType(T);
1908 else
1909 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001910 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001911
John McCallbcd03502009-12-07 02:54:59 +00001912 TypeSourceInfo *TInfo =
1913 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1914 new (TInfo) TypeSourceInfo(T);
1915 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001916}
1917
John McCallbcd03502009-12-07 02:54:59 +00001918TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001919 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001920 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001921 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001922 return DI;
1923}
1924
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001925const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001926ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001927 return getObjCLayout(D, 0);
1928}
1929
1930const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001931ASTContext::getASTObjCImplementationLayout(
1932 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001933 return getObjCLayout(D->getClassInterface(), D);
1934}
1935
Chris Lattner983a8bb2007-07-13 22:13:22 +00001936//===----------------------------------------------------------------------===//
1937// Type creation/memoization methods
1938//===----------------------------------------------------------------------===//
1939
Jay Foad39c79802011-01-12 09:06:06 +00001940QualType
John McCall33ddac02011-01-19 10:06:00 +00001941ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1942 unsigned fastQuals = quals.getFastQualifiers();
1943 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001944
1945 // Check if we've already instantiated this type.
1946 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001947 ExtQuals::Profile(ID, baseType, quals);
1948 void *insertPos = 0;
1949 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1950 assert(eq->getQualifiers() == quals);
1951 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001952 }
1953
John McCall33ddac02011-01-19 10:06:00 +00001954 // If the base type is not canonical, make the appropriate canonical type.
1955 QualType canon;
1956 if (!baseType->isCanonicalUnqualified()) {
1957 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001958 canonSplit.Quals.addConsistentQualifiers(quals);
1959 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001960
1961 // Re-find the insert position.
1962 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1963 }
1964
1965 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1966 ExtQualNodes.InsertNode(eq, insertPos);
1967 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001968}
1969
Jay Foad39c79802011-01-12 09:06:06 +00001970QualType
1971ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001972 QualType CanT = getCanonicalType(T);
1973 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001974 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001975
John McCall8ccfcb52009-09-24 19:53:00 +00001976 // If we are composing extended qualifiers together, merge together
1977 // into one ExtQuals node.
1978 QualifierCollector Quals;
1979 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001980
John McCall8ccfcb52009-09-24 19:53:00 +00001981 // If this type already has an address space specified, it cannot get
1982 // another one.
1983 assert(!Quals.hasAddressSpace() &&
1984 "Type cannot be in multiple addr spaces!");
1985 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001986
John McCall8ccfcb52009-09-24 19:53:00 +00001987 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001988}
1989
Chris Lattnerd60183d2009-02-18 22:53:11 +00001990QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001991 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001992 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001993 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001994 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001995
John McCall53fa7142010-12-24 02:08:15 +00001996 if (const PointerType *ptr = T->getAs<PointerType>()) {
1997 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001998 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001999 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2000 return getPointerType(ResultType);
2001 }
2002 }
Mike Stump11289f42009-09-09 15:08:12 +00002003
John McCall8ccfcb52009-09-24 19:53:00 +00002004 // If we are composing extended qualifiers together, merge together
2005 // into one ExtQuals node.
2006 QualifierCollector Quals;
2007 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002008
John McCall8ccfcb52009-09-24 19:53:00 +00002009 // If this type already has an ObjCGC specified, it cannot get
2010 // another one.
2011 assert(!Quals.hasObjCGCAttr() &&
2012 "Type cannot have multiple ObjCGCs!");
2013 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002014
John McCall8ccfcb52009-09-24 19:53:00 +00002015 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002016}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002017
John McCall4f5019e2010-12-19 02:44:49 +00002018const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2019 FunctionType::ExtInfo Info) {
2020 if (T->getExtInfo() == Info)
2021 return T;
2022
2023 QualType Result;
2024 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2025 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
2026 } else {
2027 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2028 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2029 EPI.ExtInfo = Info;
Jordan Rose5c382722013-03-08 21:51:21 +00002030 Result = getFunctionType(FPT->getResultType(),
2031 ArrayRef<QualType>(FPT->arg_type_begin(),
2032 FPT->getNumArgs()),
2033 EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002034 }
2035
2036 return cast<FunctionType>(Result.getTypePtr());
2037}
2038
Richard Smith2a7d4812013-05-04 07:00:32 +00002039void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2040 QualType ResultType) {
2041 // FIXME: Need to inform serialization code about this!
2042 for (FD = FD->getMostRecentDecl(); FD; FD = FD->getPreviousDecl()) {
2043 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2044 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2045 FD->setType(getFunctionType(ResultType, FPT->getArgTypes(), EPI));
2046 }
2047}
2048
Chris Lattnerc6395932007-06-22 20:56:16 +00002049/// getComplexType - Return the uniqued reference to the type for a complex
2050/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002051QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002052 // Unique pointers, to guarantee there is only one pointer of a particular
2053 // structure.
2054 llvm::FoldingSetNodeID ID;
2055 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002056
Chris Lattnerc6395932007-06-22 20:56:16 +00002057 void *InsertPos = 0;
2058 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2059 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002060
Chris Lattnerc6395932007-06-22 20:56:16 +00002061 // If the pointee type isn't canonical, this won't be a canonical type either,
2062 // so fill in the canonical type field.
2063 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002064 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002065 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002066
Chris Lattnerc6395932007-06-22 20:56:16 +00002067 // Get the new insert position for the node we care about.
2068 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002069 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002070 }
John McCall90d1c2d2009-09-24 23:30:46 +00002071 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002072 Types.push_back(New);
2073 ComplexTypes.InsertNode(New, InsertPos);
2074 return QualType(New, 0);
2075}
2076
Chris Lattner970e54e2006-11-12 00:37:36 +00002077/// getPointerType - Return the uniqued reference to the type for a pointer to
2078/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002079QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002080 // Unique pointers, to guarantee there is only one pointer of a particular
2081 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002082 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002083 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002084
Chris Lattner67521df2007-01-27 01:29:36 +00002085 void *InsertPos = 0;
2086 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002087 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002088
Chris Lattner7ccecb92006-11-12 08:50:50 +00002089 // If the pointee type isn't canonical, this won't be a canonical type either,
2090 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002091 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002092 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002093 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002094
Bob Wilsonc8541f22013-03-15 17:12:43 +00002095 // Get the new insert position for the node we care about.
2096 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2097 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2098 }
John McCall90d1c2d2009-09-24 23:30:46 +00002099 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002100 Types.push_back(New);
2101 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002102 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002103}
2104
Mike Stump11289f42009-09-09 15:08:12 +00002105/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002106/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002107QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002108 assert(T->isFunctionType() && "block of function types only");
2109 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002110 // structure.
2111 llvm::FoldingSetNodeID ID;
2112 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002113
Steve Naroffec33ed92008-08-27 16:04:49 +00002114 void *InsertPos = 0;
2115 if (BlockPointerType *PT =
2116 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2117 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002118
2119 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002120 // type either so fill in the canonical type field.
2121 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002122 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002123 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002124
Steve Naroffec33ed92008-08-27 16:04:49 +00002125 // Get the new insert position for the node we care about.
2126 BlockPointerType *NewIP =
2127 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002128 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002129 }
John McCall90d1c2d2009-09-24 23:30:46 +00002130 BlockPointerType *New
2131 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002132 Types.push_back(New);
2133 BlockPointerTypes.InsertNode(New, InsertPos);
2134 return QualType(New, 0);
2135}
2136
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002137/// getLValueReferenceType - Return the uniqued reference to the type for an
2138/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002139QualType
2140ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002141 assert(getCanonicalType(T) != OverloadTy &&
2142 "Unresolved overloaded function type");
2143
Bill Wendling3708c182007-05-27 10:15:43 +00002144 // Unique pointers, to guarantee there is only one pointer of a particular
2145 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002146 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002147 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002148
2149 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002150 if (LValueReferenceType *RT =
2151 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002152 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002153
John McCallfc93cf92009-10-22 22:37:11 +00002154 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2155
Bill Wendling3708c182007-05-27 10:15:43 +00002156 // If the referencee type isn't canonical, this won't be a canonical type
2157 // either, so fill in the canonical type field.
2158 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002159 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2160 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2161 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002162
Bill Wendling3708c182007-05-27 10:15:43 +00002163 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002164 LValueReferenceType *NewIP =
2165 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002166 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002167 }
2168
John McCall90d1c2d2009-09-24 23:30:46 +00002169 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002170 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2171 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002172 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002173 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002174
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002175 return QualType(New, 0);
2176}
2177
2178/// getRValueReferenceType - Return the uniqued reference to the type for an
2179/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002180QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002181 // Unique pointers, to guarantee there is only one pointer of a particular
2182 // structure.
2183 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002184 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002185
2186 void *InsertPos = 0;
2187 if (RValueReferenceType *RT =
2188 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2189 return QualType(RT, 0);
2190
John McCallfc93cf92009-10-22 22:37:11 +00002191 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2192
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002193 // If the referencee type isn't canonical, this won't be a canonical type
2194 // either, so fill in the canonical type field.
2195 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002196 if (InnerRef || !T.isCanonical()) {
2197 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2198 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002199
2200 // Get the new insert position for the node we care about.
2201 RValueReferenceType *NewIP =
2202 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002203 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002204 }
2205
John McCall90d1c2d2009-09-24 23:30:46 +00002206 RValueReferenceType *New
2207 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002208 Types.push_back(New);
2209 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002210 return QualType(New, 0);
2211}
2212
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002213/// getMemberPointerType - Return the uniqued reference to the type for a
2214/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002215QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002216 // Unique pointers, to guarantee there is only one pointer of a particular
2217 // structure.
2218 llvm::FoldingSetNodeID ID;
2219 MemberPointerType::Profile(ID, T, Cls);
2220
2221 void *InsertPos = 0;
2222 if (MemberPointerType *PT =
2223 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2224 return QualType(PT, 0);
2225
2226 // If the pointee or class type isn't canonical, this won't be a canonical
2227 // type either, so fill in the canonical type field.
2228 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002229 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002230 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2231
2232 // Get the new insert position for the node we care about.
2233 MemberPointerType *NewIP =
2234 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002235 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002236 }
John McCall90d1c2d2009-09-24 23:30:46 +00002237 MemberPointerType *New
2238 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002239 Types.push_back(New);
2240 MemberPointerTypes.InsertNode(New, InsertPos);
2241 return QualType(New, 0);
2242}
2243
Mike Stump11289f42009-09-09 15:08:12 +00002244/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002245/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002246QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002247 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002248 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002249 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002250 assert((EltTy->isDependentType() ||
2251 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002252 "Constant array of VLAs is illegal!");
2253
Chris Lattnere2df3f92009-05-13 04:12:56 +00002254 // Convert the array size into a canonical width matching the pointer size for
2255 // the target.
2256 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002257 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002258 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002259
Chris Lattner23b7eb62007-06-15 23:05:46 +00002260 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002261 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002262
Chris Lattner36f8e652007-01-27 08:31:04 +00002263 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002264 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002265 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002266 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002267
John McCall33ddac02011-01-19 10:06:00 +00002268 // If the element type isn't canonical or has qualifiers, this won't
2269 // be a canonical type either, so fill in the canonical type field.
2270 QualType Canon;
2271 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2272 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002273 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002274 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002275 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002276
Chris Lattner36f8e652007-01-27 08:31:04 +00002277 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002278 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002279 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002280 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002281 }
Mike Stump11289f42009-09-09 15:08:12 +00002282
John McCall90d1c2d2009-09-24 23:30:46 +00002283 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002284 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002285 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002286 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002287 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002288}
2289
John McCall06549462011-01-18 08:40:38 +00002290/// getVariableArrayDecayedType - Turns the given type, which may be
2291/// variably-modified, into the corresponding type with all the known
2292/// sizes replaced with [*].
2293QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2294 // Vastly most common case.
2295 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002296
John McCall06549462011-01-18 08:40:38 +00002297 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002298
John McCall06549462011-01-18 08:40:38 +00002299 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002300 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002301 switch (ty->getTypeClass()) {
2302#define TYPE(Class, Base)
2303#define ABSTRACT_TYPE(Class, Base)
2304#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2305#include "clang/AST/TypeNodes.def"
2306 llvm_unreachable("didn't desugar past all non-canonical types?");
2307
2308 // These types should never be variably-modified.
2309 case Type::Builtin:
2310 case Type::Complex:
2311 case Type::Vector:
2312 case Type::ExtVector:
2313 case Type::DependentSizedExtVector:
2314 case Type::ObjCObject:
2315 case Type::ObjCInterface:
2316 case Type::ObjCObjectPointer:
2317 case Type::Record:
2318 case Type::Enum:
2319 case Type::UnresolvedUsing:
2320 case Type::TypeOfExpr:
2321 case Type::TypeOf:
2322 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002323 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002324 case Type::DependentName:
2325 case Type::InjectedClassName:
2326 case Type::TemplateSpecialization:
2327 case Type::DependentTemplateSpecialization:
2328 case Type::TemplateTypeParm:
2329 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002330 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002331 case Type::PackExpansion:
2332 llvm_unreachable("type should never be variably-modified");
2333
2334 // These types can be variably-modified but should never need to
2335 // further decay.
2336 case Type::FunctionNoProto:
2337 case Type::FunctionProto:
2338 case Type::BlockPointer:
2339 case Type::MemberPointer:
2340 return type;
2341
2342 // These types can be variably-modified. All these modifications
2343 // preserve structure except as noted by comments.
2344 // TODO: if we ever care about optimizing VLAs, there are no-op
2345 // optimizations available here.
2346 case Type::Pointer:
2347 result = getPointerType(getVariableArrayDecayedType(
2348 cast<PointerType>(ty)->getPointeeType()));
2349 break;
2350
2351 case Type::LValueReference: {
2352 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2353 result = getLValueReferenceType(
2354 getVariableArrayDecayedType(lv->getPointeeType()),
2355 lv->isSpelledAsLValue());
2356 break;
2357 }
2358
2359 case Type::RValueReference: {
2360 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2361 result = getRValueReferenceType(
2362 getVariableArrayDecayedType(lv->getPointeeType()));
2363 break;
2364 }
2365
Eli Friedman0dfb8892011-10-06 23:00:33 +00002366 case Type::Atomic: {
2367 const AtomicType *at = cast<AtomicType>(ty);
2368 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2369 break;
2370 }
2371
John McCall06549462011-01-18 08:40:38 +00002372 case Type::ConstantArray: {
2373 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2374 result = getConstantArrayType(
2375 getVariableArrayDecayedType(cat->getElementType()),
2376 cat->getSize(),
2377 cat->getSizeModifier(),
2378 cat->getIndexTypeCVRQualifiers());
2379 break;
2380 }
2381
2382 case Type::DependentSizedArray: {
2383 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2384 result = getDependentSizedArrayType(
2385 getVariableArrayDecayedType(dat->getElementType()),
2386 dat->getSizeExpr(),
2387 dat->getSizeModifier(),
2388 dat->getIndexTypeCVRQualifiers(),
2389 dat->getBracketsRange());
2390 break;
2391 }
2392
2393 // Turn incomplete types into [*] types.
2394 case Type::IncompleteArray: {
2395 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2396 result = getVariableArrayType(
2397 getVariableArrayDecayedType(iat->getElementType()),
2398 /*size*/ 0,
2399 ArrayType::Normal,
2400 iat->getIndexTypeCVRQualifiers(),
2401 SourceRange());
2402 break;
2403 }
2404
2405 // Turn VLA types into [*] types.
2406 case Type::VariableArray: {
2407 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2408 result = getVariableArrayType(
2409 getVariableArrayDecayedType(vat->getElementType()),
2410 /*size*/ 0,
2411 ArrayType::Star,
2412 vat->getIndexTypeCVRQualifiers(),
2413 vat->getBracketsRange());
2414 break;
2415 }
2416 }
2417
2418 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002419 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002420}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002421
Steve Naroffcadebd02007-08-30 18:14:25 +00002422/// getVariableArrayType - Returns a non-unique reference to the type for a
2423/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002424QualType ASTContext::getVariableArrayType(QualType EltTy,
2425 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002426 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002427 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002428 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002429 // Since we don't unique expressions, it isn't possible to unique VLA's
2430 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002431 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002432
John McCall33ddac02011-01-19 10:06:00 +00002433 // Be sure to pull qualifiers off the element type.
2434 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2435 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002436 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002437 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002438 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002439 }
2440
John McCall90d1c2d2009-09-24 23:30:46 +00002441 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002442 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002443
2444 VariableArrayTypes.push_back(New);
2445 Types.push_back(New);
2446 return QualType(New, 0);
2447}
2448
Douglas Gregor4619e432008-12-05 23:32:09 +00002449/// getDependentSizedArrayType - Returns a non-unique reference to
2450/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002451/// type.
John McCall33ddac02011-01-19 10:06:00 +00002452QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2453 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002454 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002455 unsigned elementTypeQuals,
2456 SourceRange brackets) const {
2457 assert((!numElements || numElements->isTypeDependent() ||
2458 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002459 "Size must be type- or value-dependent!");
2460
John McCall33ddac02011-01-19 10:06:00 +00002461 // Dependently-sized array types that do not have a specified number
2462 // of elements will have their sizes deduced from a dependent
2463 // initializer. We do no canonicalization here at all, which is okay
2464 // because they can't be used in most locations.
2465 if (!numElements) {
2466 DependentSizedArrayType *newType
2467 = new (*this, TypeAlignment)
2468 DependentSizedArrayType(*this, elementType, QualType(),
2469 numElements, ASM, elementTypeQuals,
2470 brackets);
2471 Types.push_back(newType);
2472 return QualType(newType, 0);
2473 }
2474
2475 // Otherwise, we actually build a new type every time, but we
2476 // also build a canonical type.
2477
2478 SplitQualType canonElementType = getCanonicalType(elementType).split();
2479
2480 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002481 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002482 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002483 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002484 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002485
John McCall33ddac02011-01-19 10:06:00 +00002486 // Look for an existing type with these properties.
2487 DependentSizedArrayType *canonTy =
2488 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002489
John McCall33ddac02011-01-19 10:06:00 +00002490 // If we don't have one, build one.
2491 if (!canonTy) {
2492 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002493 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002494 QualType(), numElements, ASM, elementTypeQuals,
2495 brackets);
2496 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2497 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002498 }
2499
John McCall33ddac02011-01-19 10:06:00 +00002500 // Apply qualifiers from the element type to the array.
2501 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002502 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002503
John McCall33ddac02011-01-19 10:06:00 +00002504 // If we didn't need extra canonicalization for the element type,
2505 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002506 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002507 return canon;
2508
2509 // Otherwise, we need to build a type which follows the spelling
2510 // of the element type.
2511 DependentSizedArrayType *sugaredType
2512 = new (*this, TypeAlignment)
2513 DependentSizedArrayType(*this, elementType, canon, numElements,
2514 ASM, elementTypeQuals, brackets);
2515 Types.push_back(sugaredType);
2516 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002517}
2518
John McCall33ddac02011-01-19 10:06:00 +00002519QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002520 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002521 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002522 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002523 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002524
John McCall33ddac02011-01-19 10:06:00 +00002525 void *insertPos = 0;
2526 if (IncompleteArrayType *iat =
2527 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2528 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002529
2530 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002531 // either, so fill in the canonical type field. We also have to pull
2532 // qualifiers off the element type.
2533 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002534
John McCall33ddac02011-01-19 10:06:00 +00002535 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2536 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002537 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002538 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002539 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002540
2541 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002542 IncompleteArrayType *existing =
2543 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2544 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002545 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002546
John McCall33ddac02011-01-19 10:06:00 +00002547 IncompleteArrayType *newType = new (*this, TypeAlignment)
2548 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002549
John McCall33ddac02011-01-19 10:06:00 +00002550 IncompleteArrayTypes.InsertNode(newType, insertPos);
2551 Types.push_back(newType);
2552 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002553}
2554
Steve Naroff91fcddb2007-07-18 18:00:27 +00002555/// getVectorType - Return the unique reference to a vector type of
2556/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002557QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002558 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002559 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002560
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002561 // Check if we've already instantiated a vector of this type.
2562 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002563 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002564
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002565 void *InsertPos = 0;
2566 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2567 return QualType(VTP, 0);
2568
2569 // If the element type isn't canonical, this won't be a canonical type either,
2570 // so fill in the canonical type field.
2571 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002572 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002573 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002574
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002575 // Get the new insert position for the node we care about.
2576 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002577 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002578 }
John McCall90d1c2d2009-09-24 23:30:46 +00002579 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002580 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002581 VectorTypes.InsertNode(New, InsertPos);
2582 Types.push_back(New);
2583 return QualType(New, 0);
2584}
2585
Nate Begemance4d7fc2008-04-18 23:10:10 +00002586/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002587/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002588QualType
2589ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002590 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002591
Steve Naroff91fcddb2007-07-18 18:00:27 +00002592 // Check if we've already instantiated a vector of this type.
2593 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002594 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002595 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002596 void *InsertPos = 0;
2597 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2598 return QualType(VTP, 0);
2599
2600 // If the element type isn't canonical, this won't be a canonical type either,
2601 // so fill in the canonical type field.
2602 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002603 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002604 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002605
Steve Naroff91fcddb2007-07-18 18:00:27 +00002606 // Get the new insert position for the node we care about.
2607 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002608 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002609 }
John McCall90d1c2d2009-09-24 23:30:46 +00002610 ExtVectorType *New = new (*this, TypeAlignment)
2611 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002612 VectorTypes.InsertNode(New, InsertPos);
2613 Types.push_back(New);
2614 return QualType(New, 0);
2615}
2616
Jay Foad39c79802011-01-12 09:06:06 +00002617QualType
2618ASTContext::getDependentSizedExtVectorType(QualType vecType,
2619 Expr *SizeExpr,
2620 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002621 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002622 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002623 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002624
Douglas Gregor352169a2009-07-31 03:54:25 +00002625 void *InsertPos = 0;
2626 DependentSizedExtVectorType *Canon
2627 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2628 DependentSizedExtVectorType *New;
2629 if (Canon) {
2630 // We already have a canonical version of this array type; use it as
2631 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002632 New = new (*this, TypeAlignment)
2633 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2634 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002635 } else {
2636 QualType CanonVecTy = getCanonicalType(vecType);
2637 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002638 New = new (*this, TypeAlignment)
2639 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2640 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002641
2642 DependentSizedExtVectorType *CanonCheck
2643 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2644 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2645 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002646 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2647 } else {
2648 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2649 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002650 New = new (*this, TypeAlignment)
2651 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002652 }
2653 }
Mike Stump11289f42009-09-09 15:08:12 +00002654
Douglas Gregor758a8692009-06-17 21:51:59 +00002655 Types.push_back(New);
2656 return QualType(New, 0);
2657}
2658
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002659/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002660///
Jay Foad39c79802011-01-12 09:06:06 +00002661QualType
2662ASTContext::getFunctionNoProtoType(QualType ResultTy,
2663 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002664 const CallingConv DefaultCC = Info.getCC();
2665 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2666 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002667 // Unique functions, to guarantee there is only one function of a particular
2668 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002669 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002670 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002671
Chris Lattner47955de2007-01-27 08:37:20 +00002672 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002673 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002674 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002675 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002676
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002677 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002678 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002679 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002680 Canonical =
2681 getFunctionNoProtoType(getCanonicalType(ResultTy),
2682 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002683
Chris Lattner47955de2007-01-27 08:37:20 +00002684 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002685 FunctionNoProtoType *NewIP =
2686 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002687 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002688 }
Mike Stump11289f42009-09-09 15:08:12 +00002689
Roman Divacky65b88cd2011-03-01 17:40:53 +00002690 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002691 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002692 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002693 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002694 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002695 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002696}
2697
Douglas Gregorcd780372013-01-17 23:36:45 +00002698/// \brief Determine whether \p T is canonical as the result type of a function.
2699static bool isCanonicalResultType(QualType T) {
2700 return T.isCanonical() &&
2701 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2702 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2703}
2704
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002705/// getFunctionType - Return a normal function type with a typed argument
2706/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002707QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002708ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002709 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002710 size_t NumArgs = ArgArray.size();
2711
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002712 // Unique functions, to guarantee there is only one function of a particular
2713 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002714 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002715 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2716 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002717
2718 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002719 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002720 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002721 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002722
2723 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002724 bool isCanonical =
Douglas Gregorcd780372013-01-17 23:36:45 +00002725 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002726 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002727 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002728 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002729 isCanonical = false;
2730
Roman Divacky65b88cd2011-03-01 17:40:53 +00002731 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2732 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2733 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002734
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002735 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002736 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002737 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002738 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002739 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002740 CanonicalArgs.reserve(NumArgs);
2741 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002742 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002743
John McCalldb40c7f2010-12-14 08:05:40 +00002744 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002745 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002746 CanonicalEPI.ExceptionSpecType = EST_None;
2747 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002748 CanonicalEPI.ExtInfo
2749 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2750
Douglas Gregorcd780372013-01-17 23:36:45 +00002751 // Result types do not have ARC lifetime qualifiers.
2752 QualType CanResultTy = getCanonicalType(ResultTy);
2753 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2754 Qualifiers Qs = CanResultTy.getQualifiers();
2755 Qs.removeObjCLifetime();
2756 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2757 }
2758
Jordan Rose5c382722013-03-08 21:51:21 +00002759 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002760
Chris Lattnerfd4de792007-01-27 01:15:32 +00002761 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002762 FunctionProtoType *NewIP =
2763 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002764 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002765 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002766
John McCall31168b02011-06-15 23:02:42 +00002767 // FunctionProtoType objects are allocated with extra bytes after
2768 // them for three variable size arrays at the end:
2769 // - parameter types
2770 // - exception types
2771 // - consumed-arguments flags
2772 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002773 // expression, or information used to resolve the exception
2774 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002775 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002776 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002777 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002778 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002779 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002780 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002781 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002782 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002783 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2784 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002785 }
John McCall31168b02011-06-15 23:02:42 +00002786 if (EPI.ConsumedArguments)
2787 Size += NumArgs * sizeof(bool);
2788
John McCalldb40c7f2010-12-14 08:05:40 +00002789 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002790 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2791 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Jordan Rose5c382722013-03-08 21:51:21 +00002792 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002793 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002794 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002795 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002796}
Chris Lattneref51c202006-11-10 07:17:23 +00002797
John McCalle78aac42010-03-10 03:28:59 +00002798#ifndef NDEBUG
2799static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2800 if (!isa<CXXRecordDecl>(D)) return false;
2801 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2802 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2803 return true;
2804 if (RD->getDescribedClassTemplate() &&
2805 !isa<ClassTemplateSpecializationDecl>(RD))
2806 return true;
2807 return false;
2808}
2809#endif
2810
2811/// getInjectedClassNameType - Return the unique reference to the
2812/// injected class name type for the specified templated declaration.
2813QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002814 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002815 assert(NeedsInjectedClassNameType(Decl));
2816 if (Decl->TypeForDecl) {
2817 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002818 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002819 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2820 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2821 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2822 } else {
John McCall424cec92011-01-19 06:33:43 +00002823 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002824 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002825 Decl->TypeForDecl = newType;
2826 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002827 }
2828 return QualType(Decl->TypeForDecl, 0);
2829}
2830
Douglas Gregor83a586e2008-04-13 21:07:44 +00002831/// getTypeDeclType - Return the unique reference to the type for the
2832/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002833QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002834 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002835 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002836
Richard Smithdda56e42011-04-15 14:24:37 +00002837 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002838 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002839
John McCall96f0b5f2010-03-10 06:48:02 +00002840 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2841 "Template type parameter types are always available.");
2842
John McCall81e38502010-02-16 03:57:14 +00002843 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002844 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002845 "struct/union has previous declaration");
2846 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002847 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002848 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002849 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002850 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002851 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002852 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002853 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002854 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2855 Decl->TypeForDecl = newType;
2856 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002857 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002858 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002859
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002860 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002861}
2862
Chris Lattner32d920b2007-01-26 02:01:53 +00002863/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002864/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002865QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002866ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2867 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002868 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002869
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002870 if (Canonical.isNull())
2871 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002872 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002873 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002874 Decl->TypeForDecl = newType;
2875 Types.push_back(newType);
2876 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002877}
2878
Jay Foad39c79802011-01-12 09:06:06 +00002879QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002880 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2881
Douglas Gregorec9fd132012-01-14 16:38:05 +00002882 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002883 if (PrevDecl->TypeForDecl)
2884 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2885
John McCall424cec92011-01-19 06:33:43 +00002886 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2887 Decl->TypeForDecl = newType;
2888 Types.push_back(newType);
2889 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002890}
2891
Jay Foad39c79802011-01-12 09:06:06 +00002892QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002893 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2894
Douglas Gregorec9fd132012-01-14 16:38:05 +00002895 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002896 if (PrevDecl->TypeForDecl)
2897 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2898
John McCall424cec92011-01-19 06:33:43 +00002899 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2900 Decl->TypeForDecl = newType;
2901 Types.push_back(newType);
2902 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002903}
2904
John McCall81904512011-01-06 01:58:22 +00002905QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2906 QualType modifiedType,
2907 QualType equivalentType) {
2908 llvm::FoldingSetNodeID id;
2909 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2910
2911 void *insertPos = 0;
2912 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2913 if (type) return QualType(type, 0);
2914
2915 QualType canon = getCanonicalType(equivalentType);
2916 type = new (*this, TypeAlignment)
2917 AttributedType(canon, attrKind, modifiedType, equivalentType);
2918
2919 Types.push_back(type);
2920 AttributedTypes.InsertNode(type, insertPos);
2921
2922 return QualType(type, 0);
2923}
2924
2925
John McCallcebee162009-10-18 09:09:24 +00002926/// \brief Retrieve a substitution-result type.
2927QualType
2928ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002929 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002930 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002931 && "replacement types must always be canonical");
2932
2933 llvm::FoldingSetNodeID ID;
2934 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2935 void *InsertPos = 0;
2936 SubstTemplateTypeParmType *SubstParm
2937 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2938
2939 if (!SubstParm) {
2940 SubstParm = new (*this, TypeAlignment)
2941 SubstTemplateTypeParmType(Parm, Replacement);
2942 Types.push_back(SubstParm);
2943 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2944 }
2945
2946 return QualType(SubstParm, 0);
2947}
2948
Douglas Gregorada4b792011-01-14 02:55:32 +00002949/// \brief Retrieve a
2950QualType ASTContext::getSubstTemplateTypeParmPackType(
2951 const TemplateTypeParmType *Parm,
2952 const TemplateArgument &ArgPack) {
2953#ifndef NDEBUG
2954 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2955 PEnd = ArgPack.pack_end();
2956 P != PEnd; ++P) {
2957 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2958 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2959 }
2960#endif
2961
2962 llvm::FoldingSetNodeID ID;
2963 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2964 void *InsertPos = 0;
2965 if (SubstTemplateTypeParmPackType *SubstParm
2966 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2967 return QualType(SubstParm, 0);
2968
2969 QualType Canon;
2970 if (!Parm->isCanonicalUnqualified()) {
2971 Canon = getCanonicalType(QualType(Parm, 0));
2972 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2973 ArgPack);
2974 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2975 }
2976
2977 SubstTemplateTypeParmPackType *SubstParm
2978 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2979 ArgPack);
2980 Types.push_back(SubstParm);
2981 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2982 return QualType(SubstParm, 0);
2983}
2984
Douglas Gregoreff93e02009-02-05 23:33:38 +00002985/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002986/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002987/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002988QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002989 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002990 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002991 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002992 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002993 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002994 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002995 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2996
2997 if (TypeParm)
2998 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002999
Chandler Carruth08836322011-05-01 00:51:33 +00003000 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003001 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003002 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003003
3004 TemplateTypeParmType *TypeCheck
3005 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3006 assert(!TypeCheck && "Template type parameter canonical type broken");
3007 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003008 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003009 TypeParm = new (*this, TypeAlignment)
3010 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003011
3012 Types.push_back(TypeParm);
3013 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3014
3015 return QualType(TypeParm, 0);
3016}
3017
John McCalle78aac42010-03-10 03:28:59 +00003018TypeSourceInfo *
3019ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3020 SourceLocation NameLoc,
3021 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003022 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003023 assert(!Name.getAsDependentTemplateName() &&
3024 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003025 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003026
3027 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003028 TemplateSpecializationTypeLoc TL =
3029 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003030 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003031 TL.setTemplateNameLoc(NameLoc);
3032 TL.setLAngleLoc(Args.getLAngleLoc());
3033 TL.setRAngleLoc(Args.getRAngleLoc());
3034 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3035 TL.setArgLocInfo(i, Args[i].getLocInfo());
3036 return DI;
3037}
3038
Mike Stump11289f42009-09-09 15:08:12 +00003039QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003040ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003041 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003042 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003043 assert(!Template.getAsDependentTemplateName() &&
3044 "No dependent template names here!");
3045
John McCall6b51f282009-11-23 01:53:49 +00003046 unsigned NumArgs = Args.size();
3047
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003048 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003049 ArgVec.reserve(NumArgs);
3050 for (unsigned i = 0; i != NumArgs; ++i)
3051 ArgVec.push_back(Args[i].getArgument());
3052
John McCall2408e322010-04-27 00:57:59 +00003053 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003054 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003055}
3056
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003057#ifndef NDEBUG
3058static bool hasAnyPackExpansions(const TemplateArgument *Args,
3059 unsigned NumArgs) {
3060 for (unsigned I = 0; I != NumArgs; ++I)
3061 if (Args[I].isPackExpansion())
3062 return true;
3063
3064 return true;
3065}
3066#endif
3067
John McCall0ad16662009-10-29 08:12:44 +00003068QualType
3069ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003070 const TemplateArgument *Args,
3071 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003072 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003073 assert(!Template.getAsDependentTemplateName() &&
3074 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003075 // Look through qualified template names.
3076 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3077 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003078
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003079 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003080 Template.getAsTemplateDecl() &&
3081 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003082 QualType CanonType;
3083 if (!Underlying.isNull())
3084 CanonType = getCanonicalType(Underlying);
3085 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003086 // We can get here with an alias template when the specialization contains
3087 // a pack expansion that does not match up with a parameter pack.
3088 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3089 "Caller must compute aliased type");
3090 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003091 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3092 NumArgs);
3093 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003094
Douglas Gregora8e02e72009-07-28 23:00:59 +00003095 // Allocate the (non-canonical) template specialization type, but don't
3096 // try to unique it: these types typically have location information that
3097 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003098 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3099 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003100 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003101 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003102 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003103 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3104 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003105
Douglas Gregor8bf42052009-02-09 18:46:07 +00003106 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003107 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003108}
3109
Mike Stump11289f42009-09-09 15:08:12 +00003110QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003111ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3112 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003113 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003114 assert(!Template.getAsDependentTemplateName() &&
3115 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003116
Douglas Gregore29139c2011-03-03 17:04:51 +00003117 // Look through qualified template names.
3118 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3119 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003120
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003121 // Build the canonical template specialization type.
3122 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003123 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003124 CanonArgs.reserve(NumArgs);
3125 for (unsigned I = 0; I != NumArgs; ++I)
3126 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3127
3128 // Determine whether this canonical template specialization type already
3129 // exists.
3130 llvm::FoldingSetNodeID ID;
3131 TemplateSpecializationType::Profile(ID, CanonTemplate,
3132 CanonArgs.data(), NumArgs, *this);
3133
3134 void *InsertPos = 0;
3135 TemplateSpecializationType *Spec
3136 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3137
3138 if (!Spec) {
3139 // Allocate a new canonical template specialization type.
3140 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3141 sizeof(TemplateArgument) * NumArgs),
3142 TypeAlignment);
3143 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3144 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003145 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003146 Types.push_back(Spec);
3147 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3148 }
3149
3150 assert(Spec->isDependentType() &&
3151 "Non-dependent template-id type must have a canonical type");
3152 return QualType(Spec, 0);
3153}
3154
3155QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003156ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3157 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003158 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003159 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003160 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003161
3162 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003163 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003164 if (T)
3165 return QualType(T, 0);
3166
Douglas Gregorc42075a2010-02-04 18:10:26 +00003167 QualType Canon = NamedType;
3168 if (!Canon.isCanonical()) {
3169 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003170 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3171 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003172 (void)CheckT;
3173 }
3174
Abramo Bagnara6150c882010-05-11 21:36:43 +00003175 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003176 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003177 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003178 return QualType(T, 0);
3179}
3180
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003181QualType
Jay Foad39c79802011-01-12 09:06:06 +00003182ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003183 llvm::FoldingSetNodeID ID;
3184 ParenType::Profile(ID, InnerType);
3185
3186 void *InsertPos = 0;
3187 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3188 if (T)
3189 return QualType(T, 0);
3190
3191 QualType Canon = InnerType;
3192 if (!Canon.isCanonical()) {
3193 Canon = getCanonicalType(InnerType);
3194 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3195 assert(!CheckT && "Paren canonical type broken");
3196 (void)CheckT;
3197 }
3198
3199 T = new (*this) ParenType(InnerType, Canon);
3200 Types.push_back(T);
3201 ParenTypes.InsertNode(T, InsertPos);
3202 return QualType(T, 0);
3203}
3204
Douglas Gregor02085352010-03-31 20:19:30 +00003205QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3206 NestedNameSpecifier *NNS,
3207 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003208 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003209 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3210
3211 if (Canon.isNull()) {
3212 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003213 ElaboratedTypeKeyword CanonKeyword = Keyword;
3214 if (Keyword == ETK_None)
3215 CanonKeyword = ETK_Typename;
3216
3217 if (CanonNNS != NNS || CanonKeyword != Keyword)
3218 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003219 }
3220
3221 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003222 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003223
3224 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003225 DependentNameType *T
3226 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003227 if (T)
3228 return QualType(T, 0);
3229
Douglas Gregor02085352010-03-31 20:19:30 +00003230 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003231 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003232 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003233 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003234}
3235
Mike Stump11289f42009-09-09 15:08:12 +00003236QualType
John McCallc392f372010-06-11 00:33:02 +00003237ASTContext::getDependentTemplateSpecializationType(
3238 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003239 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003240 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003241 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003242 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003243 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003244 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3245 ArgCopy.push_back(Args[I].getArgument());
3246 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3247 ArgCopy.size(),
3248 ArgCopy.data());
3249}
3250
3251QualType
3252ASTContext::getDependentTemplateSpecializationType(
3253 ElaboratedTypeKeyword Keyword,
3254 NestedNameSpecifier *NNS,
3255 const IdentifierInfo *Name,
3256 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003257 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003258 assert((!NNS || NNS->isDependent()) &&
3259 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003260
Douglas Gregorc42075a2010-02-04 18:10:26 +00003261 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003262 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3263 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003264
3265 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00003266 DependentTemplateSpecializationType *T
3267 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003268 if (T)
3269 return QualType(T, 0);
3270
John McCallc392f372010-06-11 00:33:02 +00003271 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003272
John McCallc392f372010-06-11 00:33:02 +00003273 ElaboratedTypeKeyword CanonKeyword = Keyword;
3274 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3275
3276 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003277 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003278 for (unsigned I = 0; I != NumArgs; ++I) {
3279 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3280 if (!CanonArgs[I].structurallyEquals(Args[I]))
3281 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003282 }
3283
John McCallc392f372010-06-11 00:33:02 +00003284 QualType Canon;
3285 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3286 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3287 Name, NumArgs,
3288 CanonArgs.data());
3289
3290 // Find the insert position again.
3291 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3292 }
3293
3294 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3295 sizeof(TemplateArgument) * NumArgs),
3296 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003297 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003298 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003299 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003300 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003301 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003302}
3303
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003304QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003305 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003306 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003307 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003308
3309 assert(Pattern->containsUnexpandedParameterPack() &&
3310 "Pack expansions must expand one or more parameter packs");
3311 void *InsertPos = 0;
3312 PackExpansionType *T
3313 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3314 if (T)
3315 return QualType(T, 0);
3316
3317 QualType Canon;
3318 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003319 Canon = getCanonicalType(Pattern);
3320 // The canonical type might not contain an unexpanded parameter pack, if it
3321 // contains an alias template specialization which ignores one of its
3322 // parameters.
3323 if (Canon->containsUnexpandedParameterPack()) {
3324 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003325
Richard Smith68eea502012-07-16 00:20:35 +00003326 // Find the insert position again, in case we inserted an element into
3327 // PackExpansionTypes and invalidated our insert position.
3328 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3329 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003330 }
3331
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003332 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003333 Types.push_back(T);
3334 PackExpansionTypes.InsertNode(T, InsertPos);
3335 return QualType(T, 0);
3336}
3337
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003338/// CmpProtocolNames - Comparison predicate for sorting protocols
3339/// alphabetically.
3340static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3341 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003342 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003343}
3344
John McCall8b07ec22010-05-15 11:32:37 +00003345static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003346 unsigned NumProtocols) {
3347 if (NumProtocols == 0) return true;
3348
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003349 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3350 return false;
3351
John McCallfc93cf92009-10-22 22:37:11 +00003352 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003353 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3354 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003355 return false;
3356 return true;
3357}
3358
3359static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003360 unsigned &NumProtocols) {
3361 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003362
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003363 // Sort protocols, keyed by name.
3364 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3365
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003366 // Canonicalize.
3367 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3368 Protocols[I] = Protocols[I]->getCanonicalDecl();
3369
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003370 // Remove duplicates.
3371 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3372 NumProtocols = ProtocolsEnd-Protocols;
3373}
3374
John McCall8b07ec22010-05-15 11:32:37 +00003375QualType ASTContext::getObjCObjectType(QualType BaseType,
3376 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003377 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003378 // If the base type is an interface and there aren't any protocols
3379 // to add, then the interface type will do just fine.
3380 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3381 return BaseType;
3382
3383 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003384 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003385 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003386 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003387 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3388 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003389
John McCall8b07ec22010-05-15 11:32:37 +00003390 // Build the canonical type, which has the canonical base type and
3391 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003392 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003393 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3394 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3395 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003396 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003397 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003398 unsigned UniqueCount = NumProtocols;
3399
John McCallfc93cf92009-10-22 22:37:11 +00003400 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003401 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3402 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003403 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003404 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3405 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003406 }
3407
3408 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003409 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3410 }
3411
3412 unsigned Size = sizeof(ObjCObjectTypeImpl);
3413 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3414 void *Mem = Allocate(Size, TypeAlignment);
3415 ObjCObjectTypeImpl *T =
3416 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3417
3418 Types.push_back(T);
3419 ObjCObjectTypes.InsertNode(T, InsertPos);
3420 return QualType(T, 0);
3421}
3422
3423/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3424/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003425QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003426 llvm::FoldingSetNodeID ID;
3427 ObjCObjectPointerType::Profile(ID, ObjectT);
3428
3429 void *InsertPos = 0;
3430 if (ObjCObjectPointerType *QT =
3431 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3432 return QualType(QT, 0);
3433
3434 // Find the canonical object type.
3435 QualType Canonical;
3436 if (!ObjectT.isCanonical()) {
3437 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3438
3439 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003440 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3441 }
3442
Douglas Gregorf85bee62010-02-08 22:59:26 +00003443 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003444 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3445 ObjCObjectPointerType *QType =
3446 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003447
Steve Narofffb4330f2009-06-17 22:40:22 +00003448 Types.push_back(QType);
3449 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003450 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003451}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003452
Douglas Gregor1c283312010-08-11 12:19:30 +00003453/// getObjCInterfaceType - Return the unique reference to the type for the
3454/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003455QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3456 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003457 if (Decl->TypeForDecl)
3458 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003459
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003460 if (PrevDecl) {
3461 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3462 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3463 return QualType(PrevDecl->TypeForDecl, 0);
3464 }
3465
Douglas Gregor7671e532011-12-16 16:34:57 +00003466 // Prefer the definition, if there is one.
3467 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3468 Decl = Def;
3469
Douglas Gregor1c283312010-08-11 12:19:30 +00003470 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3471 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3472 Decl->TypeForDecl = T;
3473 Types.push_back(T);
3474 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003475}
3476
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003477/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3478/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003479/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003480/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003481/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003482QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003483 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003484 if (tofExpr->isTypeDependent()) {
3485 llvm::FoldingSetNodeID ID;
3486 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003487
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003488 void *InsertPos = 0;
3489 DependentTypeOfExprType *Canon
3490 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3491 if (Canon) {
3492 // We already have a "canonical" version of an identical, dependent
3493 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003494 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003495 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003496 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003497 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003498 Canon
3499 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003500 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3501 toe = Canon;
3502 }
3503 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003504 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003505 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003506 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003507 Types.push_back(toe);
3508 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003509}
3510
Steve Naroffa773cd52007-08-01 18:02:17 +00003511/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3512/// TypeOfType AST's. The only motivation to unique these nodes would be
3513/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003514/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003515/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003516QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003517 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003518 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003519 Types.push_back(tot);
3520 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003521}
3522
Anders Carlssonad6bd352009-06-24 21:24:56 +00003523
Anders Carlsson81df7b82009-06-24 19:06:50 +00003524/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3525/// DecltypeType AST's. The only motivation to unique these nodes would be
3526/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003527/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003528/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003529QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003530 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003531
3532 // C++0x [temp.type]p2:
3533 // If an expression e involves a template parameter, decltype(e) denotes a
3534 // unique dependent type. Two such decltype-specifiers refer to the same
3535 // type only if their expressions are equivalent (14.5.6.1).
3536 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003537 llvm::FoldingSetNodeID ID;
3538 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003539
Douglas Gregora21f6c32009-07-30 23:36:40 +00003540 void *InsertPos = 0;
3541 DependentDecltypeType *Canon
3542 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3543 if (Canon) {
3544 // We already have a "canonical" version of an equivalent, dependent
3545 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003546 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003547 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003548 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003549 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003550 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003551 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3552 dt = Canon;
3553 }
3554 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003555 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3556 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003557 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003558 Types.push_back(dt);
3559 return QualType(dt, 0);
3560}
3561
Alexis Hunte852b102011-05-24 22:41:36 +00003562/// getUnaryTransformationType - We don't unique these, since the memory
3563/// savings are minimal and these are rare.
3564QualType ASTContext::getUnaryTransformType(QualType BaseType,
3565 QualType UnderlyingType,
3566 UnaryTransformType::UTTKind Kind)
3567 const {
3568 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003569 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3570 Kind,
3571 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003572 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003573 Types.push_back(Ty);
3574 return QualType(Ty, 0);
3575}
3576
Richard Smith2a7d4812013-05-04 07:00:32 +00003577/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3578/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3579/// canonical deduced-but-dependent 'auto' type.
3580QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Richard Smith27d807c2013-04-30 13:56:41 +00003581 bool IsDependent) const {
Richard Smith2a7d4812013-05-04 07:00:32 +00003582 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
3583 return getAutoDeductType();
3584
3585 // Look in the folding set for an existing type.
Richard Smithb2bc2e62011-02-21 20:05:19 +00003586 void *InsertPos = 0;
Richard Smith2a7d4812013-05-04 07:00:32 +00003587 llvm::FoldingSetNodeID ID;
3588 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
3589 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3590 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003591
Richard Smith74aeef52013-04-26 16:15:35 +00003592 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003593 IsDecltypeAuto,
3594 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003595 Types.push_back(AT);
3596 if (InsertPos)
3597 AutoTypes.InsertNode(AT, InsertPos);
3598 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003599}
3600
Eli Friedman0dfb8892011-10-06 23:00:33 +00003601/// getAtomicType - Return the uniqued reference to the atomic type for
3602/// the given value type.
3603QualType ASTContext::getAtomicType(QualType T) const {
3604 // Unique pointers, to guarantee there is only one pointer of a particular
3605 // structure.
3606 llvm::FoldingSetNodeID ID;
3607 AtomicType::Profile(ID, T);
3608
3609 void *InsertPos = 0;
3610 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3611 return QualType(AT, 0);
3612
3613 // If the atomic value type isn't canonical, this won't be a canonical type
3614 // either, so fill in the canonical type field.
3615 QualType Canonical;
3616 if (!T.isCanonical()) {
3617 Canonical = getAtomicType(getCanonicalType(T));
3618
3619 // Get the new insert position for the node we care about.
3620 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3621 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3622 }
3623 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3624 Types.push_back(New);
3625 AtomicTypes.InsertNode(New, InsertPos);
3626 return QualType(New, 0);
3627}
3628
Richard Smith02e85f32011-04-14 22:09:26 +00003629/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3630QualType ASTContext::getAutoDeductType() const {
3631 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00003632 AutoDeductTy = QualType(
3633 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
3634 /*dependent*/false),
3635 0);
Richard Smith02e85f32011-04-14 22:09:26 +00003636 return AutoDeductTy;
3637}
3638
3639/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3640QualType ASTContext::getAutoRRefDeductType() const {
3641 if (AutoRRefDeductTy.isNull())
3642 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3643 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3644 return AutoRRefDeductTy;
3645}
3646
Chris Lattnerfb072462007-01-23 05:45:31 +00003647/// getTagDeclType - Return the unique reference to the type for the
3648/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003649QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003650 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003651 // FIXME: What is the design on getTagDeclType when it requires casting
3652 // away const? mutable?
3653 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003654}
3655
Mike Stump11289f42009-09-09 15:08:12 +00003656/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3657/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3658/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003659CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003660 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003661}
Chris Lattnerfb072462007-01-23 05:45:31 +00003662
Hans Wennborg27541db2011-10-27 08:29:09 +00003663/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3664CanQualType ASTContext::getIntMaxType() const {
3665 return getFromTargetType(Target->getIntMaxType());
3666}
3667
3668/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3669CanQualType ASTContext::getUIntMaxType() const {
3670 return getFromTargetType(Target->getUIntMaxType());
3671}
3672
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003673/// getSignedWCharType - Return the type of "signed wchar_t".
3674/// Used when in C++, as a GCC extension.
3675QualType ASTContext::getSignedWCharType() const {
3676 // FIXME: derive from "Target" ?
3677 return WCharTy;
3678}
3679
3680/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3681/// Used when in C++, as a GCC extension.
3682QualType ASTContext::getUnsignedWCharType() const {
3683 // FIXME: derive from "Target" ?
3684 return UnsignedIntTy;
3685}
3686
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00003687QualType ASTContext::getIntPtrType() const {
3688 return getFromTargetType(Target->getIntPtrType());
3689}
3690
3691QualType ASTContext::getUIntPtrType() const {
3692 return getCorrespondingUnsignedType(getIntPtrType());
3693}
3694
Hans Wennborg27541db2011-10-27 08:29:09 +00003695/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003696/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3697QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003698 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003699}
3700
Eli Friedman4e91899e2012-11-27 02:58:24 +00003701/// \brief Return the unique type for "pid_t" defined in
3702/// <sys/types.h>. We need this to compute the correct type for vfork().
3703QualType ASTContext::getProcessIDType() const {
3704 return getFromTargetType(Target->getProcessIDType());
3705}
3706
Chris Lattnera21ad802008-04-02 05:18:44 +00003707//===----------------------------------------------------------------------===//
3708// Type Operators
3709//===----------------------------------------------------------------------===//
3710
Jay Foad39c79802011-01-12 09:06:06 +00003711CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003712 // Push qualifiers into arrays, and then discard any remaining
3713 // qualifiers.
3714 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003715 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003716 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003717 QualType Result;
3718 if (isa<ArrayType>(Ty)) {
3719 Result = getArrayDecayedType(QualType(Ty,0));
3720 } else if (isa<FunctionType>(Ty)) {
3721 Result = getPointerType(QualType(Ty, 0));
3722 } else {
3723 Result = QualType(Ty, 0);
3724 }
3725
3726 return CanQualType::CreateUnsafe(Result);
3727}
3728
John McCall6c9dd522011-01-18 07:41:22 +00003729QualType ASTContext::getUnqualifiedArrayType(QualType type,
3730 Qualifiers &quals) {
3731 SplitQualType splitType = type.getSplitUnqualifiedType();
3732
3733 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3734 // the unqualified desugared type and then drops it on the floor.
3735 // We then have to strip that sugar back off with
3736 // getUnqualifiedDesugaredType(), which is silly.
3737 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003738 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003739
3740 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003741 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003742 quals = splitType.Quals;
3743 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003744 }
3745
John McCall6c9dd522011-01-18 07:41:22 +00003746 // Otherwise, recurse on the array's element type.
3747 QualType elementType = AT->getElementType();
3748 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3749
3750 // If that didn't change the element type, AT has no qualifiers, so we
3751 // can just use the results in splitType.
3752 if (elementType == unqualElementType) {
3753 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003754 quals = splitType.Quals;
3755 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003756 }
3757
3758 // Otherwise, add in the qualifiers from the outermost type, then
3759 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003760 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003761
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003762 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003763 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003764 CAT->getSizeModifier(), 0);
3765 }
3766
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003767 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003768 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003769 }
3770
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003771 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003772 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003773 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003774 VAT->getSizeModifier(),
3775 VAT->getIndexTypeCVRQualifiers(),
3776 VAT->getBracketsRange());
3777 }
3778
3779 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003780 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003781 DSAT->getSizeModifier(), 0,
3782 SourceRange());
3783}
3784
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003785/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3786/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3787/// they point to and return true. If T1 and T2 aren't pointer types
3788/// or pointer-to-member types, or if they are not similar at this
3789/// level, returns false and leaves T1 and T2 unchanged. Top-level
3790/// qualifiers on T1 and T2 are ignored. This function will typically
3791/// be called in a loop that successively "unwraps" pointer and
3792/// pointer-to-member types to compare them at each level.
3793bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3794 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3795 *T2PtrType = T2->getAs<PointerType>();
3796 if (T1PtrType && T2PtrType) {
3797 T1 = T1PtrType->getPointeeType();
3798 T2 = T2PtrType->getPointeeType();
3799 return true;
3800 }
3801
3802 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3803 *T2MPType = T2->getAs<MemberPointerType>();
3804 if (T1MPType && T2MPType &&
3805 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3806 QualType(T2MPType->getClass(), 0))) {
3807 T1 = T1MPType->getPointeeType();
3808 T2 = T2MPType->getPointeeType();
3809 return true;
3810 }
3811
David Blaikiebbafb8a2012-03-11 07:00:24 +00003812 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003813 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3814 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3815 if (T1OPType && T2OPType) {
3816 T1 = T1OPType->getPointeeType();
3817 T2 = T2OPType->getPointeeType();
3818 return true;
3819 }
3820 }
3821
3822 // FIXME: Block pointers, too?
3823
3824 return false;
3825}
3826
Jay Foad39c79802011-01-12 09:06:06 +00003827DeclarationNameInfo
3828ASTContext::getNameForTemplate(TemplateName Name,
3829 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003830 switch (Name.getKind()) {
3831 case TemplateName::QualifiedTemplate:
3832 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003833 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003834 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3835 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003836
John McCalld9dfe3a2011-06-30 08:33:18 +00003837 case TemplateName::OverloadedTemplate: {
3838 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3839 // DNInfo work in progress: CHECKME: what about DNLoc?
3840 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3841 }
3842
3843 case TemplateName::DependentTemplate: {
3844 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003845 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003846 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003847 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3848 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003849 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003850 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3851 // DNInfo work in progress: FIXME: source locations?
3852 DeclarationNameLoc DNLoc;
3853 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3854 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3855 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003856 }
3857 }
3858
John McCalld9dfe3a2011-06-30 08:33:18 +00003859 case TemplateName::SubstTemplateTemplateParm: {
3860 SubstTemplateTemplateParmStorage *subst
3861 = Name.getAsSubstTemplateTemplateParm();
3862 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3863 NameLoc);
3864 }
3865
3866 case TemplateName::SubstTemplateTemplateParmPack: {
3867 SubstTemplateTemplateParmPackStorage *subst
3868 = Name.getAsSubstTemplateTemplateParmPack();
3869 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3870 NameLoc);
3871 }
3872 }
3873
3874 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003875}
3876
Jay Foad39c79802011-01-12 09:06:06 +00003877TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003878 switch (Name.getKind()) {
3879 case TemplateName::QualifiedTemplate:
3880 case TemplateName::Template: {
3881 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003882 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003883 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003884 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3885
3886 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003887 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003888 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003889
John McCalld9dfe3a2011-06-30 08:33:18 +00003890 case TemplateName::OverloadedTemplate:
3891 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003892
John McCalld9dfe3a2011-06-30 08:33:18 +00003893 case TemplateName::DependentTemplate: {
3894 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3895 assert(DTN && "Non-dependent template names must refer to template decls.");
3896 return DTN->CanonicalTemplateName;
3897 }
3898
3899 case TemplateName::SubstTemplateTemplateParm: {
3900 SubstTemplateTemplateParmStorage *subst
3901 = Name.getAsSubstTemplateTemplateParm();
3902 return getCanonicalTemplateName(subst->getReplacement());
3903 }
3904
3905 case TemplateName::SubstTemplateTemplateParmPack: {
3906 SubstTemplateTemplateParmPackStorage *subst
3907 = Name.getAsSubstTemplateTemplateParmPack();
3908 TemplateTemplateParmDecl *canonParameter
3909 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3910 TemplateArgument canonArgPack
3911 = getCanonicalTemplateArgument(subst->getArgumentPack());
3912 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3913 }
3914 }
3915
3916 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003917}
3918
Douglas Gregoradee3e32009-11-11 23:06:43 +00003919bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3920 X = getCanonicalTemplateName(X);
3921 Y = getCanonicalTemplateName(Y);
3922 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3923}
3924
Mike Stump11289f42009-09-09 15:08:12 +00003925TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003926ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003927 switch (Arg.getKind()) {
3928 case TemplateArgument::Null:
3929 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003930
Douglas Gregora8e02e72009-07-28 23:00:59 +00003931 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003932 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003933
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003934 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00003935 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
3936 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003937 }
Mike Stump11289f42009-09-09 15:08:12 +00003938
Eli Friedmanb826a002012-09-26 02:36:12 +00003939 case TemplateArgument::NullPtr:
3940 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
3941 /*isNullPtr*/true);
3942
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003943 case TemplateArgument::Template:
3944 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003945
3946 case TemplateArgument::TemplateExpansion:
3947 return TemplateArgument(getCanonicalTemplateName(
3948 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003949 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003950
Douglas Gregora8e02e72009-07-28 23:00:59 +00003951 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003952 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003953
Douglas Gregora8e02e72009-07-28 23:00:59 +00003954 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003955 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003956
Douglas Gregora8e02e72009-07-28 23:00:59 +00003957 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003958 if (Arg.pack_size() == 0)
3959 return Arg;
3960
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003961 TemplateArgument *CanonArgs
3962 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003963 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003964 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003965 AEnd = Arg.pack_end();
3966 A != AEnd; (void)++A, ++Idx)
3967 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003968
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003969 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003970 }
3971 }
3972
3973 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003974 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003975}
3976
Douglas Gregor333489b2009-03-27 23:10:48 +00003977NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003978ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003979 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003980 return 0;
3981
3982 switch (NNS->getKind()) {
3983 case NestedNameSpecifier::Identifier:
3984 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003985 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003986 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3987 NNS->getAsIdentifier());
3988
3989 case NestedNameSpecifier::Namespace:
3990 // A namespace is canonical; build a nested-name-specifier with
3991 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003992 return NestedNameSpecifier::Create(*this, 0,
3993 NNS->getAsNamespace()->getOriginalNamespace());
3994
3995 case NestedNameSpecifier::NamespaceAlias:
3996 // A namespace is canonical; build a nested-name-specifier with
3997 // this namespace and no prefix.
3998 return NestedNameSpecifier::Create(*this, 0,
3999 NNS->getAsNamespaceAlias()->getNamespace()
4000 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004001
4002 case NestedNameSpecifier::TypeSpec:
4003 case NestedNameSpecifier::TypeSpecWithTemplate: {
4004 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004005
4006 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4007 // break it apart into its prefix and identifier, then reconsititute those
4008 // as the canonical nested-name-specifier. This is required to canonicalize
4009 // a dependent nested-name-specifier involving typedefs of dependent-name
4010 // types, e.g.,
4011 // typedef typename T::type T1;
4012 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004013 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4014 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004015 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004016
Eli Friedman5358a0a2012-03-03 04:09:56 +00004017 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4018 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4019 // first place?
John McCall33ddac02011-01-19 10:06:00 +00004020 return NestedNameSpecifier::Create(*this, 0, false,
4021 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004022 }
4023
4024 case NestedNameSpecifier::Global:
4025 // The global specifier is canonical and unique.
4026 return NNS;
4027 }
4028
David Blaikie8a40f702012-01-17 06:56:22 +00004029 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004030}
4031
Chris Lattner7adf0762008-08-04 07:31:14 +00004032
Jay Foad39c79802011-01-12 09:06:06 +00004033const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004034 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004035 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004036 // Handle the common positive case fast.
4037 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4038 return AT;
4039 }
Mike Stump11289f42009-09-09 15:08:12 +00004040
John McCall8ccfcb52009-09-24 19:53:00 +00004041 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004042 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00004043 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004044
John McCall8ccfcb52009-09-24 19:53:00 +00004045 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004046 // implements C99 6.7.3p8: "If the specification of an array type includes
4047 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004048
Chris Lattner7adf0762008-08-04 07:31:14 +00004049 // If we get here, we either have type qualifiers on the type, or we have
4050 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004051 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004052
John McCall33ddac02011-01-19 10:06:00 +00004053 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004054 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004055
Chris Lattner7adf0762008-08-04 07:31:14 +00004056 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004057 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00004058 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004059 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004060
Chris Lattner7adf0762008-08-04 07:31:14 +00004061 // Otherwise, we have an array and we have qualifiers on it. Push the
4062 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004063 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004064
Chris Lattner7adf0762008-08-04 07:31:14 +00004065 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4066 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4067 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004068 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004069 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4070 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4071 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004072 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004073
Mike Stump11289f42009-09-09 15:08:12 +00004074 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004075 = dyn_cast<DependentSizedArrayType>(ATy))
4076 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004077 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004078 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004079 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004080 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004081 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004082
Chris Lattner7adf0762008-08-04 07:31:14 +00004083 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004084 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004085 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004086 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004087 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004088 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004089}
4090
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004091QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004092 // C99 6.7.5.3p7:
4093 // A declaration of a parameter as "array of type" shall be
4094 // adjusted to "qualified pointer to type", where the type
4095 // qualifiers (if any) are those specified within the [ and ] of
4096 // the array type derivation.
4097 if (T->isArrayType())
4098 return getArrayDecayedType(T);
4099
4100 // C99 6.7.5.3p8:
4101 // A declaration of a parameter as "function returning type"
4102 // shall be adjusted to "pointer to function returning type", as
4103 // in 6.3.2.1.
4104 if (T->isFunctionType())
4105 return getPointerType(T);
4106
4107 return T;
4108}
4109
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004110QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004111 T = getVariableArrayDecayedType(T);
4112 T = getAdjustedParameterType(T);
4113 return T.getUnqualifiedType();
4114}
4115
Chris Lattnera21ad802008-04-02 05:18:44 +00004116/// getArrayDecayedType - Return the properly qualified result of decaying the
4117/// specified array type to a pointer. This operation is non-trivial when
4118/// handling typedefs etc. The canonical type of "T" must be an array type,
4119/// this returns a pointer to a properly qualified element of the array.
4120///
4121/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004122QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004123 // Get the element type with 'getAsArrayType' so that we don't lose any
4124 // typedefs in the element type of the array. This also handles propagation
4125 // of type qualifiers from the array type into the element type if present
4126 // (C99 6.7.3p8).
4127 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4128 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004129
Chris Lattner7adf0762008-08-04 07:31:14 +00004130 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004131
4132 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004133 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004134}
4135
John McCall33ddac02011-01-19 10:06:00 +00004136QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4137 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004138}
4139
John McCall33ddac02011-01-19 10:06:00 +00004140QualType ASTContext::getBaseElementType(QualType type) const {
4141 Qualifiers qs;
4142 while (true) {
4143 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004144 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004145 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004146
John McCall33ddac02011-01-19 10:06:00 +00004147 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004148 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004149 }
Mike Stump11289f42009-09-09 15:08:12 +00004150
John McCall33ddac02011-01-19 10:06:00 +00004151 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004152}
4153
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004154/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004155uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004156ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4157 uint64_t ElementCount = 1;
4158 do {
4159 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004160 CA = dyn_cast_or_null<ConstantArrayType>(
4161 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004162 } while (CA);
4163 return ElementCount;
4164}
4165
Steve Naroff0af91202007-04-27 21:51:21 +00004166/// getFloatingRank - Return a relative rank for floating point types.
4167/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004168static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004169 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004170 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004171
John McCall9dd450b2009-09-21 23:43:11 +00004172 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4173 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004174 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004175 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004176 case BuiltinType::Float: return FloatRank;
4177 case BuiltinType::Double: return DoubleRank;
4178 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004179 }
4180}
4181
Mike Stump11289f42009-09-09 15:08:12 +00004182/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4183/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004184/// 'typeDomain' is a real floating point or complex type.
4185/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004186QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4187 QualType Domain) const {
4188 FloatingRank EltRank = getFloatingRank(Size);
4189 if (Domain->isComplexType()) {
4190 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004191 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004192 case FloatRank: return FloatComplexTy;
4193 case DoubleRank: return DoubleComplexTy;
4194 case LongDoubleRank: return LongDoubleComplexTy;
4195 }
Steve Naroff0af91202007-04-27 21:51:21 +00004196 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004197
4198 assert(Domain->isRealFloatingType() && "Unknown domain!");
4199 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004200 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004201 case FloatRank: return FloatTy;
4202 case DoubleRank: return DoubleTy;
4203 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004204 }
David Blaikief47fa302012-01-17 02:30:50 +00004205 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004206}
4207
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004208/// getFloatingTypeOrder - Compare the rank of the two specified floating
4209/// point types, ignoring the domain of the type (i.e. 'double' ==
4210/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004211/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004212int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004213 FloatingRank LHSR = getFloatingRank(LHS);
4214 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004215
Chris Lattnerb90739d2008-04-06 23:38:49 +00004216 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004217 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004218 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004219 return 1;
4220 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004221}
4222
Chris Lattner76a00cf2008-04-06 22:59:24 +00004223/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4224/// routine will assert if passed a built-in type that isn't an integer or enum,
4225/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004226unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004227 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004228
Chris Lattner76a00cf2008-04-06 22:59:24 +00004229 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004230 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004231 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004232 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004233 case BuiltinType::Char_S:
4234 case BuiltinType::Char_U:
4235 case BuiltinType::SChar:
4236 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004237 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004238 case BuiltinType::Short:
4239 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004240 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004241 case BuiltinType::Int:
4242 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004243 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004244 case BuiltinType::Long:
4245 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004246 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004247 case BuiltinType::LongLong:
4248 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004249 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004250 case BuiltinType::Int128:
4251 case BuiltinType::UInt128:
4252 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004253 }
4254}
4255
Eli Friedman629ffb92009-08-20 04:21:42 +00004256/// \brief Whether this is a promotable bitfield reference according
4257/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4258///
4259/// \returns the type this bit-field will promote to, or NULL if no
4260/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004261QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004262 if (E->isTypeDependent() || E->isValueDependent())
4263 return QualType();
4264
Eli Friedman629ffb92009-08-20 04:21:42 +00004265 FieldDecl *Field = E->getBitField();
4266 if (!Field)
4267 return QualType();
4268
4269 QualType FT = Field->getType();
4270
Richard Smithcaf33902011-10-10 18:28:20 +00004271 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004272 uint64_t IntSize = getTypeSize(IntTy);
4273 // GCC extension compatibility: if the bit-field size is less than or equal
4274 // to the size of int, it gets promoted no matter what its type is.
4275 // For instance, unsigned long bf : 4 gets promoted to signed int.
4276 if (BitWidth < IntSize)
4277 return IntTy;
4278
4279 if (BitWidth == IntSize)
4280 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4281
4282 // Types bigger than int are not subject to promotions, and therefore act
4283 // like the base type.
4284 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4285 // is ridiculous.
4286 return QualType();
4287}
4288
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004289/// getPromotedIntegerType - Returns the type that Promotable will
4290/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4291/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004292QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004293 assert(!Promotable.isNull());
4294 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004295 if (const EnumType *ET = Promotable->getAs<EnumType>())
4296 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004297
4298 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4299 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4300 // (3.9.1) can be converted to a prvalue of the first of the following
4301 // types that can represent all the values of its underlying type:
4302 // int, unsigned int, long int, unsigned long int, long long int, or
4303 // unsigned long long int [...]
4304 // FIXME: Is there some better way to compute this?
4305 if (BT->getKind() == BuiltinType::WChar_S ||
4306 BT->getKind() == BuiltinType::WChar_U ||
4307 BT->getKind() == BuiltinType::Char16 ||
4308 BT->getKind() == BuiltinType::Char32) {
4309 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4310 uint64_t FromSize = getTypeSize(BT);
4311 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4312 LongLongTy, UnsignedLongLongTy };
4313 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4314 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4315 if (FromSize < ToSize ||
4316 (FromSize == ToSize &&
4317 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4318 return PromoteTypes[Idx];
4319 }
4320 llvm_unreachable("char type should fit into long long");
4321 }
4322 }
4323
4324 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004325 if (Promotable->isSignedIntegerType())
4326 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004327 uint64_t PromotableSize = getIntWidth(Promotable);
4328 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004329 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4330 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4331}
4332
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004333/// \brief Recurses in pointer/array types until it finds an objc retainable
4334/// type and returns its ownership.
4335Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4336 while (!T.isNull()) {
4337 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4338 return T.getObjCLifetime();
4339 if (T->isArrayType())
4340 T = getBaseElementType(T);
4341 else if (const PointerType *PT = T->getAs<PointerType>())
4342 T = PT->getPointeeType();
4343 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004344 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004345 else
4346 break;
4347 }
4348
4349 return Qualifiers::OCL_None;
4350}
4351
Mike Stump11289f42009-09-09 15:08:12 +00004352/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004353/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004354/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004355int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004356 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4357 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004358 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004359
Chris Lattner76a00cf2008-04-06 22:59:24 +00004360 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4361 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004362
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004363 unsigned LHSRank = getIntegerRank(LHSC);
4364 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004365
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004366 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4367 if (LHSRank == RHSRank) return 0;
4368 return LHSRank > RHSRank ? 1 : -1;
4369 }
Mike Stump11289f42009-09-09 15:08:12 +00004370
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004371 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4372 if (LHSUnsigned) {
4373 // If the unsigned [LHS] type is larger, return it.
4374 if (LHSRank >= RHSRank)
4375 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004376
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004377 // If the signed type can represent all values of the unsigned type, it
4378 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004379 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004380 return -1;
4381 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004382
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004383 // If the unsigned [RHS] type is larger, return it.
4384 if (RHSRank >= LHSRank)
4385 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004386
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004387 // If the signed type can represent all values of the unsigned type, it
4388 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004389 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004390 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004391}
Anders Carlsson98f07902007-08-17 05:31:46 +00004392
Anders Carlsson6d417272009-11-14 21:45:58 +00004393static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004394CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4395 DeclContext *DC, IdentifierInfo *Id) {
4396 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004397 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004398 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004399 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004400 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004401}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004402
Mike Stump11289f42009-09-09 15:08:12 +00004403// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004404QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004405 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00004406 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004407 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004408 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00004409 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004410
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004411 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004412
Anders Carlsson98f07902007-08-17 05:31:46 +00004413 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004414 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004415 // int flags;
4416 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004417 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004418 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004419 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004420 FieldTypes[3] = LongTy;
4421
Anders Carlsson98f07902007-08-17 05:31:46 +00004422 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004423 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004424 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004425 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004426 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004427 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004428 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004429 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004430 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004431 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004432 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004433 }
4434
Douglas Gregord5058122010-02-11 01:19:42 +00004435 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004436 }
Mike Stump11289f42009-09-09 15:08:12 +00004437
Anders Carlsson98f07902007-08-17 05:31:46 +00004438 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004439}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004440
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004441QualType ASTContext::getObjCSuperType() const {
4442 if (ObjCSuperType.isNull()) {
4443 RecordDecl *ObjCSuperTypeDecl =
4444 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4445 TUDecl->addDecl(ObjCSuperTypeDecl);
4446 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4447 }
4448 return ObjCSuperType;
4449}
4450
Douglas Gregor512b0772009-04-23 22:29:11 +00004451void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004452 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004453 assert(Rec && "Invalid CFConstantStringType");
4454 CFConstantStringTypeDecl = Rec->getDecl();
4455}
4456
Jay Foad39c79802011-01-12 09:06:06 +00004457QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004458 if (BlockDescriptorType)
4459 return getTagDeclType(BlockDescriptorType);
4460
4461 RecordDecl *T;
4462 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004463 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004464 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00004465 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004466
4467 QualType FieldTypes[] = {
4468 UnsignedLongTy,
4469 UnsignedLongTy,
4470 };
4471
4472 const char *FieldNames[] = {
4473 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004474 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004475 };
4476
4477 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004478 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00004479 SourceLocation(),
4480 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004481 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00004482 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004483 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004484 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004485 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00004486 T->addDecl(Field);
4487 }
4488
Douglas Gregord5058122010-02-11 01:19:42 +00004489 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004490
4491 BlockDescriptorType = T;
4492
4493 return getTagDeclType(BlockDescriptorType);
4494}
4495
Jay Foad39c79802011-01-12 09:06:06 +00004496QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004497 if (BlockDescriptorExtendedType)
4498 return getTagDeclType(BlockDescriptorExtendedType);
4499
4500 RecordDecl *T;
4501 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004502 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004503 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00004504 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004505
4506 QualType FieldTypes[] = {
4507 UnsignedLongTy,
4508 UnsignedLongTy,
4509 getPointerType(VoidPtrTy),
4510 getPointerType(VoidPtrTy)
4511 };
4512
4513 const char *FieldNames[] = {
4514 "reserved",
4515 "Size",
4516 "CopyFuncPtr",
4517 "DestroyFuncPtr"
4518 };
4519
4520 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004521 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004522 SourceLocation(),
4523 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004524 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004525 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004526 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004527 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004528 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004529 T->addDecl(Field);
4530 }
4531
Douglas Gregord5058122010-02-11 01:19:42 +00004532 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004533
4534 BlockDescriptorExtendedType = T;
4535
4536 return getTagDeclType(BlockDescriptorExtendedType);
4537}
4538
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004539/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4540/// requires copy/dispose. Note that this must match the logic
4541/// in buildByrefHelpers.
4542bool ASTContext::BlockRequiresCopying(QualType Ty,
4543 const VarDecl *D) {
4544 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4545 const Expr *copyExpr = getBlockVarCopyInits(D);
4546 if (!copyExpr && record->hasTrivialDestructor()) return false;
4547
Mike Stump94967902009-10-21 18:16:27 +00004548 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004549 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004550
4551 if (!Ty->isObjCRetainableType()) return false;
4552
4553 Qualifiers qs = Ty.getQualifiers();
4554
4555 // If we have lifetime, that dominates.
4556 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4557 assert(getLangOpts().ObjCAutoRefCount);
4558
4559 switch (lifetime) {
4560 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4561
4562 // These are just bits as far as the runtime is concerned.
4563 case Qualifiers::OCL_ExplicitNone:
4564 case Qualifiers::OCL_Autoreleasing:
4565 return false;
4566
4567 // Tell the runtime that this is ARC __weak, called by the
4568 // byref routines.
4569 case Qualifiers::OCL_Weak:
4570 // ARC __strong __block variables need to be retained.
4571 case Qualifiers::OCL_Strong:
4572 return true;
4573 }
4574 llvm_unreachable("fell out of lifetime switch!");
4575 }
4576 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4577 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004578}
4579
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004580bool ASTContext::getByrefLifetime(QualType Ty,
4581 Qualifiers::ObjCLifetime &LifeTime,
4582 bool &HasByrefExtendedLayout) const {
4583
4584 if (!getLangOpts().ObjC1 ||
4585 getLangOpts().getGC() != LangOptions::NonGC)
4586 return false;
4587
4588 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004589 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004590 HasByrefExtendedLayout = true;
4591 LifeTime = Qualifiers::OCL_None;
4592 }
4593 else if (getLangOpts().ObjCAutoRefCount)
4594 LifeTime = Ty.getObjCLifetime();
4595 // MRR.
4596 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4597 LifeTime = Qualifiers::OCL_ExplicitNone;
4598 else
4599 LifeTime = Qualifiers::OCL_None;
4600 return true;
4601}
4602
Douglas Gregorbab8a962011-09-08 01:46:34 +00004603TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4604 if (!ObjCInstanceTypeDecl)
4605 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4606 getTranslationUnitDecl(),
4607 SourceLocation(),
4608 SourceLocation(),
4609 &Idents.get("instancetype"),
4610 getTrivialTypeSourceInfo(getObjCIdType()));
4611 return ObjCInstanceTypeDecl;
4612}
4613
Anders Carlsson18acd442007-10-29 06:33:42 +00004614// This returns true if a type has been typedefed to BOOL:
4615// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004616static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004617 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004618 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4619 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004620
Anders Carlssond8499822007-10-29 05:01:08 +00004621 return false;
4622}
4623
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004624/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004625/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004626CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004627 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4628 return CharUnits::Zero();
4629
Ken Dyck40775002010-01-11 17:06:35 +00004630 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004631
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004632 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004633 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004634 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004635 // Treat arrays as pointers, since that's how they're passed in.
4636 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004637 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004638 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004639}
4640
4641static inline
4642std::string charUnitsToString(const CharUnits &CU) {
4643 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004644}
4645
John McCall351762c2011-02-07 10:33:21 +00004646/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004647/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004648std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4649 std::string S;
4650
David Chisnall950a9512009-11-17 19:33:30 +00004651 const BlockDecl *Decl = Expr->getBlockDecl();
4652 QualType BlockTy =
4653 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4654 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004655 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004656 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4657 BlockTy->getAs<FunctionType>()->getResultType(),
4658 S, true /*Extended*/);
4659 else
4660 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4661 S);
David Chisnall950a9512009-11-17 19:33:30 +00004662 // Compute size of all parameters.
4663 // Start with computing size of a pointer in number of bytes.
4664 // FIXME: There might(should) be a better way of doing this computation!
4665 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004666 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4667 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004668 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004669 E = Decl->param_end(); PI != E; ++PI) {
4670 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004671 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004672 if (sz.isZero())
4673 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004674 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004675 ParmOffset += sz;
4676 }
4677 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004678 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004679 // Block pointer and offset.
4680 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004681
4682 // Argument types.
4683 ParmOffset = PtrSize;
4684 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4685 Decl->param_end(); PI != E; ++PI) {
4686 ParmVarDecl *PVDecl = *PI;
4687 QualType PType = PVDecl->getOriginalType();
4688 if (const ArrayType *AT =
4689 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4690 // Use array's original type only if it has known number of
4691 // elements.
4692 if (!isa<ConstantArrayType>(AT))
4693 PType = PVDecl->getType();
4694 } else if (PType->isFunctionType())
4695 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004696 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004697 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4698 S, true /*Extended*/);
4699 else
4700 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004701 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004702 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004703 }
John McCall351762c2011-02-07 10:33:21 +00004704
4705 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004706}
4707
Douglas Gregora9d84932011-05-27 01:19:52 +00004708bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004709 std::string& S) {
4710 // Encode result type.
4711 getObjCEncodingForType(Decl->getResultType(), S);
4712 CharUnits ParmOffset;
4713 // Compute size of all parameters.
4714 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4715 E = Decl->param_end(); PI != E; ++PI) {
4716 QualType PType = (*PI)->getType();
4717 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004718 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004719 continue;
4720
David Chisnall50e4eba2010-12-30 14:05:53 +00004721 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004722 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004723 ParmOffset += sz;
4724 }
4725 S += charUnitsToString(ParmOffset);
4726 ParmOffset = CharUnits::Zero();
4727
4728 // Argument types.
4729 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4730 E = Decl->param_end(); PI != E; ++PI) {
4731 ParmVarDecl *PVDecl = *PI;
4732 QualType PType = PVDecl->getOriginalType();
4733 if (const ArrayType *AT =
4734 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4735 // Use array's original type only if it has known number of
4736 // elements.
4737 if (!isa<ConstantArrayType>(AT))
4738 PType = PVDecl->getType();
4739 } else if (PType->isFunctionType())
4740 PType = PVDecl->getType();
4741 getObjCEncodingForType(PType, S);
4742 S += charUnitsToString(ParmOffset);
4743 ParmOffset += getObjCEncodingTypeSize(PType);
4744 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004745
4746 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004747}
4748
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004749/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4750/// method parameter or return type. If Extended, include class names and
4751/// block object types.
4752void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4753 QualType T, std::string& S,
4754 bool Extended) const {
4755 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4756 getObjCEncodingForTypeQualifier(QT, S);
4757 // Encode parameter type.
4758 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4759 true /*OutermostType*/,
4760 false /*EncodingProperty*/,
4761 false /*StructField*/,
4762 Extended /*EncodeBlockParameters*/,
4763 Extended /*EncodeClassNames*/);
4764}
4765
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004766/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004767/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004768bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004769 std::string& S,
4770 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004771 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004772 // Encode return type.
4773 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4774 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004775 // Compute size of all parameters.
4776 // Start with computing size of a pointer in number of bytes.
4777 // FIXME: There might(should) be a better way of doing this computation!
4778 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004779 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004780 // The first two arguments (self and _cmd) are pointers; account for
4781 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004782 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004783 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004784 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004785 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004786 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004787 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004788 continue;
4789
Ken Dyck40775002010-01-11 17:06:35 +00004790 assert (sz.isPositive() &&
4791 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004792 ParmOffset += sz;
4793 }
Ken Dyck40775002010-01-11 17:06:35 +00004794 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004795 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004796 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004797
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004798 // Argument types.
4799 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004800 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004801 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004802 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004803 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004804 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004805 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4806 // Use array's original type only if it has known number of
4807 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004808 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004809 PType = PVDecl->getType();
4810 } else if (PType->isFunctionType())
4811 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004812 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4813 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004814 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004815 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004816 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004817
4818 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004819}
4820
Daniel Dunbar4932b362008-08-28 04:38:10 +00004821/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004822/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004823/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4824/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004825/// Property attributes are stored as a comma-delimited C string. The simple
4826/// attributes readonly and bycopy are encoded as single characters. The
4827/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4828/// encoded as single characters, followed by an identifier. Property types
4829/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004830/// these attributes are defined by the following enumeration:
4831/// @code
4832/// enum PropertyAttributes {
4833/// kPropertyReadOnly = 'R', // property is read-only.
4834/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4835/// kPropertyByref = '&', // property is a reference to the value last assigned
4836/// kPropertyDynamic = 'D', // property is dynamic
4837/// kPropertyGetter = 'G', // followed by getter selector name
4838/// kPropertySetter = 'S', // followed by setter selector name
4839/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004840/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004841/// kPropertyWeak = 'W' // 'weak' property
4842/// kPropertyStrong = 'P' // property GC'able
4843/// kPropertyNonAtomic = 'N' // property non-atomic
4844/// };
4845/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004846void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004847 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004848 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004849 // Collect information from the property implementation decl(s).
4850 bool Dynamic = false;
4851 ObjCPropertyImplDecl *SynthesizePID = 0;
4852
4853 // FIXME: Duplicated code due to poor abstraction.
4854 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004855 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004856 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4857 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004858 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004859 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004860 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004861 if (PID->getPropertyDecl() == PD) {
4862 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4863 Dynamic = true;
4864 } else {
4865 SynthesizePID = PID;
4866 }
4867 }
4868 }
4869 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004870 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004871 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004872 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004873 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004874 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004875 if (PID->getPropertyDecl() == PD) {
4876 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4877 Dynamic = true;
4878 } else {
4879 SynthesizePID = PID;
4880 }
4881 }
Mike Stump11289f42009-09-09 15:08:12 +00004882 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004883 }
4884 }
4885
4886 // FIXME: This is not very efficient.
4887 S = "T";
4888
4889 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004890 // GCC has some special rules regarding encoding of properties which
4891 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004892 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004893 true /* outermost type */,
4894 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004895
4896 if (PD->isReadOnly()) {
4897 S += ",R";
4898 } else {
4899 switch (PD->getSetterKind()) {
4900 case ObjCPropertyDecl::Assign: break;
4901 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004902 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004903 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004904 }
4905 }
4906
4907 // It really isn't clear at all what this means, since properties
4908 // are "dynamic by default".
4909 if (Dynamic)
4910 S += ",D";
4911
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004912 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4913 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004914
Daniel Dunbar4932b362008-08-28 04:38:10 +00004915 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4916 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004917 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004918 }
4919
4920 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4921 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004922 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004923 }
4924
4925 if (SynthesizePID) {
4926 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4927 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004928 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004929 }
4930
4931 // FIXME: OBJCGC: weak & strong
4932}
4933
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004934/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004935/// Another legacy compatibility encoding: 32-bit longs are encoded as
4936/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004937/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4938///
4939void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004940 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004941 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004942 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004943 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004944 else
Jay Foad39c79802011-01-12 09:06:06 +00004945 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004946 PointeeTy = IntTy;
4947 }
4948 }
4949}
4950
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004951void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004952 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004953 // We follow the behavior of gcc, expanding structures which are
4954 // directly pointed to, and expanding embedded structures. Note that
4955 // these rules are sufficient to prevent recursive encoding of the
4956 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004957 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004958 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004959}
4960
John McCall393a78d2012-12-20 02:45:14 +00004961static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
4962 BuiltinType::Kind kind) {
4963 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004964 case BuiltinType::Void: return 'v';
4965 case BuiltinType::Bool: return 'B';
4966 case BuiltinType::Char_U:
4967 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00004968 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00004969 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00004970 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00004971 case BuiltinType::UInt: return 'I';
4972 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00004973 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004974 case BuiltinType::UInt128: return 'T';
4975 case BuiltinType::ULongLong: return 'Q';
4976 case BuiltinType::Char_S:
4977 case BuiltinType::SChar: return 'c';
4978 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004979 case BuiltinType::WChar_S:
4980 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004981 case BuiltinType::Int: return 'i';
4982 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00004983 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004984 case BuiltinType::LongLong: return 'q';
4985 case BuiltinType::Int128: return 't';
4986 case BuiltinType::Float: return 'f';
4987 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004988 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00004989 case BuiltinType::NullPtr: return '*'; // like char*
4990
4991 case BuiltinType::Half:
4992 // FIXME: potentially need @encodes for these!
4993 return ' ';
4994
4995 case BuiltinType::ObjCId:
4996 case BuiltinType::ObjCClass:
4997 case BuiltinType::ObjCSel:
4998 llvm_unreachable("@encoding ObjC primitive type");
4999
5000 // OpenCL and placeholder types don't need @encodings.
5001 case BuiltinType::OCLImage1d:
5002 case BuiltinType::OCLImage1dArray:
5003 case BuiltinType::OCLImage1dBuffer:
5004 case BuiltinType::OCLImage2d:
5005 case BuiltinType::OCLImage2dArray:
5006 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005007 case BuiltinType::OCLEvent:
Guy Benyei61054192013-02-07 10:55:47 +00005008 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005009 case BuiltinType::Dependent:
5010#define BUILTIN_TYPE(KIND, ID)
5011#define PLACEHOLDER_TYPE(KIND, ID) \
5012 case BuiltinType::KIND:
5013#include "clang/AST/BuiltinTypes.def"
5014 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005015 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005016 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005017}
5018
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005019static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5020 EnumDecl *Enum = ET->getDecl();
5021
5022 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5023 if (!Enum->isFixed())
5024 return 'i';
5025
5026 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005027 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5028 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005029}
5030
Jay Foad39c79802011-01-12 09:06:06 +00005031static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005032 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005033 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005034 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005035 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5036 // The GNU runtime requires more information; bitfields are encoded as b,
5037 // then the offset (in bits) of the first element, then the type of the
5038 // bitfield, then the size in bits. For example, in this structure:
5039 //
5040 // struct
5041 // {
5042 // int integer;
5043 // int flags:2;
5044 // };
5045 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5046 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5047 // information is not especially sensible, but we're stuck with it for
5048 // compatibility with GCC, although providing it breaks anything that
5049 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005050 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005051 const RecordDecl *RD = FD->getParent();
5052 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005053 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005054 if (const EnumType *ET = T->getAs<EnumType>())
5055 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005056 else {
5057 const BuiltinType *BT = T->castAs<BuiltinType>();
5058 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5059 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005060 }
Richard Smithcaf33902011-10-10 18:28:20 +00005061 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005062}
5063
Daniel Dunbar07d07852009-10-18 21:17:35 +00005064// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005065void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5066 bool ExpandPointedToStructures,
5067 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005068 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005069 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005070 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005071 bool StructField,
5072 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005073 bool EncodeClassNames,
5074 bool EncodePointerToObjCTypedef) const {
John McCall393a78d2012-12-20 02:45:14 +00005075 CanQualType CT = getCanonicalType(T);
5076 switch (CT->getTypeClass()) {
5077 case Type::Builtin:
5078 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005079 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005080 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005081 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5082 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5083 else
5084 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005085 return;
Mike Stump11289f42009-09-09 15:08:12 +00005086
John McCall393a78d2012-12-20 02:45:14 +00005087 case Type::Complex: {
5088 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005089 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00005090 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00005091 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005092 return;
5093 }
John McCall393a78d2012-12-20 02:45:14 +00005094
5095 case Type::Atomic: {
5096 const AtomicType *AT = T->castAs<AtomicType>();
5097 S += 'A';
5098 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5099 false, false);
5100 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005101 }
John McCall393a78d2012-12-20 02:45:14 +00005102
5103 // encoding for pointer or reference types.
5104 case Type::Pointer:
5105 case Type::LValueReference:
5106 case Type::RValueReference: {
5107 QualType PointeeTy;
5108 if (isa<PointerType>(CT)) {
5109 const PointerType *PT = T->castAs<PointerType>();
5110 if (PT->isObjCSelType()) {
5111 S += ':';
5112 return;
5113 }
5114 PointeeTy = PT->getPointeeType();
5115 } else {
5116 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5117 }
5118
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005119 bool isReadOnly = false;
5120 // For historical/compatibility reasons, the read-only qualifier of the
5121 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5122 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005123 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005124 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005125 if (OutermostType && T.isConstQualified()) {
5126 isReadOnly = true;
5127 S += 'r';
5128 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005129 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005130 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005131 while (P->getAs<PointerType>())
5132 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005133 if (P.isConstQualified()) {
5134 isReadOnly = true;
5135 S += 'r';
5136 }
5137 }
5138 if (isReadOnly) {
5139 // Another legacy compatibility encoding. Some ObjC qualifier and type
5140 // combinations need to be rearranged.
5141 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005142 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005143 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005144 }
Mike Stump11289f42009-09-09 15:08:12 +00005145
Anders Carlssond8499822007-10-29 05:01:08 +00005146 if (PointeeTy->isCharType()) {
5147 // char pointer types should be encoded as '*' unless it is a
5148 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005149 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005150 S += '*';
5151 return;
5152 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005153 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005154 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5155 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5156 S += '#';
5157 return;
5158 }
5159 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5160 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5161 S += '@';
5162 return;
5163 }
5164 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005165 }
Anders Carlssond8499822007-10-29 05:01:08 +00005166 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005167 getLegacyIntegralTypeEncoding(PointeeTy);
5168
Mike Stump11289f42009-09-09 15:08:12 +00005169 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005170 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005171 return;
5172 }
John McCall393a78d2012-12-20 02:45:14 +00005173
5174 case Type::ConstantArray:
5175 case Type::IncompleteArray:
5176 case Type::VariableArray: {
5177 const ArrayType *AT = cast<ArrayType>(CT);
5178
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005179 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005180 // Incomplete arrays are encoded as a pointer to the array element.
5181 S += '^';
5182
Mike Stump11289f42009-09-09 15:08:12 +00005183 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005184 false, ExpandStructures, FD);
5185 } else {
5186 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005187
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005188 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
5189 if (getTypeSize(CAT->getElementType()) == 0)
5190 S += '0';
5191 else
5192 S += llvm::utostr(CAT->getSize().getZExtValue());
5193 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005194 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005195 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5196 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005197 S += '0';
5198 }
Mike Stump11289f42009-09-09 15:08:12 +00005199
5200 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005201 false, ExpandStructures, FD);
5202 S += ']';
5203 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005204 return;
5205 }
Mike Stump11289f42009-09-09 15:08:12 +00005206
John McCall393a78d2012-12-20 02:45:14 +00005207 case Type::FunctionNoProto:
5208 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005209 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005210 return;
Mike Stump11289f42009-09-09 15:08:12 +00005211
John McCall393a78d2012-12-20 02:45:14 +00005212 case Type::Record: {
5213 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005214 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005215 // Anonymous structures print as '?'
5216 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5217 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005218 if (ClassTemplateSpecializationDecl *Spec
5219 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5220 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005221 llvm::raw_string_ostream OS(S);
5222 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005223 TemplateArgs.data(),
5224 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005225 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005226 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005227 } else {
5228 S += '?';
5229 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005230 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005231 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005232 if (!RDecl->isUnion()) {
5233 getObjCEncodingForStructureImpl(RDecl, S, FD);
5234 } else {
5235 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5236 FieldEnd = RDecl->field_end();
5237 Field != FieldEnd; ++Field) {
5238 if (FD) {
5239 S += '"';
5240 S += Field->getNameAsString();
5241 S += '"';
5242 }
Mike Stump11289f42009-09-09 15:08:12 +00005243
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005244 // Special case bit-fields.
5245 if (Field->isBitField()) {
5246 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00005247 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005248 } else {
5249 QualType qt = Field->getType();
5250 getLegacyIntegralTypeEncoding(qt);
5251 getObjCEncodingForTypeImpl(qt, S, false, true,
5252 FD, /*OutermostType*/false,
5253 /*EncodingProperty*/false,
5254 /*StructField*/true);
5255 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005256 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005257 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005258 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005259 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005260 return;
5261 }
Mike Stump11289f42009-09-09 15:08:12 +00005262
John McCall393a78d2012-12-20 02:45:14 +00005263 case Type::BlockPointer: {
5264 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005265 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005266 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005267 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005268
5269 S += '<';
5270 // Block return type
5271 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5272 ExpandPointedToStructures, ExpandStructures,
5273 FD,
5274 false /* OutermostType */,
5275 EncodingProperty,
5276 false /* StructField */,
5277 EncodeBlockParameters,
5278 EncodeClassNames);
5279 // Block self
5280 S += "@?";
5281 // Block parameters
5282 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5283 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5284 E = FPT->arg_type_end(); I && (I != E); ++I) {
5285 getObjCEncodingForTypeImpl(*I, S,
5286 ExpandPointedToStructures,
5287 ExpandStructures,
5288 FD,
5289 false /* OutermostType */,
5290 EncodingProperty,
5291 false /* StructField */,
5292 EncodeBlockParameters,
5293 EncodeClassNames);
5294 }
5295 }
5296 S += '>';
5297 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005298 return;
5299 }
Mike Stump11289f42009-09-09 15:08:12 +00005300
John McCall393a78d2012-12-20 02:45:14 +00005301 case Type::ObjCObject:
5302 case Type::ObjCInterface: {
5303 // Ignore protocol qualifiers when mangling at this level.
5304 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005305
John McCall393a78d2012-12-20 02:45:14 +00005306 // The assumption seems to be that this assert will succeed
5307 // because nested levels will have filtered out 'id' and 'Class'.
5308 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005309 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005310 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005311 S += '{';
5312 const IdentifierInfo *II = OI->getIdentifier();
5313 S += II->getName();
5314 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005315 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005316 DeepCollectObjCIvars(OI, true, Ivars);
5317 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005318 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005319 if (Field->isBitField())
5320 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005321 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005322 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5323 false, false, false, false, false,
5324 EncodePointerToObjCTypedef);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005325 }
5326 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005327 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005328 }
Mike Stump11289f42009-09-09 15:08:12 +00005329
John McCall393a78d2012-12-20 02:45:14 +00005330 case Type::ObjCObjectPointer: {
5331 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005332 if (OPT->isObjCIdType()) {
5333 S += '@';
5334 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005335 }
Mike Stump11289f42009-09-09 15:08:12 +00005336
Steve Narofff0c86112009-10-28 22:03:49 +00005337 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5338 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5339 // Since this is a binary compatibility issue, need to consult with runtime
5340 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005341 S += '#';
5342 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005343 }
Mike Stump11289f42009-09-09 15:08:12 +00005344
Chris Lattnere7cabb92009-07-13 00:10:46 +00005345 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005346 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005347 ExpandPointedToStructures,
5348 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005349 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005350 // Note that we do extended encoding of protocol qualifer list
5351 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005352 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00005353 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5354 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005355 S += '<';
5356 S += (*I)->getNameAsString();
5357 S += '>';
5358 }
5359 S += '"';
5360 }
5361 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005362 }
Mike Stump11289f42009-09-09 15:08:12 +00005363
Chris Lattnere7cabb92009-07-13 00:10:46 +00005364 QualType PointeeTy = OPT->getPointeeType();
5365 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005366 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5367 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005368 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005369 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005370 // {...};
5371 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00005372 getObjCEncodingForTypeImpl(PointeeTy, S,
5373 false, ExpandPointedToStructures,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005374 NULL,
5375 false, false, false, false, false,
5376 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005377 return;
5378 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005379
5380 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005381 if (OPT->getInterfaceDecl() &&
5382 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005383 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005384 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00005385 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5386 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005387 S += '<';
5388 S += (*I)->getNameAsString();
5389 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005390 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005391 S += '"';
5392 }
5393 return;
5394 }
Mike Stump11289f42009-09-09 15:08:12 +00005395
John McCalla9e6e8d2010-05-17 23:56:34 +00005396 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005397 // FIXME: we shoul do better than that. 'M' is available.
5398 case Type::MemberPointer:
John McCalla9e6e8d2010-05-17 23:56:34 +00005399 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005400
John McCall393a78d2012-12-20 02:45:14 +00005401 case Type::Vector:
5402 case Type::ExtVector:
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005403 // This matches gcc's encoding, even though technically it is
5404 // insufficient.
5405 // FIXME. We should do a better job than gcc.
5406 return;
John McCall393a78d2012-12-20 02:45:14 +00005407
Richard Smith27d807c2013-04-30 13:56:41 +00005408 case Type::Auto:
5409 // We could see an undeduced auto type here during error recovery.
5410 // Just ignore it.
5411 return;
5412
John McCall393a78d2012-12-20 02:45:14 +00005413#define ABSTRACT_TYPE(KIND, BASE)
5414#define TYPE(KIND, BASE)
5415#define DEPENDENT_TYPE(KIND, BASE) \
5416 case Type::KIND:
5417#define NON_CANONICAL_TYPE(KIND, BASE) \
5418 case Type::KIND:
5419#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5420 case Type::KIND:
5421#include "clang/AST/TypeNodes.def"
5422 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005423 }
John McCall393a78d2012-12-20 02:45:14 +00005424 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005425}
5426
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005427void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5428 std::string &S,
5429 const FieldDecl *FD,
5430 bool includeVBases) const {
5431 assert(RDecl && "Expected non-null RecordDecl");
5432 assert(!RDecl->isUnion() && "Should not be called for unions");
5433 if (!RDecl->getDefinition())
5434 return;
5435
5436 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5437 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5438 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5439
5440 if (CXXRec) {
5441 for (CXXRecordDecl::base_class_iterator
5442 BI = CXXRec->bases_begin(),
5443 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5444 if (!BI->isVirtual()) {
5445 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005446 if (base->isEmpty())
5447 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005448 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005449 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5450 std::make_pair(offs, base));
5451 }
5452 }
5453 }
5454
5455 unsigned i = 0;
5456 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5457 FieldEnd = RDecl->field_end();
5458 Field != FieldEnd; ++Field, ++i) {
5459 uint64_t offs = layout.getFieldOffset(i);
5460 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005461 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005462 }
5463
5464 if (CXXRec && includeVBases) {
5465 for (CXXRecordDecl::base_class_iterator
5466 BI = CXXRec->vbases_begin(),
5467 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
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.getVBaseClassOffset(base));
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005472 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5473 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5474 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005475 }
5476 }
5477
5478 CharUnits size;
5479 if (CXXRec) {
5480 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5481 } else {
5482 size = layout.getSize();
5483 }
5484
5485 uint64_t CurOffs = 0;
5486 std::multimap<uint64_t, NamedDecl *>::iterator
5487 CurLayObj = FieldOrBaseOffsets.begin();
5488
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005489 if (CXXRec && CXXRec->isDynamicClass() &&
5490 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005491 if (FD) {
5492 S += "\"_vptr$";
5493 std::string recname = CXXRec->getNameAsString();
5494 if (recname.empty()) recname = "?";
5495 S += recname;
5496 S += '"';
5497 }
5498 S += "^^?";
5499 CurOffs += getTypeSize(VoidPtrTy);
5500 }
5501
5502 if (!RDecl->hasFlexibleArrayMember()) {
5503 // Mark the end of the structure.
5504 uint64_t offs = toBits(size);
5505 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5506 std::make_pair(offs, (NamedDecl*)0));
5507 }
5508
5509 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5510 assert(CurOffs <= CurLayObj->first);
5511
5512 if (CurOffs < CurLayObj->first) {
5513 uint64_t padding = CurLayObj->first - CurOffs;
5514 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5515 // packing/alignment of members is different that normal, in which case
5516 // the encoding will be out-of-sync with the real layout.
5517 // If the runtime switches to just consider the size of types without
5518 // taking into account alignment, we could make padding explicit in the
5519 // encoding (e.g. using arrays of chars). The encoding strings would be
5520 // longer then though.
5521 CurOffs += padding;
5522 }
5523
5524 NamedDecl *dcl = CurLayObj->second;
5525 if (dcl == 0)
5526 break; // reached end of structure.
5527
5528 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5529 // We expand the bases without their virtual bases since those are going
5530 // in the initial structure. Note that this differs from gcc which
5531 // expands virtual bases each time one is encountered in the hierarchy,
5532 // making the encoding type bigger than it really is.
5533 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005534 assert(!base->isEmpty());
5535 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005536 } else {
5537 FieldDecl *field = cast<FieldDecl>(dcl);
5538 if (FD) {
5539 S += '"';
5540 S += field->getNameAsString();
5541 S += '"';
5542 }
5543
5544 if (field->isBitField()) {
5545 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00005546 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005547 } else {
5548 QualType qt = field->getType();
5549 getLegacyIntegralTypeEncoding(qt);
5550 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5551 /*OutermostType*/false,
5552 /*EncodingProperty*/false,
5553 /*StructField*/true);
5554 CurOffs += getTypeSize(field->getType());
5555 }
5556 }
5557 }
5558}
5559
Mike Stump11289f42009-09-09 15:08:12 +00005560void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005561 std::string& S) const {
5562 if (QT & Decl::OBJC_TQ_In)
5563 S += 'n';
5564 if (QT & Decl::OBJC_TQ_Inout)
5565 S += 'N';
5566 if (QT & Decl::OBJC_TQ_Out)
5567 S += 'o';
5568 if (QT & Decl::OBJC_TQ_Bycopy)
5569 S += 'O';
5570 if (QT & Decl::OBJC_TQ_Byref)
5571 S += 'R';
5572 if (QT & Decl::OBJC_TQ_Oneway)
5573 S += 'V';
5574}
5575
Douglas Gregor3ea72692011-08-12 05:46:01 +00005576TypedefDecl *ASTContext::getObjCIdDecl() const {
5577 if (!ObjCIdDecl) {
5578 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5579 T = getObjCObjectPointerType(T);
5580 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5581 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5582 getTranslationUnitDecl(),
5583 SourceLocation(), SourceLocation(),
5584 &Idents.get("id"), IdInfo);
5585 }
5586
5587 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005588}
5589
Douglas Gregor52e02802011-08-12 06:17:30 +00005590TypedefDecl *ASTContext::getObjCSelDecl() const {
5591 if (!ObjCSelDecl) {
5592 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5593 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5594 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5595 getTranslationUnitDecl(),
5596 SourceLocation(), SourceLocation(),
5597 &Idents.get("SEL"), SelInfo);
5598 }
5599 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005600}
5601
Douglas Gregor0a586182011-08-12 05:59:41 +00005602TypedefDecl *ASTContext::getObjCClassDecl() const {
5603 if (!ObjCClassDecl) {
5604 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5605 T = getObjCObjectPointerType(T);
5606 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5607 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5608 getTranslationUnitDecl(),
5609 SourceLocation(), SourceLocation(),
5610 &Idents.get("Class"), ClassInfo);
5611 }
5612
5613 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005614}
5615
Douglas Gregord53ae832012-01-17 18:09:05 +00005616ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5617 if (!ObjCProtocolClassDecl) {
5618 ObjCProtocolClassDecl
5619 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5620 SourceLocation(),
5621 &Idents.get("Protocol"),
5622 /*PrevDecl=*/0,
5623 SourceLocation(), true);
5624 }
5625
5626 return ObjCProtocolClassDecl;
5627}
5628
Meador Inge5d3fb222012-06-16 03:34:49 +00005629//===----------------------------------------------------------------------===//
5630// __builtin_va_list Construction Functions
5631//===----------------------------------------------------------------------===//
5632
5633static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5634 // typedef char* __builtin_va_list;
5635 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5636 TypeSourceInfo *TInfo
5637 = Context->getTrivialTypeSourceInfo(CharPtrType);
5638
5639 TypedefDecl *VaListTypeDecl
5640 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5641 Context->getTranslationUnitDecl(),
5642 SourceLocation(), SourceLocation(),
5643 &Context->Idents.get("__builtin_va_list"),
5644 TInfo);
5645 return VaListTypeDecl;
5646}
5647
5648static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5649 // typedef void* __builtin_va_list;
5650 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5651 TypeSourceInfo *TInfo
5652 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5653
5654 TypedefDecl *VaListTypeDecl
5655 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5656 Context->getTranslationUnitDecl(),
5657 SourceLocation(), SourceLocation(),
5658 &Context->Idents.get("__builtin_va_list"),
5659 TInfo);
5660 return VaListTypeDecl;
5661}
5662
Tim Northover9bb857a2013-01-31 12:13:10 +00005663static TypedefDecl *
5664CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5665 RecordDecl *VaListTagDecl;
5666 if (Context->getLangOpts().CPlusPlus) {
5667 // namespace std { struct __va_list {
5668 NamespaceDecl *NS;
5669 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5670 Context->getTranslationUnitDecl(),
5671 /*Inline*/false, SourceLocation(),
5672 SourceLocation(), &Context->Idents.get("std"),
5673 /*PrevDecl*/0);
5674
5675 VaListTagDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5676 Context->getTranslationUnitDecl(),
5677 SourceLocation(), SourceLocation(),
5678 &Context->Idents.get("__va_list"));
5679 VaListTagDecl->setDeclContext(NS);
5680 } else {
5681 // struct __va_list
5682 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5683 Context->getTranslationUnitDecl(),
5684 &Context->Idents.get("__va_list"));
5685 }
5686
5687 VaListTagDecl->startDefinition();
5688
5689 const size_t NumFields = 5;
5690 QualType FieldTypes[NumFields];
5691 const char *FieldNames[NumFields];
5692
5693 // void *__stack;
5694 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5695 FieldNames[0] = "__stack";
5696
5697 // void *__gr_top;
5698 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5699 FieldNames[1] = "__gr_top";
5700
5701 // void *__vr_top;
5702 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5703 FieldNames[2] = "__vr_top";
5704
5705 // int __gr_offs;
5706 FieldTypes[3] = Context->IntTy;
5707 FieldNames[3] = "__gr_offs";
5708
5709 // int __vr_offs;
5710 FieldTypes[4] = Context->IntTy;
5711 FieldNames[4] = "__vr_offs";
5712
5713 // Create fields
5714 for (unsigned i = 0; i < NumFields; ++i) {
5715 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5716 VaListTagDecl,
5717 SourceLocation(),
5718 SourceLocation(),
5719 &Context->Idents.get(FieldNames[i]),
5720 FieldTypes[i], /*TInfo=*/0,
5721 /*BitWidth=*/0,
5722 /*Mutable=*/false,
5723 ICIS_NoInit);
5724 Field->setAccess(AS_public);
5725 VaListTagDecl->addDecl(Field);
5726 }
5727 VaListTagDecl->completeDefinition();
5728 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5729 Context->VaListTagTy = VaListTagType;
5730
5731 // } __builtin_va_list;
5732 TypedefDecl *VaListTypedefDecl
5733 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5734 Context->getTranslationUnitDecl(),
5735 SourceLocation(), SourceLocation(),
5736 &Context->Idents.get("__builtin_va_list"),
5737 Context->getTrivialTypeSourceInfo(VaListTagType));
5738
5739 return VaListTypedefDecl;
5740}
5741
Meador Inge5d3fb222012-06-16 03:34:49 +00005742static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5743 // typedef struct __va_list_tag {
5744 RecordDecl *VaListTagDecl;
5745
5746 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5747 Context->getTranslationUnitDecl(),
5748 &Context->Idents.get("__va_list_tag"));
5749 VaListTagDecl->startDefinition();
5750
5751 const size_t NumFields = 5;
5752 QualType FieldTypes[NumFields];
5753 const char *FieldNames[NumFields];
5754
5755 // unsigned char gpr;
5756 FieldTypes[0] = Context->UnsignedCharTy;
5757 FieldNames[0] = "gpr";
5758
5759 // unsigned char fpr;
5760 FieldTypes[1] = Context->UnsignedCharTy;
5761 FieldNames[1] = "fpr";
5762
5763 // unsigned short reserved;
5764 FieldTypes[2] = Context->UnsignedShortTy;
5765 FieldNames[2] = "reserved";
5766
5767 // void* overflow_arg_area;
5768 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5769 FieldNames[3] = "overflow_arg_area";
5770
5771 // void* reg_save_area;
5772 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5773 FieldNames[4] = "reg_save_area";
5774
5775 // Create fields
5776 for (unsigned i = 0; i < NumFields; ++i) {
5777 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5778 SourceLocation(),
5779 SourceLocation(),
5780 &Context->Idents.get(FieldNames[i]),
5781 FieldTypes[i], /*TInfo=*/0,
5782 /*BitWidth=*/0,
5783 /*Mutable=*/false,
5784 ICIS_NoInit);
5785 Field->setAccess(AS_public);
5786 VaListTagDecl->addDecl(Field);
5787 }
5788 VaListTagDecl->completeDefinition();
5789 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005790 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005791
5792 // } __va_list_tag;
5793 TypedefDecl *VaListTagTypedefDecl
5794 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5795 Context->getTranslationUnitDecl(),
5796 SourceLocation(), SourceLocation(),
5797 &Context->Idents.get("__va_list_tag"),
5798 Context->getTrivialTypeSourceInfo(VaListTagType));
5799 QualType VaListTagTypedefType =
5800 Context->getTypedefType(VaListTagTypedefDecl);
5801
5802 // typedef __va_list_tag __builtin_va_list[1];
5803 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5804 QualType VaListTagArrayType
5805 = Context->getConstantArrayType(VaListTagTypedefType,
5806 Size, ArrayType::Normal, 0);
5807 TypeSourceInfo *TInfo
5808 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5809 TypedefDecl *VaListTypedefDecl
5810 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5811 Context->getTranslationUnitDecl(),
5812 SourceLocation(), SourceLocation(),
5813 &Context->Idents.get("__builtin_va_list"),
5814 TInfo);
5815
5816 return VaListTypedefDecl;
5817}
5818
5819static TypedefDecl *
5820CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5821 // typedef struct __va_list_tag {
5822 RecordDecl *VaListTagDecl;
5823 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5824 Context->getTranslationUnitDecl(),
5825 &Context->Idents.get("__va_list_tag"));
5826 VaListTagDecl->startDefinition();
5827
5828 const size_t NumFields = 4;
5829 QualType FieldTypes[NumFields];
5830 const char *FieldNames[NumFields];
5831
5832 // unsigned gp_offset;
5833 FieldTypes[0] = Context->UnsignedIntTy;
5834 FieldNames[0] = "gp_offset";
5835
5836 // unsigned fp_offset;
5837 FieldTypes[1] = Context->UnsignedIntTy;
5838 FieldNames[1] = "fp_offset";
5839
5840 // void* overflow_arg_area;
5841 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5842 FieldNames[2] = "overflow_arg_area";
5843
5844 // void* reg_save_area;
5845 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5846 FieldNames[3] = "reg_save_area";
5847
5848 // Create fields
5849 for (unsigned i = 0; i < NumFields; ++i) {
5850 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5851 VaListTagDecl,
5852 SourceLocation(),
5853 SourceLocation(),
5854 &Context->Idents.get(FieldNames[i]),
5855 FieldTypes[i], /*TInfo=*/0,
5856 /*BitWidth=*/0,
5857 /*Mutable=*/false,
5858 ICIS_NoInit);
5859 Field->setAccess(AS_public);
5860 VaListTagDecl->addDecl(Field);
5861 }
5862 VaListTagDecl->completeDefinition();
5863 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005864 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005865
5866 // } __va_list_tag;
5867 TypedefDecl *VaListTagTypedefDecl
5868 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5869 Context->getTranslationUnitDecl(),
5870 SourceLocation(), SourceLocation(),
5871 &Context->Idents.get("__va_list_tag"),
5872 Context->getTrivialTypeSourceInfo(VaListTagType));
5873 QualType VaListTagTypedefType =
5874 Context->getTypedefType(VaListTagTypedefDecl);
5875
5876 // typedef __va_list_tag __builtin_va_list[1];
5877 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5878 QualType VaListTagArrayType
5879 = Context->getConstantArrayType(VaListTagTypedefType,
5880 Size, ArrayType::Normal,0);
5881 TypeSourceInfo *TInfo
5882 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5883 TypedefDecl *VaListTypedefDecl
5884 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5885 Context->getTranslationUnitDecl(),
5886 SourceLocation(), SourceLocation(),
5887 &Context->Idents.get("__builtin_va_list"),
5888 TInfo);
5889
5890 return VaListTypedefDecl;
5891}
5892
5893static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5894 // typedef int __builtin_va_list[4];
5895 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5896 QualType IntArrayType
5897 = Context->getConstantArrayType(Context->IntTy,
5898 Size, ArrayType::Normal, 0);
5899 TypedefDecl *VaListTypedefDecl
5900 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5901 Context->getTranslationUnitDecl(),
5902 SourceLocation(), SourceLocation(),
5903 &Context->Idents.get("__builtin_va_list"),
5904 Context->getTrivialTypeSourceInfo(IntArrayType));
5905
5906 return VaListTypedefDecl;
5907}
5908
Logan Chien57086ce2012-10-10 06:56:20 +00005909static TypedefDecl *
5910CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5911 RecordDecl *VaListDecl;
5912 if (Context->getLangOpts().CPlusPlus) {
5913 // namespace std { struct __va_list {
5914 NamespaceDecl *NS;
5915 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5916 Context->getTranslationUnitDecl(),
5917 /*Inline*/false, SourceLocation(),
5918 SourceLocation(), &Context->Idents.get("std"),
5919 /*PrevDecl*/0);
5920
5921 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5922 Context->getTranslationUnitDecl(),
5923 SourceLocation(), SourceLocation(),
5924 &Context->Idents.get("__va_list"));
5925
5926 VaListDecl->setDeclContext(NS);
5927
5928 } else {
5929 // struct __va_list {
5930 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
5931 Context->getTranslationUnitDecl(),
5932 &Context->Idents.get("__va_list"));
5933 }
5934
5935 VaListDecl->startDefinition();
5936
5937 // void * __ap;
5938 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5939 VaListDecl,
5940 SourceLocation(),
5941 SourceLocation(),
5942 &Context->Idents.get("__ap"),
5943 Context->getPointerType(Context->VoidTy),
5944 /*TInfo=*/0,
5945 /*BitWidth=*/0,
5946 /*Mutable=*/false,
5947 ICIS_NoInit);
5948 Field->setAccess(AS_public);
5949 VaListDecl->addDecl(Field);
5950
5951 // };
5952 VaListDecl->completeDefinition();
5953
5954 // typedef struct __va_list __builtin_va_list;
5955 TypeSourceInfo *TInfo
5956 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
5957
5958 TypedefDecl *VaListTypeDecl
5959 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5960 Context->getTranslationUnitDecl(),
5961 SourceLocation(), SourceLocation(),
5962 &Context->Idents.get("__builtin_va_list"),
5963 TInfo);
5964
5965 return VaListTypeDecl;
5966}
5967
Meador Inge5d3fb222012-06-16 03:34:49 +00005968static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5969 TargetInfo::BuiltinVaListKind Kind) {
5970 switch (Kind) {
5971 case TargetInfo::CharPtrBuiltinVaList:
5972 return CreateCharPtrBuiltinVaListDecl(Context);
5973 case TargetInfo::VoidPtrBuiltinVaList:
5974 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00005975 case TargetInfo::AArch64ABIBuiltinVaList:
5976 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00005977 case TargetInfo::PowerABIBuiltinVaList:
5978 return CreatePowerABIBuiltinVaListDecl(Context);
5979 case TargetInfo::X86_64ABIBuiltinVaList:
5980 return CreateX86_64ABIBuiltinVaListDecl(Context);
5981 case TargetInfo::PNaClABIBuiltinVaList:
5982 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00005983 case TargetInfo::AAPCSABIBuiltinVaList:
5984 return CreateAAPCSABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00005985 }
5986
5987 llvm_unreachable("Unhandled __builtin_va_list type kind");
5988}
5989
5990TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5991 if (!BuiltinVaListDecl)
5992 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5993
5994 return BuiltinVaListDecl;
5995}
5996
Meador Ingecfb60902012-07-01 15:57:25 +00005997QualType ASTContext::getVaListTagType() const {
5998 // Force the creation of VaListTagTy by building the __builtin_va_list
5999 // declaration.
6000 if (VaListTagTy.isNull())
6001 (void) getBuiltinVaListDecl();
6002
6003 return VaListTagTy;
6004}
6005
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006006void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006007 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006008 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006009
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006010 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006011}
6012
John McCalld28ae272009-12-02 08:04:21 +00006013/// \brief Retrieve the template name that corresponds to a non-empty
6014/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006015TemplateName
6016ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6017 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006018 unsigned size = End - Begin;
6019 assert(size > 1 && "set is not overloaded!");
6020
6021 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6022 size * sizeof(FunctionTemplateDecl*));
6023 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6024
6025 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006026 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006027 NamedDecl *D = *I;
6028 assert(isa<FunctionTemplateDecl>(D) ||
6029 (isa<UsingShadowDecl>(D) &&
6030 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6031 *Storage++ = D;
6032 }
6033
6034 return TemplateName(OT);
6035}
6036
Douglas Gregordc572a32009-03-30 22:58:21 +00006037/// \brief Retrieve the template name that represents a qualified
6038/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006039TemplateName
6040ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6041 bool TemplateKeyword,
6042 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006043 assert(NNS && "Missing nested-name-specifier in qualified template name");
6044
Douglas Gregorc42075a2010-02-04 18:10:26 +00006045 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006046 llvm::FoldingSetNodeID ID;
6047 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6048
6049 void *InsertPos = 0;
6050 QualifiedTemplateName *QTN =
6051 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6052 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006053 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6054 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006055 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6056 }
6057
6058 return TemplateName(QTN);
6059}
6060
6061/// \brief Retrieve the template name that represents a dependent
6062/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006063TemplateName
6064ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6065 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006066 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006067 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006068
6069 llvm::FoldingSetNodeID ID;
6070 DependentTemplateName::Profile(ID, NNS, Name);
6071
6072 void *InsertPos = 0;
6073 DependentTemplateName *QTN =
6074 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6075
6076 if (QTN)
6077 return TemplateName(QTN);
6078
6079 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6080 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006081 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6082 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006083 } else {
6084 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006085 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6086 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006087 DependentTemplateName *CheckQTN =
6088 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6089 assert(!CheckQTN && "Dependent type name canonicalization broken");
6090 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006091 }
6092
6093 DependentTemplateNames.InsertNode(QTN, InsertPos);
6094 return TemplateName(QTN);
6095}
6096
Douglas Gregor71395fa2009-11-04 00:56:37 +00006097/// \brief Retrieve the template name that represents a dependent
6098/// template name such as \c MetaFun::template operator+.
6099TemplateName
6100ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006101 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006102 assert((!NNS || NNS->isDependent()) &&
6103 "Nested name specifier must be dependent");
6104
6105 llvm::FoldingSetNodeID ID;
6106 DependentTemplateName::Profile(ID, NNS, Operator);
6107
6108 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006109 DependentTemplateName *QTN
6110 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006111
6112 if (QTN)
6113 return TemplateName(QTN);
6114
6115 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6116 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006117 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6118 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006119 } else {
6120 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006121 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6122 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006123
6124 DependentTemplateName *CheckQTN
6125 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6126 assert(!CheckQTN && "Dependent template name canonicalization broken");
6127 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006128 }
6129
6130 DependentTemplateNames.InsertNode(QTN, InsertPos);
6131 return TemplateName(QTN);
6132}
6133
Douglas Gregor5590be02011-01-15 06:45:20 +00006134TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006135ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6136 TemplateName replacement) const {
6137 llvm::FoldingSetNodeID ID;
6138 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6139
6140 void *insertPos = 0;
6141 SubstTemplateTemplateParmStorage *subst
6142 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6143
6144 if (!subst) {
6145 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6146 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6147 }
6148
6149 return TemplateName(subst);
6150}
6151
6152TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006153ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6154 const TemplateArgument &ArgPack) const {
6155 ASTContext &Self = const_cast<ASTContext &>(*this);
6156 llvm::FoldingSetNodeID ID;
6157 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6158
6159 void *InsertPos = 0;
6160 SubstTemplateTemplateParmPackStorage *Subst
6161 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6162
6163 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006164 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006165 ArgPack.pack_size(),
6166 ArgPack.pack_begin());
6167 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6168 }
6169
6170 return TemplateName(Subst);
6171}
6172
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006173/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006174/// TargetInfo, produce the corresponding type. The unsigned @p Type
6175/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006176CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006177 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006178 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006179 case TargetInfo::SignedShort: return ShortTy;
6180 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6181 case TargetInfo::SignedInt: return IntTy;
6182 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6183 case TargetInfo::SignedLong: return LongTy;
6184 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6185 case TargetInfo::SignedLongLong: return LongLongTy;
6186 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6187 }
6188
David Blaikie83d382b2011-09-23 05:06:16 +00006189 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006190}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006191
6192//===----------------------------------------------------------------------===//
6193// Type Predicates.
6194//===----------------------------------------------------------------------===//
6195
Fariborz Jahanian96207692009-02-18 21:49:28 +00006196/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6197/// garbage collection attribute.
6198///
John McCall553d45a2011-01-12 00:34:59 +00006199Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006200 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006201 return Qualifiers::GCNone;
6202
David Blaikiebbafb8a2012-03-11 07:00:24 +00006203 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006204 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6205
6206 // Default behaviour under objective-C's gc is for ObjC pointers
6207 // (or pointers to them) be treated as though they were declared
6208 // as __strong.
6209 if (GCAttrs == Qualifiers::GCNone) {
6210 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6211 return Qualifiers::Strong;
6212 else if (Ty->isPointerType())
6213 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6214 } else {
6215 // It's not valid to set GC attributes on anything that isn't a
6216 // pointer.
6217#ifndef NDEBUG
6218 QualType CT = Ty->getCanonicalTypeInternal();
6219 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6220 CT = AT->getElementType();
6221 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6222#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006223 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006224 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006225}
6226
Chris Lattner49af6a42008-04-07 06:51:04 +00006227//===----------------------------------------------------------------------===//
6228// Type Compatibility Testing
6229//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006230
Mike Stump11289f42009-09-09 15:08:12 +00006231/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006232/// compatible.
6233static bool areCompatVectorTypes(const VectorType *LHS,
6234 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006235 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006236 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006237 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006238}
6239
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006240bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6241 QualType SecondVec) {
6242 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6243 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6244
6245 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6246 return true;
6247
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006248 // Treat Neon vector types and most AltiVec vector types as if they are the
6249 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006250 const VectorType *First = FirstVec->getAs<VectorType>();
6251 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006252 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006253 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006254 First->getVectorKind() != VectorType::AltiVecPixel &&
6255 First->getVectorKind() != VectorType::AltiVecBool &&
6256 Second->getVectorKind() != VectorType::AltiVecPixel &&
6257 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006258 return true;
6259
6260 return false;
6261}
6262
Steve Naroff8e6aee52009-07-23 01:01:38 +00006263//===----------------------------------------------------------------------===//
6264// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6265//===----------------------------------------------------------------------===//
6266
6267/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6268/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006269bool
6270ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6271 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006272 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006273 return true;
6274 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6275 E = rProto->protocol_end(); PI != E; ++PI)
6276 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6277 return true;
6278 return false;
6279}
6280
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006281/// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
Steve Naroff8e6aee52009-07-23 01:01:38 +00006282/// return true if lhs's protocols conform to rhs's protocol; false
6283/// otherwise.
6284bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
6285 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
6286 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
6287 return false;
6288}
6289
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006290/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6291/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006292bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6293 QualType rhs) {
6294 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6295 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6296 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6297
6298 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6299 E = lhsQID->qual_end(); I != E; ++I) {
6300 bool match = false;
6301 ObjCProtocolDecl *lhsProto = *I;
6302 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6303 E = rhsOPT->qual_end(); J != E; ++J) {
6304 ObjCProtocolDecl *rhsProto = *J;
6305 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6306 match = true;
6307 break;
6308 }
6309 }
6310 if (!match)
6311 return false;
6312 }
6313 return true;
6314}
6315
Steve Naroff8e6aee52009-07-23 01:01:38 +00006316/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6317/// ObjCQualifiedIDType.
6318bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6319 bool compare) {
6320 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006321 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006322 lhs->isObjCIdType() || lhs->isObjCClassType())
6323 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006324 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006325 rhs->isObjCIdType() || rhs->isObjCClassType())
6326 return true;
6327
6328 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006329 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006330
Steve Naroff8e6aee52009-07-23 01:01:38 +00006331 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006332
Steve Naroff8e6aee52009-07-23 01:01:38 +00006333 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006334 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006335 // make sure we check the class hierarchy.
6336 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6337 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6338 E = lhsQID->qual_end(); I != E; ++I) {
6339 // when comparing an id<P> on lhs with a static type on rhs,
6340 // see if static class implements all of id's protocols, directly or
6341 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006342 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006343 return false;
6344 }
6345 }
6346 // If there are no qualifiers and no interface, we have an 'id'.
6347 return true;
6348 }
Mike Stump11289f42009-09-09 15:08:12 +00006349 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006350 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6351 E = lhsQID->qual_end(); I != E; ++I) {
6352 ObjCProtocolDecl *lhsProto = *I;
6353 bool match = false;
6354
6355 // when comparing an id<P> on lhs with a static type on rhs,
6356 // see if static class implements all of id's protocols, directly or
6357 // through its super class and categories.
6358 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6359 E = rhsOPT->qual_end(); J != E; ++J) {
6360 ObjCProtocolDecl *rhsProto = *J;
6361 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6362 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6363 match = true;
6364 break;
6365 }
6366 }
Mike Stump11289f42009-09-09 15:08:12 +00006367 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006368 // make sure we check the class hierarchy.
6369 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6370 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6371 E = lhsQID->qual_end(); I != E; ++I) {
6372 // when comparing an id<P> on lhs with a static type on rhs,
6373 // see if static class implements all of id's protocols, directly or
6374 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006375 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006376 match = true;
6377 break;
6378 }
6379 }
6380 }
6381 if (!match)
6382 return false;
6383 }
Mike Stump11289f42009-09-09 15:08:12 +00006384
Steve Naroff8e6aee52009-07-23 01:01:38 +00006385 return true;
6386 }
Mike Stump11289f42009-09-09 15:08:12 +00006387
Steve Naroff8e6aee52009-07-23 01:01:38 +00006388 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6389 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6390
Mike Stump11289f42009-09-09 15:08:12 +00006391 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006392 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006393 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006394 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6395 E = lhsOPT->qual_end(); I != E; ++I) {
6396 ObjCProtocolDecl *lhsProto = *I;
6397 bool match = false;
6398
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006399 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006400 // see if static class implements all of id's protocols, directly or
6401 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006402 // First, lhs protocols in the qualifier list must be found, direct
6403 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006404 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6405 E = rhsQID->qual_end(); J != E; ++J) {
6406 ObjCProtocolDecl *rhsProto = *J;
6407 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6408 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6409 match = true;
6410 break;
6411 }
6412 }
6413 if (!match)
6414 return false;
6415 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006416
6417 // Static class's protocols, or its super class or category protocols
6418 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6419 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6420 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6421 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6422 // This is rather dubious but matches gcc's behavior. If lhs has
6423 // no type qualifier and its class has no static protocol(s)
6424 // assume that it is mismatch.
6425 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6426 return false;
6427 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6428 LHSInheritedProtocols.begin(),
6429 E = LHSInheritedProtocols.end(); I != E; ++I) {
6430 bool match = false;
6431 ObjCProtocolDecl *lhsProto = (*I);
6432 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6433 E = rhsQID->qual_end(); J != E; ++J) {
6434 ObjCProtocolDecl *rhsProto = *J;
6435 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6436 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6437 match = true;
6438 break;
6439 }
6440 }
6441 if (!match)
6442 return false;
6443 }
6444 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006445 return true;
6446 }
6447 return false;
6448}
6449
Eli Friedman47f77112008-08-22 00:56:42 +00006450/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006451/// compatible for assignment from RHS to LHS. This handles validation of any
6452/// protocol qualifiers on the LHS or RHS.
6453///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006454bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6455 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006456 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6457 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6458
Steve Naroff1329fa02009-07-15 18:40:39 +00006459 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006460 if (LHS->isObjCUnqualifiedIdOrClass() ||
6461 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006462 return true;
6463
John McCall8b07ec22010-05-15 11:32:37 +00006464 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006465 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6466 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006467 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006468
6469 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6470 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6471 QualType(RHSOPT,0));
6472
John McCall8b07ec22010-05-15 11:32:37 +00006473 // If we have 2 user-defined types, fall into that path.
6474 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006475 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006476
Steve Naroff8e6aee52009-07-23 01:01:38 +00006477 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006478}
6479
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006480/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006481/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006482/// arguments in block literals. When passed as arguments, passing 'A*' where
6483/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6484/// not OK. For the return type, the opposite is not OK.
6485bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6486 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006487 const ObjCObjectPointerType *RHSOPT,
6488 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006489 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006490 return true;
6491
6492 if (LHSOPT->isObjCBuiltinType()) {
6493 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6494 }
6495
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006496 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006497 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6498 QualType(RHSOPT,0),
6499 false);
6500
6501 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6502 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6503 if (LHS && RHS) { // We have 2 user-defined types.
6504 if (LHS != RHS) {
6505 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006506 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006507 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006508 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006509 }
6510 else
6511 return true;
6512 }
6513 return false;
6514}
6515
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006516/// getIntersectionOfProtocols - This routine finds the intersection of set
6517/// of protocols inherited from two distinct objective-c pointer objects.
6518/// It is used to build composite qualifier list of the composite type of
6519/// the conditional expression involving two objective-c pointer objects.
6520static
6521void getIntersectionOfProtocols(ASTContext &Context,
6522 const ObjCObjectPointerType *LHSOPT,
6523 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006524 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006525
John McCall8b07ec22010-05-15 11:32:37 +00006526 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6527 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6528 assert(LHS->getInterface() && "LHS must have an interface base");
6529 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006530
6531 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6532 unsigned LHSNumProtocols = LHS->getNumProtocols();
6533 if (LHSNumProtocols > 0)
6534 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6535 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006536 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006537 Context.CollectInheritedProtocols(LHS->getInterface(),
6538 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006539 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6540 LHSInheritedProtocols.end());
6541 }
6542
6543 unsigned RHSNumProtocols = RHS->getNumProtocols();
6544 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006545 ObjCProtocolDecl **RHSProtocols =
6546 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006547 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6548 if (InheritedProtocolSet.count(RHSProtocols[i]))
6549 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006550 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006551 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006552 Context.CollectInheritedProtocols(RHS->getInterface(),
6553 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006554 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6555 RHSInheritedProtocols.begin(),
6556 E = RHSInheritedProtocols.end(); I != E; ++I)
6557 if (InheritedProtocolSet.count((*I)))
6558 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006559 }
6560}
6561
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006562/// areCommonBaseCompatible - Returns common base class of the two classes if
6563/// one found. Note that this is O'2 algorithm. But it will be called as the
6564/// last type comparison in a ?-exp of ObjC pointer types before a
6565/// warning is issued. So, its invokation is extremely rare.
6566QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006567 const ObjCObjectPointerType *Lptr,
6568 const ObjCObjectPointerType *Rptr) {
6569 const ObjCObjectType *LHS = Lptr->getObjectType();
6570 const ObjCObjectType *RHS = Rptr->getObjectType();
6571 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6572 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006573 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006574 return QualType();
6575
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006576 do {
John McCall8b07ec22010-05-15 11:32:37 +00006577 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006578 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006579 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006580 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6581
6582 QualType Result = QualType(LHS, 0);
6583 if (!Protocols.empty())
6584 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6585 Result = getObjCObjectPointerType(Result);
6586 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006587 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006588 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006589
6590 return QualType();
6591}
6592
John McCall8b07ec22010-05-15 11:32:37 +00006593bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6594 const ObjCObjectType *RHS) {
6595 assert(LHS->getInterface() && "LHS is not an interface type");
6596 assert(RHS->getInterface() && "RHS is not an interface type");
6597
Chris Lattner49af6a42008-04-07 06:51:04 +00006598 // Verify that the base decls are compatible: the RHS must be a subclass of
6599 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006600 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006601 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006602
Chris Lattner49af6a42008-04-07 06:51:04 +00006603 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6604 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006605 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006606 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006607
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006608 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6609 // more detailed analysis is required.
6610 if (RHS->getNumProtocols() == 0) {
6611 // OK, if LHS is a superclass of RHS *and*
6612 // this superclass is assignment compatible with LHS.
6613 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006614 bool IsSuperClass =
6615 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6616 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006617 // OK if conversion of LHS to SuperClass results in narrowing of types
6618 // ; i.e., SuperClass may implement at least one of the protocols
6619 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6620 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6621 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006622 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006623 // If super class has no protocols, it is not a match.
6624 if (SuperClassInheritedProtocols.empty())
6625 return false;
6626
6627 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6628 LHSPE = LHS->qual_end();
6629 LHSPI != LHSPE; LHSPI++) {
6630 bool SuperImplementsProtocol = false;
6631 ObjCProtocolDecl *LHSProto = (*LHSPI);
6632
6633 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6634 SuperClassInheritedProtocols.begin(),
6635 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6636 ObjCProtocolDecl *SuperClassProto = (*I);
6637 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6638 SuperImplementsProtocol = true;
6639 break;
6640 }
6641 }
6642 if (!SuperImplementsProtocol)
6643 return false;
6644 }
6645 return true;
6646 }
6647 return false;
6648 }
Mike Stump11289f42009-09-09 15:08:12 +00006649
John McCall8b07ec22010-05-15 11:32:37 +00006650 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6651 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006652 LHSPI != LHSPE; LHSPI++) {
6653 bool RHSImplementsProtocol = false;
6654
6655 // If the RHS doesn't implement the protocol on the left, the types
6656 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006657 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6658 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006659 RHSPI != RHSPE; RHSPI++) {
6660 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006661 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006662 break;
6663 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006664 }
6665 // FIXME: For better diagnostics, consider passing back the protocol name.
6666 if (!RHSImplementsProtocol)
6667 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006668 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006669 // The RHS implements all protocols listed on the LHS.
6670 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006671}
6672
Steve Naroffb7605152009-02-12 17:52:19 +00006673bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6674 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006675 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6676 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006677
Steve Naroff7cae42b2009-07-10 23:34:53 +00006678 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006679 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006680
6681 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6682 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006683}
6684
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006685bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6686 return canAssignObjCInterfaces(
6687 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6688 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6689}
6690
Mike Stump11289f42009-09-09 15:08:12 +00006691/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006692/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006693/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006694/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006695bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6696 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006697 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006698 return hasSameType(LHS, RHS);
6699
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006700 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006701}
6702
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006703bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006704 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006705}
6706
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006707bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6708 return !mergeTypes(LHS, RHS, true).isNull();
6709}
6710
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006711/// mergeTransparentUnionType - if T is a transparent union type and a member
6712/// of T is compatible with SubType, return the merged type, else return
6713/// QualType()
6714QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6715 bool OfBlockPointer,
6716 bool Unqualified) {
6717 if (const RecordType *UT = T->getAsUnionType()) {
6718 RecordDecl *UD = UT->getDecl();
6719 if (UD->hasAttr<TransparentUnionAttr>()) {
6720 for (RecordDecl::field_iterator it = UD->field_begin(),
6721 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006722 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006723 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6724 if (!MT.isNull())
6725 return MT;
6726 }
6727 }
6728 }
6729
6730 return QualType();
6731}
6732
6733/// mergeFunctionArgumentTypes - merge two types which appear as function
6734/// argument types
6735QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6736 bool OfBlockPointer,
6737 bool Unqualified) {
6738 // GNU extension: two types are compatible if they appear as a function
6739 // argument, one of the types is a transparent union type and the other
6740 // type is compatible with a union member
6741 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6742 Unqualified);
6743 if (!lmerge.isNull())
6744 return lmerge;
6745
6746 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6747 Unqualified);
6748 if (!rmerge.isNull())
6749 return rmerge;
6750
6751 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6752}
6753
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006754QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006755 bool OfBlockPointer,
6756 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006757 const FunctionType *lbase = lhs->getAs<FunctionType>();
6758 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006759 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6760 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006761 bool allLTypes = true;
6762 bool allRTypes = true;
6763
6764 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006765 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006766 if (OfBlockPointer) {
6767 QualType RHS = rbase->getResultType();
6768 QualType LHS = lbase->getResultType();
6769 bool UnqualifiedResult = Unqualified;
6770 if (!UnqualifiedResult)
6771 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006772 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006773 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006774 else
John McCall8c6b56f2010-12-15 01:06:38 +00006775 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6776 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006777 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006778
6779 if (Unqualified)
6780 retType = retType.getUnqualifiedType();
6781
6782 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6783 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6784 if (Unqualified) {
6785 LRetType = LRetType.getUnqualifiedType();
6786 RRetType = RRetType.getUnqualifiedType();
6787 }
6788
6789 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006790 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006791 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006792 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006793
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006794 // FIXME: double check this
6795 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6796 // rbase->getRegParmAttr() != 0 &&
6797 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006798 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6799 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006800
Douglas Gregor8c940862010-01-18 17:14:39 +00006801 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00006802 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00006803 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006804
John McCall8c6b56f2010-12-15 01:06:38 +00006805 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006806 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6807 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006808 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6809 return QualType();
6810
John McCall31168b02011-06-15 23:02:42 +00006811 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6812 return QualType();
6813
John McCall8c6b56f2010-12-15 01:06:38 +00006814 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6815 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006816
Rafael Espindola8778c282012-11-29 16:09:03 +00006817 if (lbaseInfo.getNoReturn() != NoReturn)
6818 allLTypes = false;
6819 if (rbaseInfo.getNoReturn() != NoReturn)
6820 allRTypes = false;
6821
John McCall31168b02011-06-15 23:02:42 +00006822 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006823
Eli Friedman47f77112008-08-22 00:56:42 +00006824 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006825 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6826 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006827 unsigned lproto_nargs = lproto->getNumArgs();
6828 unsigned rproto_nargs = rproto->getNumArgs();
6829
6830 // Compatible functions must have the same number of arguments
6831 if (lproto_nargs != rproto_nargs)
6832 return QualType();
6833
6834 // Variadic and non-variadic functions aren't compatible
6835 if (lproto->isVariadic() != rproto->isVariadic())
6836 return QualType();
6837
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006838 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6839 return QualType();
6840
Fariborz Jahanian97676972011-09-28 21:52:05 +00006841 if (LangOpts.ObjCAutoRefCount &&
6842 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6843 return QualType();
6844
Eli Friedman47f77112008-08-22 00:56:42 +00006845 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006846 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00006847 for (unsigned i = 0; i < lproto_nargs; i++) {
6848 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6849 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006850 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6851 OfBlockPointer,
6852 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006853 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006854
6855 if (Unqualified)
6856 argtype = argtype.getUnqualifiedType();
6857
Eli Friedman47f77112008-08-22 00:56:42 +00006858 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006859 if (Unqualified) {
6860 largtype = largtype.getUnqualifiedType();
6861 rargtype = rargtype.getUnqualifiedType();
6862 }
6863
Chris Lattner465fa322008-10-05 17:34:18 +00006864 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6865 allLTypes = false;
6866 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6867 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006868 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006869
Eli Friedman47f77112008-08-22 00:56:42 +00006870 if (allLTypes) return lhs;
6871 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006872
6873 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6874 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00006875 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006876 }
6877
6878 if (lproto) allRTypes = false;
6879 if (rproto) allLTypes = false;
6880
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006881 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006882 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006883 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006884 if (proto->isVariadic()) return QualType();
6885 // Check that the types are compatible with the types that
6886 // would result from default argument promotions (C99 6.7.5.3p15).
6887 // The only types actually affected are promotable integer
6888 // types and floats, which would be passed as a different
6889 // type depending on whether the prototype is visible.
6890 unsigned proto_nargs = proto->getNumArgs();
6891 for (unsigned i = 0; i < proto_nargs; ++i) {
6892 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00006893
Eli Friedman448ce402012-08-30 00:44:15 +00006894 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00006895 // to pass enum values.
Eli Friedman448ce402012-08-30 00:44:15 +00006896 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
6897 argTy = Enum->getDecl()->getIntegerType();
6898 if (argTy.isNull())
6899 return QualType();
6900 }
Douglas Gregor2973d402010-02-03 19:27:29 +00006901
Eli Friedman47f77112008-08-22 00:56:42 +00006902 if (argTy->isPromotableIntegerType() ||
6903 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6904 return QualType();
6905 }
6906
6907 if (allLTypes) return lhs;
6908 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006909
6910 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6911 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00006912 return getFunctionType(retType,
6913 ArrayRef<QualType>(proto->arg_type_begin(),
6914 proto->getNumArgs()),
6915 EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006916 }
6917
6918 if (allLTypes) return lhs;
6919 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00006920 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00006921}
6922
John McCall433c2e62013-03-21 00:10:07 +00006923/// Given that we have an enum type and a non-enum type, try to merge them.
6924static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
6925 QualType other, bool isBlockReturnType) {
6926 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
6927 // a signed integer type, or an unsigned integer type.
6928 // Compatibility is based on the underlying type, not the promotion
6929 // type.
6930 QualType underlyingType = ET->getDecl()->getIntegerType();
6931 if (underlyingType.isNull()) return QualType();
6932 if (Context.hasSameType(underlyingType, other))
6933 return other;
6934
6935 // In block return types, we're more permissive and accept any
6936 // integral type of the same size.
6937 if (isBlockReturnType && other->isIntegerType() &&
6938 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
6939 return other;
6940
6941 return QualType();
6942}
6943
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006944QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006945 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006946 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00006947 // C++ [expr]: If an expression initially has the type "reference to T", the
6948 // type is adjusted to "T" prior to any further analysis, the expression
6949 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006950 // expression is an lvalue unless the reference is an rvalue reference and
6951 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00006952 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6953 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006954
6955 if (Unqualified) {
6956 LHS = LHS.getUnqualifiedType();
6957 RHS = RHS.getUnqualifiedType();
6958 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00006959
Eli Friedman47f77112008-08-22 00:56:42 +00006960 QualType LHSCan = getCanonicalType(LHS),
6961 RHSCan = getCanonicalType(RHS);
6962
6963 // If two types are identical, they are compatible.
6964 if (LHSCan == RHSCan)
6965 return LHS;
6966
John McCall8ccfcb52009-09-24 19:53:00 +00006967 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006968 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6969 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00006970 if (LQuals != RQuals) {
6971 // If any of these qualifiers are different, we have a type
6972 // mismatch.
6973 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00006974 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6975 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00006976 return QualType();
6977
6978 // Exactly one GC qualifier difference is allowed: __strong is
6979 // okay if the other type has no GC qualifier but is an Objective
6980 // C object pointer (i.e. implicitly strong by default). We fix
6981 // this by pretending that the unqualified type was actually
6982 // qualified __strong.
6983 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6984 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6985 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6986
6987 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6988 return QualType();
6989
6990 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6991 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6992 }
6993 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6994 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6995 }
Eli Friedman47f77112008-08-22 00:56:42 +00006996 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00006997 }
6998
6999 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007000
Eli Friedmandcca6332009-06-01 01:22:52 +00007001 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7002 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007003
Chris Lattnerfd652912008-01-14 05:45:46 +00007004 // We want to consider the two function types to be the same for these
7005 // comparisons, just force one to the other.
7006 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7007 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007008
7009 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007010 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7011 LHSClass = Type::ConstantArray;
7012 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7013 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007014
John McCall8b07ec22010-05-15 11:32:37 +00007015 // ObjCInterfaces are just specialized ObjCObjects.
7016 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7017 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7018
Nate Begemance4d7fc2008-04-18 23:10:10 +00007019 // Canonicalize ExtVector -> Vector.
7020 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7021 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007022
Chris Lattner95554662008-04-07 05:43:21 +00007023 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007024 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007025 // Note that we only have special rules for turning block enum
7026 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007027 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007028 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007029 }
John McCall9dd450b2009-09-21 23:43:11 +00007030 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007031 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007032 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007033 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007034 if (OfBlockPointer && !BlockReturnType) {
7035 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7036 return LHS;
7037 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7038 return RHS;
7039 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007040
Eli Friedman47f77112008-08-22 00:56:42 +00007041 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007042 }
Eli Friedman47f77112008-08-22 00:56:42 +00007043
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007044 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007045 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007046#define TYPE(Class, Base)
7047#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007048#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007049#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7050#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7051#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007052 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007053
Richard Smith27d807c2013-04-30 13:56:41 +00007054 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007055 case Type::LValueReference:
7056 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007057 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007058 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007059
John McCall8b07ec22010-05-15 11:32:37 +00007060 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007061 case Type::IncompleteArray:
7062 case Type::VariableArray:
7063 case Type::FunctionProto:
7064 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007065 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007066
Chris Lattnerfd652912008-01-14 05:45:46 +00007067 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007068 {
7069 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007070 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7071 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007072 if (Unqualified) {
7073 LHSPointee = LHSPointee.getUnqualifiedType();
7074 RHSPointee = RHSPointee.getUnqualifiedType();
7075 }
7076 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7077 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007078 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007079 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007080 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007081 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007082 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007083 return getPointerType(ResultType);
7084 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007085 case Type::BlockPointer:
7086 {
7087 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007088 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7089 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007090 if (Unqualified) {
7091 LHSPointee = LHSPointee.getUnqualifiedType();
7092 RHSPointee = RHSPointee.getUnqualifiedType();
7093 }
7094 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7095 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007096 if (ResultType.isNull()) return QualType();
7097 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7098 return LHS;
7099 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7100 return RHS;
7101 return getBlockPointerType(ResultType);
7102 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007103 case Type::Atomic:
7104 {
7105 // Merge two pointer types, while trying to preserve typedef info
7106 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7107 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7108 if (Unqualified) {
7109 LHSValue = LHSValue.getUnqualifiedType();
7110 RHSValue = RHSValue.getUnqualifiedType();
7111 }
7112 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7113 Unqualified);
7114 if (ResultType.isNull()) return QualType();
7115 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7116 return LHS;
7117 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7118 return RHS;
7119 return getAtomicType(ResultType);
7120 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007121 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007122 {
7123 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7124 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7125 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7126 return QualType();
7127
7128 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7129 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007130 if (Unqualified) {
7131 LHSElem = LHSElem.getUnqualifiedType();
7132 RHSElem = RHSElem.getUnqualifiedType();
7133 }
7134
7135 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007136 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007137 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7138 return LHS;
7139 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7140 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007141 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7142 ArrayType::ArraySizeModifier(), 0);
7143 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7144 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007145 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7146 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007147 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7148 return LHS;
7149 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7150 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007151 if (LVAT) {
7152 // FIXME: This isn't correct! But tricky to implement because
7153 // the array's size has to be the size of LHS, but the type
7154 // has to be different.
7155 return LHS;
7156 }
7157 if (RVAT) {
7158 // FIXME: This isn't correct! But tricky to implement because
7159 // the array's size has to be the size of RHS, but the type
7160 // has to be different.
7161 return RHS;
7162 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007163 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7164 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007165 return getIncompleteArrayType(ResultType,
7166 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007167 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007168 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007169 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007170 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007171 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007172 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007173 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007174 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007175 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007176 case Type::Complex:
7177 // Distinct complex types are incompatible.
7178 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007179 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007180 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007181 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7182 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007183 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007184 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007185 case Type::ObjCObject: {
7186 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007187 // FIXME: This should be type compatibility, e.g. whether
7188 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007189 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7190 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7191 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007192 return LHS;
7193
Eli Friedman47f77112008-08-22 00:56:42 +00007194 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007195 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007196 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007197 if (OfBlockPointer) {
7198 if (canAssignObjCInterfacesInBlockPointer(
7199 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007200 RHS->getAs<ObjCObjectPointerType>(),
7201 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007202 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007203 return QualType();
7204 }
John McCall9dd450b2009-09-21 23:43:11 +00007205 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7206 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007207 return LHS;
7208
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007209 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007210 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007211 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007212
David Blaikie8a40f702012-01-17 06:56:22 +00007213 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007214}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007215
Fariborz Jahanian97676972011-09-28 21:52:05 +00007216bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7217 const FunctionProtoType *FromFunctionType,
7218 const FunctionProtoType *ToFunctionType) {
7219 if (FromFunctionType->hasAnyConsumedArgs() !=
7220 ToFunctionType->hasAnyConsumedArgs())
7221 return false;
7222 FunctionProtoType::ExtProtoInfo FromEPI =
7223 FromFunctionType->getExtProtoInfo();
7224 FunctionProtoType::ExtProtoInfo ToEPI =
7225 ToFunctionType->getExtProtoInfo();
7226 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
7227 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
7228 ArgIdx != NumArgs; ++ArgIdx) {
7229 if (FromEPI.ConsumedArguments[ArgIdx] !=
7230 ToEPI.ConsumedArguments[ArgIdx])
7231 return false;
7232 }
7233 return true;
7234}
7235
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007236/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7237/// 'RHS' attributes and returns the merged version; including for function
7238/// return types.
7239QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7240 QualType LHSCan = getCanonicalType(LHS),
7241 RHSCan = getCanonicalType(RHS);
7242 // If two types are identical, they are compatible.
7243 if (LHSCan == RHSCan)
7244 return LHS;
7245 if (RHSCan->isFunctionType()) {
7246 if (!LHSCan->isFunctionType())
7247 return QualType();
7248 QualType OldReturnType =
7249 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7250 QualType NewReturnType =
7251 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7252 QualType ResReturnType =
7253 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7254 if (ResReturnType.isNull())
7255 return QualType();
7256 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7257 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7258 // In either case, use OldReturnType to build the new function type.
7259 const FunctionType *F = LHS->getAs<FunctionType>();
7260 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007261 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7262 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007263 QualType ResultType
Jordan Rose5c382722013-03-08 21:51:21 +00007264 = getFunctionType(OldReturnType,
7265 ArrayRef<QualType>(FPT->arg_type_begin(),
7266 FPT->getNumArgs()),
7267 EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007268 return ResultType;
7269 }
7270 }
7271 return QualType();
7272 }
7273
7274 // If the qualifiers are different, the types can still be merged.
7275 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7276 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7277 if (LQuals != RQuals) {
7278 // If any of these qualifiers are different, we have a type mismatch.
7279 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7280 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7281 return QualType();
7282
7283 // Exactly one GC qualifier difference is allowed: __strong is
7284 // okay if the other type has no GC qualifier but is an Objective
7285 // C object pointer (i.e. implicitly strong by default). We fix
7286 // this by pretending that the unqualified type was actually
7287 // qualified __strong.
7288 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7289 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7290 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7291
7292 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7293 return QualType();
7294
7295 if (GC_L == Qualifiers::Strong)
7296 return LHS;
7297 if (GC_R == Qualifiers::Strong)
7298 return RHS;
7299 return QualType();
7300 }
7301
7302 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7303 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7304 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7305 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7306 if (ResQT == LHSBaseQT)
7307 return LHS;
7308 if (ResQT == RHSBaseQT)
7309 return RHS;
7310 }
7311 return QualType();
7312}
7313
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007314//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007315// Integer Predicates
7316//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007317
Jay Foad39c79802011-01-12 09:06:06 +00007318unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00007319 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00007320 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007321 if (T->isBooleanType())
7322 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007323 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007324 return (unsigned)getTypeSize(T);
7325}
7326
Abramo Bagnara13640492012-09-09 10:21:24 +00007327QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007328 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007329
7330 // Turn <4 x signed int> -> <4 x unsigned int>
7331 if (const VectorType *VTy = T->getAs<VectorType>())
7332 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007333 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007334
7335 // For enums, we return the unsigned version of the base type.
7336 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007337 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007338
7339 const BuiltinType *BTy = T->getAs<BuiltinType>();
7340 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007341 switch (BTy->getKind()) {
7342 case BuiltinType::Char_S:
7343 case BuiltinType::SChar:
7344 return UnsignedCharTy;
7345 case BuiltinType::Short:
7346 return UnsignedShortTy;
7347 case BuiltinType::Int:
7348 return UnsignedIntTy;
7349 case BuiltinType::Long:
7350 return UnsignedLongTy;
7351 case BuiltinType::LongLong:
7352 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007353 case BuiltinType::Int128:
7354 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007355 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007356 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007357 }
7358}
7359
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007360ASTMutationListener::~ASTMutationListener() { }
7361
Chris Lattnerecd79c62009-06-14 00:45:47 +00007362
7363//===----------------------------------------------------------------------===//
7364// Builtin Type Computation
7365//===----------------------------------------------------------------------===//
7366
7367/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007368/// pointer over the consumed characters. This returns the resultant type. If
7369/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7370/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7371/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007372///
7373/// RequiresICE is filled in on return to indicate whether the value is required
7374/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007375static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007376 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007377 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007378 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007379 // Modifiers.
7380 int HowLong = 0;
7381 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007382 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007383
Chris Lattnerdc226c22010-10-01 22:42:38 +00007384 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007385 bool Done = false;
7386 while (!Done) {
7387 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007388 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007389 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007390 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007391 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007392 case 'S':
7393 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7394 assert(!Signed && "Can't use 'S' modifier multiple times!");
7395 Signed = true;
7396 break;
7397 case 'U':
7398 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7399 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7400 Unsigned = true;
7401 break;
7402 case 'L':
7403 assert(HowLong <= 2 && "Can't have LLLL modifier");
7404 ++HowLong;
7405 break;
7406 }
7407 }
7408
7409 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007410
Chris Lattnerecd79c62009-06-14 00:45:47 +00007411 // Read the base type.
7412 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007413 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007414 case 'v':
7415 assert(HowLong == 0 && !Signed && !Unsigned &&
7416 "Bad modifiers used with 'v'!");
7417 Type = Context.VoidTy;
7418 break;
7419 case 'f':
7420 assert(HowLong == 0 && !Signed && !Unsigned &&
7421 "Bad modifiers used with 'f'!");
7422 Type = Context.FloatTy;
7423 break;
7424 case 'd':
7425 assert(HowLong < 2 && !Signed && !Unsigned &&
7426 "Bad modifiers used with 'd'!");
7427 if (HowLong)
7428 Type = Context.LongDoubleTy;
7429 else
7430 Type = Context.DoubleTy;
7431 break;
7432 case 's':
7433 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7434 if (Unsigned)
7435 Type = Context.UnsignedShortTy;
7436 else
7437 Type = Context.ShortTy;
7438 break;
7439 case 'i':
7440 if (HowLong == 3)
7441 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7442 else if (HowLong == 2)
7443 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7444 else if (HowLong == 1)
7445 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7446 else
7447 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7448 break;
7449 case 'c':
7450 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7451 if (Signed)
7452 Type = Context.SignedCharTy;
7453 else if (Unsigned)
7454 Type = Context.UnsignedCharTy;
7455 else
7456 Type = Context.CharTy;
7457 break;
7458 case 'b': // boolean
7459 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7460 Type = Context.BoolTy;
7461 break;
7462 case 'z': // size_t.
7463 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7464 Type = Context.getSizeType();
7465 break;
7466 case 'F':
7467 Type = Context.getCFConstantStringType();
7468 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007469 case 'G':
7470 Type = Context.getObjCIdType();
7471 break;
7472 case 'H':
7473 Type = Context.getObjCSelType();
7474 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007475 case 'M':
7476 Type = Context.getObjCSuperType();
7477 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007478 case 'a':
7479 Type = Context.getBuiltinVaListType();
7480 assert(!Type.isNull() && "builtin va list type not initialized!");
7481 break;
7482 case 'A':
7483 // This is a "reference" to a va_list; however, what exactly
7484 // this means depends on how va_list is defined. There are two
7485 // different kinds of va_list: ones passed by value, and ones
7486 // passed by reference. An example of a by-value va_list is
7487 // x86, where va_list is a char*. An example of by-ref va_list
7488 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7489 // we want this argument to be a char*&; for x86-64, we want
7490 // it to be a __va_list_tag*.
7491 Type = Context.getBuiltinVaListType();
7492 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007493 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007494 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007495 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007496 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007497 break;
7498 case 'V': {
7499 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007500 unsigned NumElements = strtoul(Str, &End, 10);
7501 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007502 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007503
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007504 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7505 RequiresICE, false);
7506 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007507
7508 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007509 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007510 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007511 break;
7512 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007513 case 'E': {
7514 char *End;
7515
7516 unsigned NumElements = strtoul(Str, &End, 10);
7517 assert(End != Str && "Missing vector size");
7518
7519 Str = End;
7520
7521 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7522 false);
7523 Type = Context.getExtVectorType(ElementType, NumElements);
7524 break;
7525 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007526 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007527 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7528 false);
7529 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007530 Type = Context.getComplexType(ElementType);
7531 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007532 }
7533 case 'Y' : {
7534 Type = Context.getPointerDiffType();
7535 break;
7536 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007537 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007538 Type = Context.getFILEType();
7539 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007540 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007541 return QualType();
7542 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007543 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007544 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007545 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007546 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007547 else
7548 Type = Context.getjmp_bufType();
7549
Mike Stump2adb4da2009-07-28 23:47:15 +00007550 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007551 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007552 return QualType();
7553 }
7554 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007555 case 'K':
7556 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7557 Type = Context.getucontext_tType();
7558
7559 if (Type.isNull()) {
7560 Error = ASTContext::GE_Missing_ucontext;
7561 return QualType();
7562 }
7563 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007564 case 'p':
7565 Type = Context.getProcessIDType();
7566 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007567 }
Mike Stump11289f42009-09-09 15:08:12 +00007568
Chris Lattnerdc226c22010-10-01 22:42:38 +00007569 // If there are modifiers and if we're allowed to parse them, go for it.
7570 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007571 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007572 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007573 default: Done = true; --Str; break;
7574 case '*':
7575 case '&': {
7576 // Both pointers and references can have their pointee types
7577 // qualified with an address space.
7578 char *End;
7579 unsigned AddrSpace = strtoul(Str, &End, 10);
7580 if (End != Str && AddrSpace != 0) {
7581 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7582 Str = End;
7583 }
7584 if (c == '*')
7585 Type = Context.getPointerType(Type);
7586 else
7587 Type = Context.getLValueReferenceType(Type);
7588 break;
7589 }
7590 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7591 case 'C':
7592 Type = Type.withConst();
7593 break;
7594 case 'D':
7595 Type = Context.getVolatileType(Type);
7596 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007597 case 'R':
7598 Type = Type.withRestrict();
7599 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007600 }
7601 }
Chris Lattner84733392010-10-01 07:13:18 +00007602
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007603 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007604 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007605
Chris Lattnerecd79c62009-06-14 00:45:47 +00007606 return Type;
7607}
7608
7609/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007610QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007611 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007612 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007613 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007614
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007615 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007616
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007617 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007618 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007619 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7620 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007621 if (Error != GE_None)
7622 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007623
7624 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7625
Chris Lattnerecd79c62009-06-14 00:45:47 +00007626 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007627 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007628 if (Error != GE_None)
7629 return QualType();
7630
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007631 // If this argument is required to be an IntegerConstantExpression and the
7632 // caller cares, fill in the bitmask we return.
7633 if (RequiresICE && IntegerConstantArgs)
7634 *IntegerConstantArgs |= 1 << ArgTypes.size();
7635
Chris Lattnerecd79c62009-06-14 00:45:47 +00007636 // Do array -> pointer decay. The builtin should use the decayed type.
7637 if (Ty->isArrayType())
7638 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007639
Chris Lattnerecd79c62009-06-14 00:45:47 +00007640 ArgTypes.push_back(Ty);
7641 }
7642
7643 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7644 "'.' should only occur at end of builtin type list!");
7645
John McCall991eb4b2010-12-21 00:44:39 +00007646 FunctionType::ExtInfo EI;
7647 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7648
7649 bool Variadic = (TypeStr[0] == '.');
7650
7651 // We really shouldn't be making a no-proto type here, especially in C++.
7652 if (ArgTypes.empty() && Variadic)
7653 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007654
John McCalldb40c7f2010-12-14 08:05:40 +00007655 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007656 EPI.ExtInfo = EI;
7657 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007658
Jordan Rose5c382722013-03-08 21:51:21 +00007659 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007660}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007661
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007662GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
7663 GVALinkage External = GVA_StrongExternal;
7664
7665 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007666 switch (L) {
7667 case NoLinkage:
7668 case InternalLinkage:
7669 case UniqueExternalLinkage:
7670 return GVA_Internal;
7671
7672 case ExternalLinkage:
7673 switch (FD->getTemplateSpecializationKind()) {
7674 case TSK_Undeclared:
7675 case TSK_ExplicitSpecialization:
7676 External = GVA_StrongExternal;
7677 break;
7678
7679 case TSK_ExplicitInstantiationDefinition:
7680 return GVA_ExplicitTemplateInstantiation;
7681
7682 case TSK_ExplicitInstantiationDeclaration:
7683 case TSK_ImplicitInstantiation:
7684 External = GVA_TemplateInstantiation;
7685 break;
7686 }
7687 }
7688
7689 if (!FD->isInlined())
7690 return External;
7691
David Blaikiebbafb8a2012-03-11 07:00:24 +00007692 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007693 // GNU or C99 inline semantics. Determine whether this symbol should be
7694 // externally visible.
7695 if (FD->isInlineDefinitionExternallyVisible())
7696 return External;
7697
7698 // C99 inline semantics, where the symbol is not externally visible.
7699 return GVA_C99Inline;
7700 }
7701
7702 // C++0x [temp.explicit]p9:
7703 // [ Note: The intent is that an inline function that is the subject of
7704 // an explicit instantiation declaration will still be implicitly
7705 // instantiated when used so that the body can be considered for
7706 // inlining, but that no out-of-line copy of the inline function would be
7707 // generated in the translation unit. -- end note ]
7708 if (FD->getTemplateSpecializationKind()
7709 == TSK_ExplicitInstantiationDeclaration)
7710 return GVA_C99Inline;
7711
7712 return GVA_CXXInline;
7713}
7714
7715GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7716 // If this is a static data member, compute the kind of template
7717 // specialization. Otherwise, this variable is not part of a
7718 // template.
7719 TemplateSpecializationKind TSK = TSK_Undeclared;
7720 if (VD->isStaticDataMember())
7721 TSK = VD->getTemplateSpecializationKind();
7722
7723 Linkage L = VD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007724
7725 switch (L) {
7726 case NoLinkage:
7727 case InternalLinkage:
7728 case UniqueExternalLinkage:
7729 return GVA_Internal;
7730
7731 case ExternalLinkage:
7732 switch (TSK) {
7733 case TSK_Undeclared:
7734 case TSK_ExplicitSpecialization:
7735 return GVA_StrongExternal;
7736
7737 case TSK_ExplicitInstantiationDeclaration:
7738 llvm_unreachable("Variable should not be instantiated");
7739 // Fall through to treat this like any other instantiation.
7740
7741 case TSK_ExplicitInstantiationDefinition:
7742 return GVA_ExplicitTemplateInstantiation;
7743
7744 case TSK_ImplicitInstantiation:
7745 return GVA_TemplateInstantiation;
7746 }
7747 }
7748
David Blaikie8a40f702012-01-17 06:56:22 +00007749 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007750}
7751
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007752bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007753 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7754 if (!VD->isFileVarDecl())
7755 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00007756 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7757 // We never need to emit an uninstantiated function template.
7758 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7759 return false;
7760 } else
7761 return false;
7762
7763 // If this is a member of a class template, we do not need to emit it.
7764 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007765 return false;
7766
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007767 // Weak references don't produce any output by themselves.
7768 if (D->hasAttr<WeakRefAttr>())
7769 return false;
7770
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007771 // Aliases and used decls are required.
7772 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7773 return true;
7774
7775 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7776 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007777 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007778 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007779
7780 // Constructors and destructors are required.
7781 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7782 return true;
7783
John McCall6bd2a892013-01-25 22:31:03 +00007784 // The key function for a class is required. This rule only comes
7785 // into play when inline functions can be key functions, though.
7786 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7787 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7788 const CXXRecordDecl *RD = MD->getParent();
7789 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7790 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7791 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7792 return true;
7793 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007794 }
7795 }
7796
7797 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7798
7799 // static, static inline, always_inline, and extern inline functions can
7800 // always be deferred. Normal inline functions can be deferred in C99/C++.
7801 // Implicit template instantiations can also be deferred in C++.
7802 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007803 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007804 return false;
7805 return true;
7806 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007807
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007808 const VarDecl *VD = cast<VarDecl>(D);
7809 assert(VD->isFileVarDecl() && "Expected file scoped var");
7810
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007811 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7812 return false;
7813
Richard Smitha0e5e542012-11-12 21:38:00 +00007814 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007815 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smitha0e5e542012-11-12 21:38:00 +00007816 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7817 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007818
Richard Smitha0e5e542012-11-12 21:38:00 +00007819 // Variables that have destruction with side-effects are required.
7820 if (VD->getType().isDestructedType())
7821 return true;
7822
7823 // Variables that have initialization with side-effects are required.
7824 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7825 return true;
7826
7827 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007828}
Charles Davis53c59df2010-08-16 03:33:14 +00007829
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007830CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davis99202b32010-11-09 18:04:24 +00007831 // Pass through to the C++ ABI object
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007832 return ABI->getDefaultMethodCallConv(isVariadic);
7833}
7834
7835CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
John McCall359b8852013-01-25 22:30:49 +00007836 if (CC == CC_C && !LangOpts.MRTD &&
7837 getTargetInfo().getCXXABI().isMemberFunctionCCDefault())
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007838 return CC_Default;
7839 return CC;
Charles Davis99202b32010-11-09 18:04:24 +00007840}
7841
Jay Foad39c79802011-01-12 09:06:06 +00007842bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007843 // Pass through to the C++ ABI object
7844 return ABI->isNearlyEmpty(RD);
7845}
7846
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007847MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00007848 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00007849 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00007850 case TargetCXXABI::GenericItanium:
7851 case TargetCXXABI::GenericARM:
7852 case TargetCXXABI::iOS:
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007853 return createItaniumMangleContext(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00007854 case TargetCXXABI::Microsoft:
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007855 return createMicrosoftMangleContext(*this, getDiagnostics());
7856 }
David Blaikie83d382b2011-09-23 05:06:16 +00007857 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007858}
7859
Charles Davis53c59df2010-08-16 03:33:14 +00007860CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007861
7862size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00007863 return ASTRecordLayouts.getMemorySize()
7864 + llvm::capacity_in_bytes(ObjCLayouts)
7865 + llvm::capacity_in_bytes(KeyFunctions)
7866 + llvm::capacity_in_bytes(ObjCImpls)
7867 + llvm::capacity_in_bytes(BlockVarCopyInits)
7868 + llvm::capacity_in_bytes(DeclAttrs)
7869 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7870 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7871 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7872 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7873 + llvm::capacity_in_bytes(OverriddenMethods)
7874 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007875 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00007876 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007877}
Ted Kremenek540017e2011-10-06 05:00:56 +00007878
David Blaikie095deba2012-11-14 01:52:05 +00007879void ASTContext::addUnnamedTag(const TagDecl *Tag) {
7880 // FIXME: This mangling should be applied to function local classes too
7881 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl() ||
7882 !isa<CXXRecordDecl>(Tag->getParent()) || Tag->getLinkage() != ExternalLinkage)
7883 return;
7884
7885 std::pair<llvm::DenseMap<const DeclContext *, unsigned>::iterator, bool> P =
7886 UnnamedMangleContexts.insert(std::make_pair(Tag->getParent(), 0));
7887 UnnamedMangleNumbers.insert(std::make_pair(Tag, P.first->second++));
7888}
7889
7890int ASTContext::getUnnamedTagManglingNumber(const TagDecl *Tag) const {
7891 llvm::DenseMap<const TagDecl *, unsigned>::const_iterator I =
7892 UnnamedMangleNumbers.find(Tag);
7893 return I != UnnamedMangleNumbers.end() ? I->second : -1;
7894}
7895
Douglas Gregor63798542012-02-20 19:44:39 +00007896unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7897 CXXRecordDecl *Lambda = CallOperator->getParent();
7898 return LambdaMangleContexts[Lambda->getDeclContext()]
7899 .getManglingNumber(CallOperator);
7900}
7901
7902
Ted Kremenek540017e2011-10-06 05:00:56 +00007903void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7904 ParamIndices[D] = index;
7905}
7906
7907unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7908 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7909 assert(I != ParamIndices.end() &&
7910 "ParmIndices lacks entry set by ParmVarDecl");
7911 return I->second;
7912}