blob: 2a405271b6dd33c72abaa355827ad4f72b36352b [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
Aaron Ballmand428ff42013-05-04 16:56:22 +0000900 if (LangOpts.CPlusPlus && LangOpts.WChar) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000901 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000902 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
903 else // -fshort-wchar makes wchar_t be unsigned.
904 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
Aaron Ballmand428ff42013-05-04 16:56:22 +0000905 } else // C99 (or C++ using -fno-wchar)
Chris Lattner007cb022009-02-26 23:43:47 +0000906 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000907
James Molloy36365542012-05-04 10:55:22 +0000908 WIntTy = getFromTargetType(Target.getWIntType());
909
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000910 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
911 InitBuiltinType(Char16Ty, BuiltinType::Char16);
912 else // C99
913 Char16Ty = getFromTargetType(Target.getChar16Type());
914
915 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
916 InitBuiltinType(Char32Ty, BuiltinType::Char32);
917 else // C99
918 Char32Ty = getFromTargetType(Target.getChar32Type());
919
Douglas Gregor4619e432008-12-05 23:32:09 +0000920 // Placeholder type for type-dependent expressions whose type is
921 // completely unknown. No code should ever check a type against
922 // DependentTy and users should never see it; however, it is here to
923 // help diagnose failures to properly check for type-dependent
924 // expressions.
925 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000926
John McCall36e7fe32010-10-12 00:20:44 +0000927 // Placeholder type for functions.
928 InitBuiltinType(OverloadTy, BuiltinType::Overload);
929
John McCall0009fcc2011-04-26 20:42:42 +0000930 // Placeholder type for bound members.
931 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
932
John McCall526ab472011-10-25 17:37:35 +0000933 // Placeholder type for pseudo-objects.
934 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
935
John McCall31996342011-04-07 08:22:57 +0000936 // "any" type; useful for debugger-like clients.
937 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
938
John McCall8a6b59a2011-10-17 18:09:15 +0000939 // Placeholder type for unbridged ARC casts.
940 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
941
Eli Friedman34866c72012-08-31 00:14:07 +0000942 // Placeholder type for builtin functions.
943 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
944
Chris Lattner970e54e2006-11-12 00:37:36 +0000945 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000946 FloatComplexTy = getComplexType(FloatTy);
947 DoubleComplexTy = getComplexType(DoubleTy);
948 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000949
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000950 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000951 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
952 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000953 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000954
955 if (LangOpts.OpenCL) {
956 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
957 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
958 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
959 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
960 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
961 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000962
Guy Benyei61054192013-02-07 10:55:47 +0000963 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000964 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000965 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000966
967 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000968 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
969 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000970
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000971 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +0000972
973 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000974
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000975 // void * type
976 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000977
978 // nullptr type (C++0x 2.14.7)
979 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000980
981 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
982 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +0000983
984 // Builtin type used to help define __builtin_va_list.
985 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +0000986}
987
David Blaikie9c902b52011-09-25 23:23:43 +0000988DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000989 return SourceMgr.getDiagnostics();
990}
991
Douglas Gregor561eceb2010-08-30 16:49:28 +0000992AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
993 AttrVec *&Result = DeclAttrs[D];
994 if (!Result) {
995 void *Mem = Allocate(sizeof(AttrVec));
996 Result = new (Mem) AttrVec;
997 }
998
999 return *Result;
1000}
1001
1002/// \brief Erase the attributes corresponding to the given declaration.
1003void ASTContext::eraseDeclAttrs(const Decl *D) {
1004 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1005 if (Pos != DeclAttrs.end()) {
1006 Pos->second->~AttrVec();
1007 DeclAttrs.erase(Pos);
1008 }
1009}
1010
Douglas Gregor86d142a2009-10-08 07:24:58 +00001011MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001012ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001013 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +00001014 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001015 = InstantiatedFromStaticDataMember.find(Var);
1016 if (Pos == InstantiatedFromStaticDataMember.end())
1017 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001018
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001019 return Pos->second;
1020}
1021
Mike Stump11289f42009-09-09 15:08:12 +00001022void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001023ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001024 TemplateSpecializationKind TSK,
1025 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001026 assert(Inst->isStaticDataMember() && "Not a static data member");
1027 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1028 assert(!InstantiatedFromStaticDataMember[Inst] &&
1029 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +00001030 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001031 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001032}
1033
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001034FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1035 const FunctionDecl *FD){
1036 assert(FD && "Specialization is 0");
1037 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001038 = ClassScopeSpecializationPattern.find(FD);
1039 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001040 return 0;
1041
1042 return Pos->second;
1043}
1044
1045void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1046 FunctionDecl *Pattern) {
1047 assert(FD && "Specialization is 0");
1048 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001049 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001050}
1051
John McCalle61f2ba2009-11-18 02:36:19 +00001052NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001053ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001054 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001055 = InstantiatedFromUsingDecl.find(UUD);
1056 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001057 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001058
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001059 return Pos->second;
1060}
1061
1062void
John McCallb96ec562009-12-04 22:46:56 +00001063ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1064 assert((isa<UsingDecl>(Pattern) ||
1065 isa<UnresolvedUsingValueDecl>(Pattern) ||
1066 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1067 "pattern decl is not a using decl");
1068 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1069 InstantiatedFromUsingDecl[Inst] = Pattern;
1070}
1071
1072UsingShadowDecl *
1073ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1074 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1075 = InstantiatedFromUsingShadowDecl.find(Inst);
1076 if (Pos == InstantiatedFromUsingShadowDecl.end())
1077 return 0;
1078
1079 return Pos->second;
1080}
1081
1082void
1083ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1084 UsingShadowDecl *Pattern) {
1085 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1086 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001087}
1088
Anders Carlsson5da84842009-09-01 04:26:58 +00001089FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1090 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1091 = InstantiatedFromUnnamedFieldDecl.find(Field);
1092 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1093 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001094
Anders Carlsson5da84842009-09-01 04:26:58 +00001095 return Pos->second;
1096}
1097
1098void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1099 FieldDecl *Tmpl) {
1100 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1101 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1102 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1103 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001104
Anders Carlsson5da84842009-09-01 04:26:58 +00001105 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1106}
1107
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +00001108bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
1109 const FieldDecl *LastFD) const {
1110 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001111 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +00001112}
1113
Fariborz Jahanianeb397412011-05-02 17:20:56 +00001114bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
1115 const FieldDecl *LastFD) const {
1116 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001117 FD->getBitWidthValue(*this) == 0 &&
1118 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +00001119}
1120
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001121bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
1122 const FieldDecl *LastFD) const {
1123 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001124 FD->getBitWidthValue(*this) &&
1125 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001126}
1127
Chad Rosierf01a7dd2011-08-04 23:34:15 +00001128bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001129 const FieldDecl *LastFD) const {
1130 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001131 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001132}
1133
Chad Rosierf01a7dd2011-08-04 23:34:15 +00001134bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001135 const FieldDecl *LastFD) const {
1136 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001137 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001138}
1139
Douglas Gregor832940b2010-03-02 23:58:15 +00001140ASTContext::overridden_cxx_method_iterator
1141ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1142 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001143 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001144 if (Pos == OverriddenMethods.end())
1145 return 0;
1146
1147 return Pos->second.begin();
1148}
1149
1150ASTContext::overridden_cxx_method_iterator
1151ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1152 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001153 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001154 if (Pos == OverriddenMethods.end())
1155 return 0;
1156
1157 return Pos->second.end();
1158}
1159
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001160unsigned
1161ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1162 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001163 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001164 if (Pos == OverriddenMethods.end())
1165 return 0;
1166
1167 return Pos->second.size();
1168}
1169
Douglas Gregor832940b2010-03-02 23:58:15 +00001170void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1171 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001172 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001173 OverriddenMethods[Method].push_back(Overridden);
1174}
1175
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001176void ASTContext::getOverriddenMethods(
1177 const NamedDecl *D,
1178 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001179 assert(D);
1180
1181 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001182 Overridden.append(overridden_methods_begin(CXXMethod),
1183 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001184 return;
1185 }
1186
1187 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1188 if (!Method)
1189 return;
1190
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001191 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1192 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001193 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001194}
1195
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001196void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1197 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1198 assert(!Import->isFromASTFile() && "Non-local import declaration");
1199 if (!FirstLocalImport) {
1200 FirstLocalImport = Import;
1201 LastLocalImport = Import;
1202 return;
1203 }
1204
1205 LastLocalImport->NextLocalImport = Import;
1206 LastLocalImport = Import;
1207}
1208
Chris Lattner53cfe802007-07-18 17:52:12 +00001209//===----------------------------------------------------------------------===//
1210// Type Sizing and Analysis
1211//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001212
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001213/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1214/// scalar floating point type.
1215const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001216 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001217 assert(BT && "Not a floating point type!");
1218 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001219 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001220 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001221 case BuiltinType::Float: return Target->getFloatFormat();
1222 case BuiltinType::Double: return Target->getDoubleFormat();
1223 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001224 }
1225}
1226
Ken Dyck160146e2010-01-27 17:10:57 +00001227/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +00001228/// specified decl. Note that bitfields do not have a valid alignment, so
1229/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001230/// If @p RefAsPointee, references are treated like their underlying type
1231/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +00001232CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001233 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001234
John McCall94268702010-10-08 18:24:19 +00001235 bool UseAlignAttrOnly = false;
1236 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1237 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001238
John McCall94268702010-10-08 18:24:19 +00001239 // __attribute__((aligned)) can increase or decrease alignment
1240 // *except* on a struct or struct member, where it only increases
1241 // alignment unless 'packed' is also specified.
1242 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001243 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001244 // ignore that possibility; Sema should diagnose it.
1245 if (isa<FieldDecl>(D)) {
1246 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1247 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1248 } else {
1249 UseAlignAttrOnly = true;
1250 }
1251 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001252 else if (isa<FieldDecl>(D))
1253 UseAlignAttrOnly =
1254 D->hasAttr<PackedAttr>() ||
1255 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001256
John McCall4e819612011-01-20 07:57:12 +00001257 // If we're using the align attribute only, just ignore everything
1258 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001259 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001260 // do nothing
1261
John McCall94268702010-10-08 18:24:19 +00001262 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001263 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001264 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001265 if (RefAsPointee)
1266 T = RT->getPointeeType();
1267 else
1268 T = getPointerType(RT->getPointeeType());
1269 }
1270 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001271 // Adjust alignments of declarations with array type by the
1272 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +00001273 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +00001274 const ArrayType *arrayType;
1275 if (MinWidth && (arrayType = getAsArrayType(T))) {
1276 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001277 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +00001278 else if (isa<ConstantArrayType>(arrayType) &&
1279 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001280 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +00001281
John McCall33ddac02011-01-19 10:06:00 +00001282 // Walk through any array types while we're at it.
1283 T = getBaseElementType(arrayType);
1284 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001285 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001286 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1287 if (VD->hasGlobalStorage())
1288 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1289 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001290 }
John McCall4e819612011-01-20 07:57:12 +00001291
1292 // Fields can be subject to extra alignment constraints, like if
1293 // the field is packed, the struct is packed, or the struct has a
1294 // a max-field-alignment constraint (#pragma pack). So calculate
1295 // the actual alignment of the field within the struct, and then
1296 // (as we're expected to) constrain that by the alignment of the type.
1297 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1298 // So calculate the alignment of the field.
1299 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1300
1301 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +00001302 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001303
1304 // Use the GCD of that and the offset within the record.
1305 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1306 if (offset > 0) {
1307 // Alignment is always a power of 2, so the GCD will be a power of 2,
1308 // which means we get to do this crazy thing instead of Euclid's.
1309 uint64_t lowBitOfOffset = offset & (~offset + 1);
1310 if (lowBitOfOffset < fieldAlign)
1311 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1312 }
1313
1314 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +00001315 }
Chris Lattner68061312009-01-24 21:53:27 +00001316 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001317
Ken Dyckcc56c542011-01-15 18:38:59 +00001318 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001319}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001320
John McCallf1249922012-08-21 04:10:00 +00001321// getTypeInfoDataSizeInChars - Return the size of a type, in
1322// chars. If the type is a record, its data size is returned. This is
1323// the size of the memcpy that's performed when assigning this type
1324// using a trivial copy/move assignment operator.
1325std::pair<CharUnits, CharUnits>
1326ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1327 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1328
1329 // In C++, objects can sometimes be allocated into the tail padding
1330 // of a base-class subobject. We decide whether that's possible
1331 // during class layout, so here we can just trust the layout results.
1332 if (getLangOpts().CPlusPlus) {
1333 if (const RecordType *RT = T->getAs<RecordType>()) {
1334 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1335 sizeAndAlign.first = layout.getDataSize();
1336 }
1337 }
1338
1339 return sizeAndAlign;
1340}
1341
John McCall87fe5d52010-05-20 01:18:31 +00001342std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001343ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001344 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +00001345 return std::make_pair(toCharUnitsFromBits(Info.first),
1346 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +00001347}
1348
1349std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001350ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001351 return getTypeInfoInChars(T.getTypePtr());
1352}
1353
Daniel Dunbarc6475872012-03-09 04:12:54 +00001354std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1355 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1356 if (it != MemoizedTypeInfo.end())
1357 return it->second;
1358
1359 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1360 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1361 return Info;
1362}
1363
1364/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1365/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001366///
1367/// FIXME: Pointers into different addr spaces could have different sizes and
1368/// alignment requirements: getPointerInfo should take an AddrSpace, this
1369/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001370std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001371ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001372 uint64_t Width=0;
1373 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001374 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001375#define TYPE(Class, Base)
1376#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001377#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001378#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1379#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001380 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001381
Chris Lattner355332d2007-07-13 22:27:08 +00001382 case Type::FunctionNoProto:
1383 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001384 // GCC extension: alignof(function) = 32 bits
1385 Width = 0;
1386 Align = 32;
1387 break;
1388
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001389 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001390 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001391 Width = 0;
1392 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1393 break;
1394
Steve Naroff5c131802007-08-30 01:06:46 +00001395 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001396 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001397
Chris Lattner37e05872008-03-05 18:54:05 +00001398 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001399 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001400 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1401 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001402 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001403 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +00001404 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001405 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001406 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001407 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001408 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001409 const VectorType *VT = cast<VectorType>(T);
1410 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1411 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001412 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001413 // If the alignment is not a power of 2, round up to the next power of 2.
1414 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001415 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001416 Align = llvm::NextPowerOf2(Align);
1417 Width = llvm::RoundUpToAlignment(Width, Align);
1418 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001419 // Adjust the alignment based on the target max.
1420 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1421 if (TargetVectorAlign && TargetVectorAlign < Align)
1422 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001423 break;
1424 }
Chris Lattner647fb222007-07-18 18:26:58 +00001425
Chris Lattner7570e9c2008-03-08 08:52:55 +00001426 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001427 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001428 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001429 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001430 // GCC extension: alignof(void) = 8 bits.
1431 Width = 0;
1432 Align = 8;
1433 break;
1434
Chris Lattner6a4f7452007-12-19 19:23:28 +00001435 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001436 Width = Target->getBoolWidth();
1437 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001438 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001439 case BuiltinType::Char_S:
1440 case BuiltinType::Char_U:
1441 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001442 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001443 Width = Target->getCharWidth();
1444 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001445 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001446 case BuiltinType::WChar_S:
1447 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001448 Width = Target->getWCharWidth();
1449 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001450 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001451 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001452 Width = Target->getChar16Width();
1453 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001454 break;
1455 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001456 Width = Target->getChar32Width();
1457 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001458 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001459 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001460 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001461 Width = Target->getShortWidth();
1462 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001463 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001464 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001465 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001466 Width = Target->getIntWidth();
1467 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001468 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001469 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001470 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001471 Width = Target->getLongWidth();
1472 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001473 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001474 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001475 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001476 Width = Target->getLongLongWidth();
1477 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001478 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001479 case BuiltinType::Int128:
1480 case BuiltinType::UInt128:
1481 Width = 128;
1482 Align = 128; // int128_t is 128-bit aligned on all targets.
1483 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001484 case BuiltinType::Half:
1485 Width = Target->getHalfWidth();
1486 Align = Target->getHalfAlign();
1487 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001488 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001489 Width = Target->getFloatWidth();
1490 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001491 break;
1492 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001493 Width = Target->getDoubleWidth();
1494 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001495 break;
1496 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001497 Width = Target->getLongDoubleWidth();
1498 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001499 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001500 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001501 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1502 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001503 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001504 case BuiltinType::ObjCId:
1505 case BuiltinType::ObjCClass:
1506 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001507 Width = Target->getPointerWidth(0);
1508 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001509 break;
Guy Benyei61054192013-02-07 10:55:47 +00001510 case BuiltinType::OCLSampler:
1511 // Samplers are modeled as integers.
1512 Width = Target->getIntWidth();
1513 Align = Target->getIntAlign();
1514 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001515 case BuiltinType::OCLEvent:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001516 case BuiltinType::OCLImage1d:
1517 case BuiltinType::OCLImage1dArray:
1518 case BuiltinType::OCLImage1dBuffer:
1519 case BuiltinType::OCLImage2d:
1520 case BuiltinType::OCLImage2dArray:
1521 case BuiltinType::OCLImage3d:
1522 // Currently these types are pointers to opaque types.
1523 Width = Target->getPointerWidth(0);
1524 Align = Target->getPointerAlign(0);
1525 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001526 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001527 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001528 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001529 Width = Target->getPointerWidth(0);
1530 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001531 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001532 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001533 unsigned AS = getTargetAddressSpace(
1534 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001535 Width = Target->getPointerWidth(AS);
1536 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001537 break;
1538 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001539 case Type::LValueReference:
1540 case Type::RValueReference: {
1541 // alignof and sizeof should never enter this code path here, so we go
1542 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001543 unsigned AS = getTargetAddressSpace(
1544 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001545 Width = Target->getPointerWidth(AS);
1546 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001547 break;
1548 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001549 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001550 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001551 Width = Target->getPointerWidth(AS);
1552 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001553 break;
1554 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001555 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001556 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Reid Kleckner3a52abf2013-03-28 20:02:56 +00001557 llvm::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001558 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001559 }
Chris Lattner647fb222007-07-18 18:26:58 +00001560 case Type::Complex: {
1561 // Complex types have the same alignment as their elements, but twice the
1562 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001563 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001564 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001565 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001566 Align = EltInfo.second;
1567 break;
1568 }
John McCall8b07ec22010-05-15 11:32:37 +00001569 case Type::ObjCObject:
1570 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001571 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001572 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001573 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001574 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001575 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001576 break;
1577 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001578 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001579 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001580 const TagType *TT = cast<TagType>(T);
1581
1582 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001583 Width = 8;
1584 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001585 break;
1586 }
Mike Stump11289f42009-09-09 15:08:12 +00001587
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001588 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001589 return getTypeInfo(ET->getDecl()->getIntegerType());
1590
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001591 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001592 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001593 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001594 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001595 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001596 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001597
Chris Lattner63d2b362009-10-22 05:17:15 +00001598 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001599 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1600 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001601
Richard Smith30482bc2011-02-20 03:19:35 +00001602 case Type::Auto: {
1603 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001604 assert(!A->getDeducedType().isNull() &&
1605 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001606 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001607 }
1608
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001609 case Type::Paren:
1610 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1611
Douglas Gregoref462e62009-04-30 17:32:17 +00001612 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001613 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001614 std::pair<uint64_t, unsigned> Info
1615 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001616 // If the typedef has an aligned attribute on it, it overrides any computed
1617 // alignment we have. This violates the GCC documentation (which says that
1618 // attribute(aligned) can only round up) but matches its implementation.
1619 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1620 Align = AttrAlign;
1621 else
1622 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001623 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001624 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001625 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001626
1627 case Type::TypeOfExpr:
1628 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1629 .getTypePtr());
1630
1631 case Type::TypeOf:
1632 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1633
Anders Carlsson81df7b82009-06-24 19:06:50 +00001634 case Type::Decltype:
1635 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1636 .getTypePtr());
1637
Alexis Hunte852b102011-05-24 22:41:36 +00001638 case Type::UnaryTransform:
1639 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1640
Abramo Bagnara6150c882010-05-11 21:36:43 +00001641 case Type::Elaborated:
1642 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001643
John McCall81904512011-01-06 01:58:22 +00001644 case Type::Attributed:
1645 return getTypeInfo(
1646 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1647
Richard Smith3f1b5d02011-05-05 21:57:07 +00001648 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001649 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001650 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001651 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1652 // A type alias template specialization may refer to a typedef with the
1653 // aligned attribute on it.
1654 if (TST->isTypeAlias())
1655 return getTypeInfo(TST->getAliasedType().getTypePtr());
1656 else
1657 return getTypeInfo(getCanonicalType(T));
1658 }
1659
Eli Friedman0dfb8892011-10-06 23:00:33 +00001660 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001661 // Start with the base type information.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001662 std::pair<uint64_t, unsigned> Info
1663 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1664 Width = Info.first;
1665 Align = Info.second;
John McCalla8ec7eb2013-03-07 21:37:17 +00001666
1667 // If the size of the type doesn't exceed the platform's max
1668 // atomic promotion width, make the size and alignment more
1669 // favorable to atomic operations:
1670 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1671 // Round the size up to a power of 2.
1672 if (!llvm::isPowerOf2_64(Width))
1673 Width = llvm::NextPowerOf2(Width);
1674
1675 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001676 Align = static_cast<unsigned>(Width);
1677 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001678 }
1679
Douglas Gregoref462e62009-04-30 17:32:17 +00001680 }
Mike Stump11289f42009-09-09 15:08:12 +00001681
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001682 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001683 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001684}
1685
Ken Dyckcc56c542011-01-15 18:38:59 +00001686/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1687CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1688 return CharUnits::fromQuantity(BitSize / getCharWidth());
1689}
1690
Ken Dyckb0fcc592011-02-11 01:54:29 +00001691/// toBits - Convert a size in characters to a size in characters.
1692int64_t ASTContext::toBits(CharUnits CharSize) const {
1693 return CharSize.getQuantity() * getCharWidth();
1694}
1695
Ken Dyck8c89d592009-12-22 14:23:30 +00001696/// getTypeSizeInChars - Return the size of the specified type, in characters.
1697/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001698CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001699 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001700}
Jay Foad39c79802011-01-12 09:06:06 +00001701CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001702 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001703}
1704
Ken Dycka6046ab2010-01-26 17:25:18 +00001705/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001706/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001707CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001708 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001709}
Jay Foad39c79802011-01-12 09:06:06 +00001710CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001711 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001712}
1713
Chris Lattnera3402cd2009-01-27 18:08:34 +00001714/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1715/// type for the current target in bits. This can be different than the ABI
1716/// alignment in cases where it is beneficial for performance to overalign
1717/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001718unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001719 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001720
1721 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001722 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001723 T = CT->getElementType().getTypePtr();
1724 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001725 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1726 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001727 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1728
Chris Lattnera3402cd2009-01-27 18:08:34 +00001729 return ABIAlign;
1730}
1731
Ulrich Weigandfa806422013-05-06 16:23:57 +00001732/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1733/// to a global variable of the specified type.
1734unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1735 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1736}
1737
1738/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1739/// should be given to a global variable of the specified type.
1740CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1741 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1742}
1743
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001744/// DeepCollectObjCIvars -
1745/// This routine first collects all declared, but not synthesized, ivars in
1746/// super class and then collects all ivars, including those synthesized for
1747/// current class. This routine is used for implementation of current class
1748/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001749///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001750void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1751 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001752 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001753 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1754 DeepCollectObjCIvars(SuperClass, false, Ivars);
1755 if (!leafClass) {
1756 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1757 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001758 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001759 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001760 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001761 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001762 Iv= Iv->getNextIvar())
1763 Ivars.push_back(Iv);
1764 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001765}
1766
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001767/// CollectInheritedProtocols - Collect all protocols in current class and
1768/// those inherited by it.
1769void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001770 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001771 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001772 // We can use protocol_iterator here instead of
1773 // all_referenced_protocol_iterator since we are walking all categories.
1774 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1775 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001776 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001777 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001778 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001779 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001780 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001781 CollectInheritedProtocols(*P, Protocols);
1782 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001783 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001784
1785 // Categories of this Interface.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001786 for (ObjCInterfaceDecl::visible_categories_iterator
1787 Cat = OI->visible_categories_begin(),
1788 CatEnd = OI->visible_categories_end();
1789 Cat != CatEnd; ++Cat) {
1790 CollectInheritedProtocols(*Cat, Protocols);
1791 }
1792
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001793 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1794 while (SD) {
1795 CollectInheritedProtocols(SD, Protocols);
1796 SD = SD->getSuperClass();
1797 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001798 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001799 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001800 PE = OC->protocol_end(); P != PE; ++P) {
1801 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001802 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001803 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1804 PE = Proto->protocol_end(); P != PE; ++P)
1805 CollectInheritedProtocols(*P, Protocols);
1806 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001807 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001808 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1809 PE = OP->protocol_end(); P != PE; ++P) {
1810 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001811 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001812 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1813 PE = Proto->protocol_end(); P != PE; ++P)
1814 CollectInheritedProtocols(*P, Protocols);
1815 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001816 }
1817}
1818
Jay Foad39c79802011-01-12 09:06:06 +00001819unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001820 unsigned count = 0;
1821 // Count ivars declared in class extension.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001822 for (ObjCInterfaceDecl::known_extensions_iterator
1823 Ext = OI->known_extensions_begin(),
1824 ExtEnd = OI->known_extensions_end();
1825 Ext != ExtEnd; ++Ext) {
1826 count += Ext->ivar_size();
1827 }
1828
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001829 // Count ivar defined in this class's implementation. This
1830 // includes synthesized ivars.
1831 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001832 count += ImplDecl->ivar_size();
1833
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001834 return count;
1835}
1836
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001837bool ASTContext::isSentinelNullExpr(const Expr *E) {
1838 if (!E)
1839 return false;
1840
1841 // nullptr_t is always treated as null.
1842 if (E->getType()->isNullPtrType()) return true;
1843
1844 if (E->getType()->isAnyPointerType() &&
1845 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1846 Expr::NPC_ValueDependentIsNull))
1847 return true;
1848
1849 // Unfortunately, __null has type 'int'.
1850 if (isa<GNUNullExpr>(E)) return true;
1851
1852 return false;
1853}
1854
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001855/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1856ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1857 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1858 I = ObjCImpls.find(D);
1859 if (I != ObjCImpls.end())
1860 return cast<ObjCImplementationDecl>(I->second);
1861 return 0;
1862}
1863/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1864ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1865 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1866 I = ObjCImpls.find(D);
1867 if (I != ObjCImpls.end())
1868 return cast<ObjCCategoryImplDecl>(I->second);
1869 return 0;
1870}
1871
1872/// \brief Set the implementation of ObjCInterfaceDecl.
1873void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1874 ObjCImplementationDecl *ImplD) {
1875 assert(IFaceD && ImplD && "Passed null params");
1876 ObjCImpls[IFaceD] = ImplD;
1877}
1878/// \brief Set the implementation of ObjCCategoryDecl.
1879void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1880 ObjCCategoryImplDecl *ImplD) {
1881 assert(CatD && ImplD && "Passed null params");
1882 ObjCImpls[CatD] = ImplD;
1883}
1884
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001885const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1886 const NamedDecl *ND) const {
1887 if (const ObjCInterfaceDecl *ID =
1888 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001889 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001890 if (const ObjCCategoryDecl *CD =
1891 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001892 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001893 if (const ObjCImplDecl *IMD =
1894 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001895 return IMD->getClassInterface();
1896
1897 return 0;
1898}
1899
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001900/// \brief Get the copy initialization expression of VarDecl,or NULL if
1901/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001902Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001903 assert(VD && "Passed null params");
1904 assert(VD->hasAttr<BlocksAttr>() &&
1905 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001906 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001907 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001908 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1909}
1910
1911/// \brief Set the copy inialization expression of a block var decl.
1912void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1913 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001914 assert(VD->hasAttr<BlocksAttr>() &&
1915 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001916 BlockVarCopyInits[VD] = Init;
1917}
1918
John McCallbcd03502009-12-07 02:54:59 +00001919TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001920 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001921 if (!DataSize)
1922 DataSize = TypeLoc::getFullDataSizeForType(T);
1923 else
1924 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001925 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001926
John McCallbcd03502009-12-07 02:54:59 +00001927 TypeSourceInfo *TInfo =
1928 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1929 new (TInfo) TypeSourceInfo(T);
1930 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001931}
1932
John McCallbcd03502009-12-07 02:54:59 +00001933TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001934 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001935 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001936 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001937 return DI;
1938}
1939
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001940const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001941ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001942 return getObjCLayout(D, 0);
1943}
1944
1945const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001946ASTContext::getASTObjCImplementationLayout(
1947 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001948 return getObjCLayout(D->getClassInterface(), D);
1949}
1950
Chris Lattner983a8bb2007-07-13 22:13:22 +00001951//===----------------------------------------------------------------------===//
1952// Type creation/memoization methods
1953//===----------------------------------------------------------------------===//
1954
Jay Foad39c79802011-01-12 09:06:06 +00001955QualType
John McCall33ddac02011-01-19 10:06:00 +00001956ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1957 unsigned fastQuals = quals.getFastQualifiers();
1958 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001959
1960 // Check if we've already instantiated this type.
1961 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001962 ExtQuals::Profile(ID, baseType, quals);
1963 void *insertPos = 0;
1964 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1965 assert(eq->getQualifiers() == quals);
1966 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001967 }
1968
John McCall33ddac02011-01-19 10:06:00 +00001969 // If the base type is not canonical, make the appropriate canonical type.
1970 QualType canon;
1971 if (!baseType->isCanonicalUnqualified()) {
1972 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001973 canonSplit.Quals.addConsistentQualifiers(quals);
1974 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001975
1976 // Re-find the insert position.
1977 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1978 }
1979
1980 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1981 ExtQualNodes.InsertNode(eq, insertPos);
1982 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001983}
1984
Jay Foad39c79802011-01-12 09:06:06 +00001985QualType
1986ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001987 QualType CanT = getCanonicalType(T);
1988 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001989 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001990
John McCall8ccfcb52009-09-24 19:53:00 +00001991 // If we are composing extended qualifiers together, merge together
1992 // into one ExtQuals node.
1993 QualifierCollector Quals;
1994 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001995
John McCall8ccfcb52009-09-24 19:53:00 +00001996 // If this type already has an address space specified, it cannot get
1997 // another one.
1998 assert(!Quals.hasAddressSpace() &&
1999 "Type cannot be in multiple addr spaces!");
2000 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002001
John McCall8ccfcb52009-09-24 19:53:00 +00002002 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002003}
2004
Chris Lattnerd60183d2009-02-18 22:53:11 +00002005QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002006 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002007 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002008 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002009 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002010
John McCall53fa7142010-12-24 02:08:15 +00002011 if (const PointerType *ptr = T->getAs<PointerType>()) {
2012 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002013 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002014 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2015 return getPointerType(ResultType);
2016 }
2017 }
Mike Stump11289f42009-09-09 15:08:12 +00002018
John McCall8ccfcb52009-09-24 19:53:00 +00002019 // If we are composing extended qualifiers together, merge together
2020 // into one ExtQuals node.
2021 QualifierCollector Quals;
2022 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002023
John McCall8ccfcb52009-09-24 19:53:00 +00002024 // If this type already has an ObjCGC specified, it cannot get
2025 // another one.
2026 assert(!Quals.hasObjCGCAttr() &&
2027 "Type cannot have multiple ObjCGCs!");
2028 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002029
John McCall8ccfcb52009-09-24 19:53:00 +00002030 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002031}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002032
John McCall4f5019e2010-12-19 02:44:49 +00002033const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2034 FunctionType::ExtInfo Info) {
2035 if (T->getExtInfo() == Info)
2036 return T;
2037
2038 QualType Result;
2039 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2040 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
2041 } else {
2042 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2043 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2044 EPI.ExtInfo = Info;
Jordan Rose5c382722013-03-08 21:51:21 +00002045 Result = getFunctionType(FPT->getResultType(),
2046 ArrayRef<QualType>(FPT->arg_type_begin(),
2047 FPT->getNumArgs()),
2048 EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002049 }
2050
2051 return cast<FunctionType>(Result.getTypePtr());
2052}
2053
Richard Smith2a7d4812013-05-04 07:00:32 +00002054void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2055 QualType ResultType) {
2056 // FIXME: Need to inform serialization code about this!
2057 for (FD = FD->getMostRecentDecl(); FD; FD = FD->getPreviousDecl()) {
2058 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2059 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2060 FD->setType(getFunctionType(ResultType, FPT->getArgTypes(), EPI));
2061 }
2062}
2063
Chris Lattnerc6395932007-06-22 20:56:16 +00002064/// getComplexType - Return the uniqued reference to the type for a complex
2065/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002066QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002067 // Unique pointers, to guarantee there is only one pointer of a particular
2068 // structure.
2069 llvm::FoldingSetNodeID ID;
2070 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002071
Chris Lattnerc6395932007-06-22 20:56:16 +00002072 void *InsertPos = 0;
2073 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2074 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002075
Chris Lattnerc6395932007-06-22 20:56:16 +00002076 // If the pointee type isn't canonical, this won't be a canonical type either,
2077 // so fill in the canonical type field.
2078 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002079 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002080 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002081
Chris Lattnerc6395932007-06-22 20:56:16 +00002082 // Get the new insert position for the node we care about.
2083 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002084 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002085 }
John McCall90d1c2d2009-09-24 23:30:46 +00002086 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002087 Types.push_back(New);
2088 ComplexTypes.InsertNode(New, InsertPos);
2089 return QualType(New, 0);
2090}
2091
Chris Lattner970e54e2006-11-12 00:37:36 +00002092/// getPointerType - Return the uniqued reference to the type for a pointer to
2093/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002094QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002095 // Unique pointers, to guarantee there is only one pointer of a particular
2096 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002097 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002098 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002099
Chris Lattner67521df2007-01-27 01:29:36 +00002100 void *InsertPos = 0;
2101 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002102 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002103
Chris Lattner7ccecb92006-11-12 08:50:50 +00002104 // If the pointee type isn't canonical, this won't be a canonical type either,
2105 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002106 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002107 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002108 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002109
Bob Wilsonc8541f22013-03-15 17:12:43 +00002110 // Get the new insert position for the node we care about.
2111 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2112 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2113 }
John McCall90d1c2d2009-09-24 23:30:46 +00002114 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002115 Types.push_back(New);
2116 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002117 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002118}
2119
Mike Stump11289f42009-09-09 15:08:12 +00002120/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002121/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002122QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002123 assert(T->isFunctionType() && "block of function types only");
2124 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002125 // structure.
2126 llvm::FoldingSetNodeID ID;
2127 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002128
Steve Naroffec33ed92008-08-27 16:04:49 +00002129 void *InsertPos = 0;
2130 if (BlockPointerType *PT =
2131 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2132 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002133
2134 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002135 // type either so fill in the canonical type field.
2136 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002137 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002138 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002139
Steve Naroffec33ed92008-08-27 16:04:49 +00002140 // Get the new insert position for the node we care about.
2141 BlockPointerType *NewIP =
2142 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002143 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002144 }
John McCall90d1c2d2009-09-24 23:30:46 +00002145 BlockPointerType *New
2146 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002147 Types.push_back(New);
2148 BlockPointerTypes.InsertNode(New, InsertPos);
2149 return QualType(New, 0);
2150}
2151
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002152/// getLValueReferenceType - Return the uniqued reference to the type for an
2153/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002154QualType
2155ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002156 assert(getCanonicalType(T) != OverloadTy &&
2157 "Unresolved overloaded function type");
2158
Bill Wendling3708c182007-05-27 10:15:43 +00002159 // Unique pointers, to guarantee there is only one pointer of a particular
2160 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002161 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002162 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002163
2164 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002165 if (LValueReferenceType *RT =
2166 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002167 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002168
John McCallfc93cf92009-10-22 22:37:11 +00002169 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2170
Bill Wendling3708c182007-05-27 10:15:43 +00002171 // If the referencee type isn't canonical, this won't be a canonical type
2172 // either, so fill in the canonical type field.
2173 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002174 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2175 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2176 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002177
Bill Wendling3708c182007-05-27 10:15:43 +00002178 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002179 LValueReferenceType *NewIP =
2180 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002181 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002182 }
2183
John McCall90d1c2d2009-09-24 23:30:46 +00002184 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002185 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2186 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002187 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002188 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002189
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002190 return QualType(New, 0);
2191}
2192
2193/// getRValueReferenceType - Return the uniqued reference to the type for an
2194/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002195QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002196 // Unique pointers, to guarantee there is only one pointer of a particular
2197 // structure.
2198 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002199 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002200
2201 void *InsertPos = 0;
2202 if (RValueReferenceType *RT =
2203 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2204 return QualType(RT, 0);
2205
John McCallfc93cf92009-10-22 22:37:11 +00002206 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2207
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002208 // If the referencee type isn't canonical, this won't be a canonical type
2209 // either, so fill in the canonical type field.
2210 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002211 if (InnerRef || !T.isCanonical()) {
2212 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2213 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002214
2215 // Get the new insert position for the node we care about.
2216 RValueReferenceType *NewIP =
2217 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002218 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002219 }
2220
John McCall90d1c2d2009-09-24 23:30:46 +00002221 RValueReferenceType *New
2222 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002223 Types.push_back(New);
2224 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002225 return QualType(New, 0);
2226}
2227
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002228/// getMemberPointerType - Return the uniqued reference to the type for a
2229/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002230QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002231 // Unique pointers, to guarantee there is only one pointer of a particular
2232 // structure.
2233 llvm::FoldingSetNodeID ID;
2234 MemberPointerType::Profile(ID, T, Cls);
2235
2236 void *InsertPos = 0;
2237 if (MemberPointerType *PT =
2238 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2239 return QualType(PT, 0);
2240
2241 // If the pointee or class type isn't canonical, this won't be a canonical
2242 // type either, so fill in the canonical type field.
2243 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002244 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002245 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2246
2247 // Get the new insert position for the node we care about.
2248 MemberPointerType *NewIP =
2249 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002250 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002251 }
John McCall90d1c2d2009-09-24 23:30:46 +00002252 MemberPointerType *New
2253 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002254 Types.push_back(New);
2255 MemberPointerTypes.InsertNode(New, InsertPos);
2256 return QualType(New, 0);
2257}
2258
Mike Stump11289f42009-09-09 15:08:12 +00002259/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002260/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002261QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002262 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002263 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002264 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002265 assert((EltTy->isDependentType() ||
2266 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002267 "Constant array of VLAs is illegal!");
2268
Chris Lattnere2df3f92009-05-13 04:12:56 +00002269 // Convert the array size into a canonical width matching the pointer size for
2270 // the target.
2271 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002272 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002273 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002274
Chris Lattner23b7eb62007-06-15 23:05:46 +00002275 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002276 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002277
Chris Lattner36f8e652007-01-27 08:31:04 +00002278 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002279 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002280 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002281 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002282
John McCall33ddac02011-01-19 10:06:00 +00002283 // If the element type isn't canonical or has qualifiers, this won't
2284 // be a canonical type either, so fill in the canonical type field.
2285 QualType Canon;
2286 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2287 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002288 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002289 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002290 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002291
Chris Lattner36f8e652007-01-27 08:31:04 +00002292 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002293 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002294 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002295 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002296 }
Mike Stump11289f42009-09-09 15:08:12 +00002297
John McCall90d1c2d2009-09-24 23:30:46 +00002298 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002299 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002300 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002301 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002302 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002303}
2304
John McCall06549462011-01-18 08:40:38 +00002305/// getVariableArrayDecayedType - Turns the given type, which may be
2306/// variably-modified, into the corresponding type with all the known
2307/// sizes replaced with [*].
2308QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2309 // Vastly most common case.
2310 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002311
John McCall06549462011-01-18 08:40:38 +00002312 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002313
John McCall06549462011-01-18 08:40:38 +00002314 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002315 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002316 switch (ty->getTypeClass()) {
2317#define TYPE(Class, Base)
2318#define ABSTRACT_TYPE(Class, Base)
2319#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2320#include "clang/AST/TypeNodes.def"
2321 llvm_unreachable("didn't desugar past all non-canonical types?");
2322
2323 // These types should never be variably-modified.
2324 case Type::Builtin:
2325 case Type::Complex:
2326 case Type::Vector:
2327 case Type::ExtVector:
2328 case Type::DependentSizedExtVector:
2329 case Type::ObjCObject:
2330 case Type::ObjCInterface:
2331 case Type::ObjCObjectPointer:
2332 case Type::Record:
2333 case Type::Enum:
2334 case Type::UnresolvedUsing:
2335 case Type::TypeOfExpr:
2336 case Type::TypeOf:
2337 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002338 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002339 case Type::DependentName:
2340 case Type::InjectedClassName:
2341 case Type::TemplateSpecialization:
2342 case Type::DependentTemplateSpecialization:
2343 case Type::TemplateTypeParm:
2344 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002345 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002346 case Type::PackExpansion:
2347 llvm_unreachable("type should never be variably-modified");
2348
2349 // These types can be variably-modified but should never need to
2350 // further decay.
2351 case Type::FunctionNoProto:
2352 case Type::FunctionProto:
2353 case Type::BlockPointer:
2354 case Type::MemberPointer:
2355 return type;
2356
2357 // These types can be variably-modified. All these modifications
2358 // preserve structure except as noted by comments.
2359 // TODO: if we ever care about optimizing VLAs, there are no-op
2360 // optimizations available here.
2361 case Type::Pointer:
2362 result = getPointerType(getVariableArrayDecayedType(
2363 cast<PointerType>(ty)->getPointeeType()));
2364 break;
2365
2366 case Type::LValueReference: {
2367 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2368 result = getLValueReferenceType(
2369 getVariableArrayDecayedType(lv->getPointeeType()),
2370 lv->isSpelledAsLValue());
2371 break;
2372 }
2373
2374 case Type::RValueReference: {
2375 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2376 result = getRValueReferenceType(
2377 getVariableArrayDecayedType(lv->getPointeeType()));
2378 break;
2379 }
2380
Eli Friedman0dfb8892011-10-06 23:00:33 +00002381 case Type::Atomic: {
2382 const AtomicType *at = cast<AtomicType>(ty);
2383 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2384 break;
2385 }
2386
John McCall06549462011-01-18 08:40:38 +00002387 case Type::ConstantArray: {
2388 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2389 result = getConstantArrayType(
2390 getVariableArrayDecayedType(cat->getElementType()),
2391 cat->getSize(),
2392 cat->getSizeModifier(),
2393 cat->getIndexTypeCVRQualifiers());
2394 break;
2395 }
2396
2397 case Type::DependentSizedArray: {
2398 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2399 result = getDependentSizedArrayType(
2400 getVariableArrayDecayedType(dat->getElementType()),
2401 dat->getSizeExpr(),
2402 dat->getSizeModifier(),
2403 dat->getIndexTypeCVRQualifiers(),
2404 dat->getBracketsRange());
2405 break;
2406 }
2407
2408 // Turn incomplete types into [*] types.
2409 case Type::IncompleteArray: {
2410 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2411 result = getVariableArrayType(
2412 getVariableArrayDecayedType(iat->getElementType()),
2413 /*size*/ 0,
2414 ArrayType::Normal,
2415 iat->getIndexTypeCVRQualifiers(),
2416 SourceRange());
2417 break;
2418 }
2419
2420 // Turn VLA types into [*] types.
2421 case Type::VariableArray: {
2422 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2423 result = getVariableArrayType(
2424 getVariableArrayDecayedType(vat->getElementType()),
2425 /*size*/ 0,
2426 ArrayType::Star,
2427 vat->getIndexTypeCVRQualifiers(),
2428 vat->getBracketsRange());
2429 break;
2430 }
2431 }
2432
2433 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002434 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002435}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002436
Steve Naroffcadebd02007-08-30 18:14:25 +00002437/// getVariableArrayType - Returns a non-unique reference to the type for a
2438/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002439QualType ASTContext::getVariableArrayType(QualType EltTy,
2440 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002441 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002442 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002443 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002444 // Since we don't unique expressions, it isn't possible to unique VLA's
2445 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002446 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002447
John McCall33ddac02011-01-19 10:06:00 +00002448 // Be sure to pull qualifiers off the element type.
2449 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2450 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002451 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002452 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002453 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002454 }
2455
John McCall90d1c2d2009-09-24 23:30:46 +00002456 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002457 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002458
2459 VariableArrayTypes.push_back(New);
2460 Types.push_back(New);
2461 return QualType(New, 0);
2462}
2463
Douglas Gregor4619e432008-12-05 23:32:09 +00002464/// getDependentSizedArrayType - Returns a non-unique reference to
2465/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002466/// type.
John McCall33ddac02011-01-19 10:06:00 +00002467QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2468 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002469 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002470 unsigned elementTypeQuals,
2471 SourceRange brackets) const {
2472 assert((!numElements || numElements->isTypeDependent() ||
2473 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002474 "Size must be type- or value-dependent!");
2475
John McCall33ddac02011-01-19 10:06:00 +00002476 // Dependently-sized array types that do not have a specified number
2477 // of elements will have their sizes deduced from a dependent
2478 // initializer. We do no canonicalization here at all, which is okay
2479 // because they can't be used in most locations.
2480 if (!numElements) {
2481 DependentSizedArrayType *newType
2482 = new (*this, TypeAlignment)
2483 DependentSizedArrayType(*this, elementType, QualType(),
2484 numElements, ASM, elementTypeQuals,
2485 brackets);
2486 Types.push_back(newType);
2487 return QualType(newType, 0);
2488 }
2489
2490 // Otherwise, we actually build a new type every time, but we
2491 // also build a canonical type.
2492
2493 SplitQualType canonElementType = getCanonicalType(elementType).split();
2494
2495 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002496 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002497 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002498 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002499 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002500
John McCall33ddac02011-01-19 10:06:00 +00002501 // Look for an existing type with these properties.
2502 DependentSizedArrayType *canonTy =
2503 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002504
John McCall33ddac02011-01-19 10:06:00 +00002505 // If we don't have one, build one.
2506 if (!canonTy) {
2507 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002508 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002509 QualType(), numElements, ASM, elementTypeQuals,
2510 brackets);
2511 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2512 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002513 }
2514
John McCall33ddac02011-01-19 10:06:00 +00002515 // Apply qualifiers from the element type to the array.
2516 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002517 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002518
John McCall33ddac02011-01-19 10:06:00 +00002519 // If we didn't need extra canonicalization for the element type,
2520 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002521 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002522 return canon;
2523
2524 // Otherwise, we need to build a type which follows the spelling
2525 // of the element type.
2526 DependentSizedArrayType *sugaredType
2527 = new (*this, TypeAlignment)
2528 DependentSizedArrayType(*this, elementType, canon, numElements,
2529 ASM, elementTypeQuals, brackets);
2530 Types.push_back(sugaredType);
2531 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002532}
2533
John McCall33ddac02011-01-19 10:06:00 +00002534QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002535 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002536 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002537 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002538 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002539
John McCall33ddac02011-01-19 10:06:00 +00002540 void *insertPos = 0;
2541 if (IncompleteArrayType *iat =
2542 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2543 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002544
2545 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002546 // either, so fill in the canonical type field. We also have to pull
2547 // qualifiers off the element type.
2548 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002549
John McCall33ddac02011-01-19 10:06:00 +00002550 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2551 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002552 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002553 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002554 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002555
2556 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002557 IncompleteArrayType *existing =
2558 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2559 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002560 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002561
John McCall33ddac02011-01-19 10:06:00 +00002562 IncompleteArrayType *newType = new (*this, TypeAlignment)
2563 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002564
John McCall33ddac02011-01-19 10:06:00 +00002565 IncompleteArrayTypes.InsertNode(newType, insertPos);
2566 Types.push_back(newType);
2567 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002568}
2569
Steve Naroff91fcddb2007-07-18 18:00:27 +00002570/// getVectorType - Return the unique reference to a vector type of
2571/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002572QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002573 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002574 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002575
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002576 // Check if we've already instantiated a vector of this type.
2577 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002578 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002579
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002580 void *InsertPos = 0;
2581 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2582 return QualType(VTP, 0);
2583
2584 // If the element type isn't canonical, this won't be a canonical type either,
2585 // so fill in the canonical type field.
2586 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002587 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002588 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002589
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002590 // Get the new insert position for the node we care about.
2591 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002592 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002593 }
John McCall90d1c2d2009-09-24 23:30:46 +00002594 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002595 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002596 VectorTypes.InsertNode(New, InsertPos);
2597 Types.push_back(New);
2598 return QualType(New, 0);
2599}
2600
Nate Begemance4d7fc2008-04-18 23:10:10 +00002601/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002602/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002603QualType
2604ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002605 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002606
Steve Naroff91fcddb2007-07-18 18:00:27 +00002607 // Check if we've already instantiated a vector of this type.
2608 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002609 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002610 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002611 void *InsertPos = 0;
2612 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2613 return QualType(VTP, 0);
2614
2615 // If the element type isn't canonical, this won't be a canonical type either,
2616 // so fill in the canonical type field.
2617 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002618 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002619 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002620
Steve Naroff91fcddb2007-07-18 18:00:27 +00002621 // Get the new insert position for the node we care about.
2622 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002623 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002624 }
John McCall90d1c2d2009-09-24 23:30:46 +00002625 ExtVectorType *New = new (*this, TypeAlignment)
2626 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002627 VectorTypes.InsertNode(New, InsertPos);
2628 Types.push_back(New);
2629 return QualType(New, 0);
2630}
2631
Jay Foad39c79802011-01-12 09:06:06 +00002632QualType
2633ASTContext::getDependentSizedExtVectorType(QualType vecType,
2634 Expr *SizeExpr,
2635 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002636 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002637 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002638 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002639
Douglas Gregor352169a2009-07-31 03:54:25 +00002640 void *InsertPos = 0;
2641 DependentSizedExtVectorType *Canon
2642 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2643 DependentSizedExtVectorType *New;
2644 if (Canon) {
2645 // We already have a canonical version of this array type; use it as
2646 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002647 New = new (*this, TypeAlignment)
2648 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2649 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002650 } else {
2651 QualType CanonVecTy = getCanonicalType(vecType);
2652 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002653 New = new (*this, TypeAlignment)
2654 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2655 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002656
2657 DependentSizedExtVectorType *CanonCheck
2658 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2659 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2660 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002661 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2662 } else {
2663 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2664 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002665 New = new (*this, TypeAlignment)
2666 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002667 }
2668 }
Mike Stump11289f42009-09-09 15:08:12 +00002669
Douglas Gregor758a8692009-06-17 21:51:59 +00002670 Types.push_back(New);
2671 return QualType(New, 0);
2672}
2673
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002674/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002675///
Jay Foad39c79802011-01-12 09:06:06 +00002676QualType
2677ASTContext::getFunctionNoProtoType(QualType ResultTy,
2678 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002679 const CallingConv DefaultCC = Info.getCC();
2680 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2681 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002682 // Unique functions, to guarantee there is only one function of a particular
2683 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002684 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002685 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002686
Chris Lattner47955de2007-01-27 08:37:20 +00002687 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002688 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002689 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002690 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002691
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002692 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002693 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002694 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002695 Canonical =
2696 getFunctionNoProtoType(getCanonicalType(ResultTy),
2697 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002698
Chris Lattner47955de2007-01-27 08:37:20 +00002699 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002700 FunctionNoProtoType *NewIP =
2701 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002702 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002703 }
Mike Stump11289f42009-09-09 15:08:12 +00002704
Roman Divacky65b88cd2011-03-01 17:40:53 +00002705 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002706 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002707 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002708 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002709 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002710 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002711}
2712
Douglas Gregorcd780372013-01-17 23:36:45 +00002713/// \brief Determine whether \p T is canonical as the result type of a function.
2714static bool isCanonicalResultType(QualType T) {
2715 return T.isCanonical() &&
2716 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2717 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2718}
2719
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002720/// getFunctionType - Return a normal function type with a typed argument
2721/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002722QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002723ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002724 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002725 size_t NumArgs = ArgArray.size();
2726
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002727 // Unique functions, to guarantee there is only one function of a particular
2728 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002729 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002730 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2731 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002732
2733 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002734 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002735 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002736 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002737
2738 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002739 bool isCanonical =
Douglas Gregorcd780372013-01-17 23:36:45 +00002740 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002741 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002742 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002743 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002744 isCanonical = false;
2745
Roman Divacky65b88cd2011-03-01 17:40:53 +00002746 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2747 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2748 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002749
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002750 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002751 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002752 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002753 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002754 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002755 CanonicalArgs.reserve(NumArgs);
2756 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002757 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002758
John McCalldb40c7f2010-12-14 08:05:40 +00002759 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002760 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002761 CanonicalEPI.ExceptionSpecType = EST_None;
2762 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002763 CanonicalEPI.ExtInfo
2764 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2765
Douglas Gregorcd780372013-01-17 23:36:45 +00002766 // Result types do not have ARC lifetime qualifiers.
2767 QualType CanResultTy = getCanonicalType(ResultTy);
2768 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2769 Qualifiers Qs = CanResultTy.getQualifiers();
2770 Qs.removeObjCLifetime();
2771 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2772 }
2773
Jordan Rose5c382722013-03-08 21:51:21 +00002774 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002775
Chris Lattnerfd4de792007-01-27 01:15:32 +00002776 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002777 FunctionProtoType *NewIP =
2778 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002779 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002780 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002781
John McCall31168b02011-06-15 23:02:42 +00002782 // FunctionProtoType objects are allocated with extra bytes after
2783 // them for three variable size arrays at the end:
2784 // - parameter types
2785 // - exception types
2786 // - consumed-arguments flags
2787 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002788 // expression, or information used to resolve the exception
2789 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002790 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002791 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002792 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002793 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002794 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002795 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002796 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002797 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002798 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2799 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002800 }
John McCall31168b02011-06-15 23:02:42 +00002801 if (EPI.ConsumedArguments)
2802 Size += NumArgs * sizeof(bool);
2803
John McCalldb40c7f2010-12-14 08:05:40 +00002804 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002805 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2806 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Jordan Rose5c382722013-03-08 21:51:21 +00002807 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002808 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002809 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002810 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002811}
Chris Lattneref51c202006-11-10 07:17:23 +00002812
John McCalle78aac42010-03-10 03:28:59 +00002813#ifndef NDEBUG
2814static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2815 if (!isa<CXXRecordDecl>(D)) return false;
2816 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2817 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2818 return true;
2819 if (RD->getDescribedClassTemplate() &&
2820 !isa<ClassTemplateSpecializationDecl>(RD))
2821 return true;
2822 return false;
2823}
2824#endif
2825
2826/// getInjectedClassNameType - Return the unique reference to the
2827/// injected class name type for the specified templated declaration.
2828QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002829 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002830 assert(NeedsInjectedClassNameType(Decl));
2831 if (Decl->TypeForDecl) {
2832 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002833 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002834 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2835 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2836 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2837 } else {
John McCall424cec92011-01-19 06:33:43 +00002838 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002839 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002840 Decl->TypeForDecl = newType;
2841 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002842 }
2843 return QualType(Decl->TypeForDecl, 0);
2844}
2845
Douglas Gregor83a586e2008-04-13 21:07:44 +00002846/// getTypeDeclType - Return the unique reference to the type for the
2847/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002848QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002849 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002850 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002851
Richard Smithdda56e42011-04-15 14:24:37 +00002852 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002853 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002854
John McCall96f0b5f2010-03-10 06:48:02 +00002855 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2856 "Template type parameter types are always available.");
2857
John McCall81e38502010-02-16 03:57:14 +00002858 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002859 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002860 "struct/union has previous declaration");
2861 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002862 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002863 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002864 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002865 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002866 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002867 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002868 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002869 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2870 Decl->TypeForDecl = newType;
2871 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002872 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002873 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002874
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002875 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002876}
2877
Chris Lattner32d920b2007-01-26 02:01:53 +00002878/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002879/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002880QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002881ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2882 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002883 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002884
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002885 if (Canonical.isNull())
2886 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002887 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002888 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002889 Decl->TypeForDecl = newType;
2890 Types.push_back(newType);
2891 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002892}
2893
Jay Foad39c79802011-01-12 09:06:06 +00002894QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002895 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2896
Douglas Gregorec9fd132012-01-14 16:38:05 +00002897 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002898 if (PrevDecl->TypeForDecl)
2899 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2900
John McCall424cec92011-01-19 06:33:43 +00002901 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2902 Decl->TypeForDecl = newType;
2903 Types.push_back(newType);
2904 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002905}
2906
Jay Foad39c79802011-01-12 09:06:06 +00002907QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002908 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2909
Douglas Gregorec9fd132012-01-14 16:38:05 +00002910 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002911 if (PrevDecl->TypeForDecl)
2912 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2913
John McCall424cec92011-01-19 06:33:43 +00002914 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2915 Decl->TypeForDecl = newType;
2916 Types.push_back(newType);
2917 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002918}
2919
John McCall81904512011-01-06 01:58:22 +00002920QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2921 QualType modifiedType,
2922 QualType equivalentType) {
2923 llvm::FoldingSetNodeID id;
2924 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2925
2926 void *insertPos = 0;
2927 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2928 if (type) return QualType(type, 0);
2929
2930 QualType canon = getCanonicalType(equivalentType);
2931 type = new (*this, TypeAlignment)
2932 AttributedType(canon, attrKind, modifiedType, equivalentType);
2933
2934 Types.push_back(type);
2935 AttributedTypes.InsertNode(type, insertPos);
2936
2937 return QualType(type, 0);
2938}
2939
2940
John McCallcebee162009-10-18 09:09:24 +00002941/// \brief Retrieve a substitution-result type.
2942QualType
2943ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002944 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002945 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002946 && "replacement types must always be canonical");
2947
2948 llvm::FoldingSetNodeID ID;
2949 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2950 void *InsertPos = 0;
2951 SubstTemplateTypeParmType *SubstParm
2952 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2953
2954 if (!SubstParm) {
2955 SubstParm = new (*this, TypeAlignment)
2956 SubstTemplateTypeParmType(Parm, Replacement);
2957 Types.push_back(SubstParm);
2958 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2959 }
2960
2961 return QualType(SubstParm, 0);
2962}
2963
Douglas Gregorada4b792011-01-14 02:55:32 +00002964/// \brief Retrieve a
2965QualType ASTContext::getSubstTemplateTypeParmPackType(
2966 const TemplateTypeParmType *Parm,
2967 const TemplateArgument &ArgPack) {
2968#ifndef NDEBUG
2969 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2970 PEnd = ArgPack.pack_end();
2971 P != PEnd; ++P) {
2972 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2973 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2974 }
2975#endif
2976
2977 llvm::FoldingSetNodeID ID;
2978 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2979 void *InsertPos = 0;
2980 if (SubstTemplateTypeParmPackType *SubstParm
2981 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2982 return QualType(SubstParm, 0);
2983
2984 QualType Canon;
2985 if (!Parm->isCanonicalUnqualified()) {
2986 Canon = getCanonicalType(QualType(Parm, 0));
2987 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2988 ArgPack);
2989 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2990 }
2991
2992 SubstTemplateTypeParmPackType *SubstParm
2993 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2994 ArgPack);
2995 Types.push_back(SubstParm);
2996 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2997 return QualType(SubstParm, 0);
2998}
2999
Douglas Gregoreff93e02009-02-05 23:33:38 +00003000/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003001/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003002/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003003QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003004 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003005 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003006 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003007 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003008 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003009 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003010 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3011
3012 if (TypeParm)
3013 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003014
Chandler Carruth08836322011-05-01 00:51:33 +00003015 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003016 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003017 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003018
3019 TemplateTypeParmType *TypeCheck
3020 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3021 assert(!TypeCheck && "Template type parameter canonical type broken");
3022 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003023 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003024 TypeParm = new (*this, TypeAlignment)
3025 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003026
3027 Types.push_back(TypeParm);
3028 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3029
3030 return QualType(TypeParm, 0);
3031}
3032
John McCalle78aac42010-03-10 03:28:59 +00003033TypeSourceInfo *
3034ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3035 SourceLocation NameLoc,
3036 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003037 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003038 assert(!Name.getAsDependentTemplateName() &&
3039 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003040 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003041
3042 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003043 TemplateSpecializationTypeLoc TL =
3044 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003045 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003046 TL.setTemplateNameLoc(NameLoc);
3047 TL.setLAngleLoc(Args.getLAngleLoc());
3048 TL.setRAngleLoc(Args.getRAngleLoc());
3049 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3050 TL.setArgLocInfo(i, Args[i].getLocInfo());
3051 return DI;
3052}
3053
Mike Stump11289f42009-09-09 15:08:12 +00003054QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003055ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003056 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003057 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003058 assert(!Template.getAsDependentTemplateName() &&
3059 "No dependent template names here!");
3060
John McCall6b51f282009-11-23 01:53:49 +00003061 unsigned NumArgs = Args.size();
3062
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003063 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003064 ArgVec.reserve(NumArgs);
3065 for (unsigned i = 0; i != NumArgs; ++i)
3066 ArgVec.push_back(Args[i].getArgument());
3067
John McCall2408e322010-04-27 00:57:59 +00003068 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003069 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003070}
3071
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003072#ifndef NDEBUG
3073static bool hasAnyPackExpansions(const TemplateArgument *Args,
3074 unsigned NumArgs) {
3075 for (unsigned I = 0; I != NumArgs; ++I)
3076 if (Args[I].isPackExpansion())
3077 return true;
3078
3079 return true;
3080}
3081#endif
3082
John McCall0ad16662009-10-29 08:12:44 +00003083QualType
3084ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003085 const TemplateArgument *Args,
3086 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003087 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003088 assert(!Template.getAsDependentTemplateName() &&
3089 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003090 // Look through qualified template names.
3091 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3092 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003093
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003094 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003095 Template.getAsTemplateDecl() &&
3096 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003097 QualType CanonType;
3098 if (!Underlying.isNull())
3099 CanonType = getCanonicalType(Underlying);
3100 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003101 // We can get here with an alias template when the specialization contains
3102 // a pack expansion that does not match up with a parameter pack.
3103 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3104 "Caller must compute aliased type");
3105 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003106 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3107 NumArgs);
3108 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003109
Douglas Gregora8e02e72009-07-28 23:00:59 +00003110 // Allocate the (non-canonical) template specialization type, but don't
3111 // try to unique it: these types typically have location information that
3112 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003113 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3114 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003115 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003116 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003117 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003118 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3119 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003120
Douglas Gregor8bf42052009-02-09 18:46:07 +00003121 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003122 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003123}
3124
Mike Stump11289f42009-09-09 15:08:12 +00003125QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003126ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3127 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003128 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003129 assert(!Template.getAsDependentTemplateName() &&
3130 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003131
Douglas Gregore29139c2011-03-03 17:04:51 +00003132 // Look through qualified template names.
3133 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3134 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003135
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003136 // Build the canonical template specialization type.
3137 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003138 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003139 CanonArgs.reserve(NumArgs);
3140 for (unsigned I = 0; I != NumArgs; ++I)
3141 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3142
3143 // Determine whether this canonical template specialization type already
3144 // exists.
3145 llvm::FoldingSetNodeID ID;
3146 TemplateSpecializationType::Profile(ID, CanonTemplate,
3147 CanonArgs.data(), NumArgs, *this);
3148
3149 void *InsertPos = 0;
3150 TemplateSpecializationType *Spec
3151 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3152
3153 if (!Spec) {
3154 // Allocate a new canonical template specialization type.
3155 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3156 sizeof(TemplateArgument) * NumArgs),
3157 TypeAlignment);
3158 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3159 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003160 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003161 Types.push_back(Spec);
3162 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3163 }
3164
3165 assert(Spec->isDependentType() &&
3166 "Non-dependent template-id type must have a canonical type");
3167 return QualType(Spec, 0);
3168}
3169
3170QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003171ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3172 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003173 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003174 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003175 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003176
3177 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003178 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003179 if (T)
3180 return QualType(T, 0);
3181
Douglas Gregorc42075a2010-02-04 18:10:26 +00003182 QualType Canon = NamedType;
3183 if (!Canon.isCanonical()) {
3184 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003185 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3186 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003187 (void)CheckT;
3188 }
3189
Abramo Bagnara6150c882010-05-11 21:36:43 +00003190 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003191 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003192 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003193 return QualType(T, 0);
3194}
3195
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003196QualType
Jay Foad39c79802011-01-12 09:06:06 +00003197ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003198 llvm::FoldingSetNodeID ID;
3199 ParenType::Profile(ID, InnerType);
3200
3201 void *InsertPos = 0;
3202 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3203 if (T)
3204 return QualType(T, 0);
3205
3206 QualType Canon = InnerType;
3207 if (!Canon.isCanonical()) {
3208 Canon = getCanonicalType(InnerType);
3209 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3210 assert(!CheckT && "Paren canonical type broken");
3211 (void)CheckT;
3212 }
3213
3214 T = new (*this) ParenType(InnerType, Canon);
3215 Types.push_back(T);
3216 ParenTypes.InsertNode(T, InsertPos);
3217 return QualType(T, 0);
3218}
3219
Douglas Gregor02085352010-03-31 20:19:30 +00003220QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3221 NestedNameSpecifier *NNS,
3222 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003223 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003224 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3225
3226 if (Canon.isNull()) {
3227 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003228 ElaboratedTypeKeyword CanonKeyword = Keyword;
3229 if (Keyword == ETK_None)
3230 CanonKeyword = ETK_Typename;
3231
3232 if (CanonNNS != NNS || CanonKeyword != Keyword)
3233 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003234 }
3235
3236 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003237 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003238
3239 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003240 DependentNameType *T
3241 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003242 if (T)
3243 return QualType(T, 0);
3244
Douglas Gregor02085352010-03-31 20:19:30 +00003245 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003246 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003247 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003248 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003249}
3250
Mike Stump11289f42009-09-09 15:08:12 +00003251QualType
John McCallc392f372010-06-11 00:33:02 +00003252ASTContext::getDependentTemplateSpecializationType(
3253 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003254 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003255 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003256 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003257 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003258 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003259 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3260 ArgCopy.push_back(Args[I].getArgument());
3261 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3262 ArgCopy.size(),
3263 ArgCopy.data());
3264}
3265
3266QualType
3267ASTContext::getDependentTemplateSpecializationType(
3268 ElaboratedTypeKeyword Keyword,
3269 NestedNameSpecifier *NNS,
3270 const IdentifierInfo *Name,
3271 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003272 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003273 assert((!NNS || NNS->isDependent()) &&
3274 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003275
Douglas Gregorc42075a2010-02-04 18:10:26 +00003276 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003277 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3278 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003279
3280 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00003281 DependentTemplateSpecializationType *T
3282 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003283 if (T)
3284 return QualType(T, 0);
3285
John McCallc392f372010-06-11 00:33:02 +00003286 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003287
John McCallc392f372010-06-11 00:33:02 +00003288 ElaboratedTypeKeyword CanonKeyword = Keyword;
3289 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3290
3291 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003292 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003293 for (unsigned I = 0; I != NumArgs; ++I) {
3294 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3295 if (!CanonArgs[I].structurallyEquals(Args[I]))
3296 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003297 }
3298
John McCallc392f372010-06-11 00:33:02 +00003299 QualType Canon;
3300 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3301 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3302 Name, NumArgs,
3303 CanonArgs.data());
3304
3305 // Find the insert position again.
3306 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3307 }
3308
3309 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3310 sizeof(TemplateArgument) * NumArgs),
3311 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003312 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003313 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003314 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003315 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003316 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003317}
3318
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003319QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003320 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003321 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003322 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003323
3324 assert(Pattern->containsUnexpandedParameterPack() &&
3325 "Pack expansions must expand one or more parameter packs");
3326 void *InsertPos = 0;
3327 PackExpansionType *T
3328 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3329 if (T)
3330 return QualType(T, 0);
3331
3332 QualType Canon;
3333 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003334 Canon = getCanonicalType(Pattern);
3335 // The canonical type might not contain an unexpanded parameter pack, if it
3336 // contains an alias template specialization which ignores one of its
3337 // parameters.
3338 if (Canon->containsUnexpandedParameterPack()) {
3339 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003340
Richard Smith68eea502012-07-16 00:20:35 +00003341 // Find the insert position again, in case we inserted an element into
3342 // PackExpansionTypes and invalidated our insert position.
3343 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3344 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003345 }
3346
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003347 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003348 Types.push_back(T);
3349 PackExpansionTypes.InsertNode(T, InsertPos);
3350 return QualType(T, 0);
3351}
3352
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003353/// CmpProtocolNames - Comparison predicate for sorting protocols
3354/// alphabetically.
3355static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3356 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003357 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003358}
3359
John McCall8b07ec22010-05-15 11:32:37 +00003360static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003361 unsigned NumProtocols) {
3362 if (NumProtocols == 0) return true;
3363
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003364 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3365 return false;
3366
John McCallfc93cf92009-10-22 22:37:11 +00003367 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003368 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3369 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003370 return false;
3371 return true;
3372}
3373
3374static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003375 unsigned &NumProtocols) {
3376 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003377
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003378 // Sort protocols, keyed by name.
3379 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3380
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003381 // Canonicalize.
3382 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3383 Protocols[I] = Protocols[I]->getCanonicalDecl();
3384
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003385 // Remove duplicates.
3386 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3387 NumProtocols = ProtocolsEnd-Protocols;
3388}
3389
John McCall8b07ec22010-05-15 11:32:37 +00003390QualType ASTContext::getObjCObjectType(QualType BaseType,
3391 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003392 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003393 // If the base type is an interface and there aren't any protocols
3394 // to add, then the interface type will do just fine.
3395 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3396 return BaseType;
3397
3398 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003399 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003400 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003401 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003402 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3403 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003404
John McCall8b07ec22010-05-15 11:32:37 +00003405 // Build the canonical type, which has the canonical base type and
3406 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003407 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003408 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3409 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3410 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003411 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003412 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003413 unsigned UniqueCount = NumProtocols;
3414
John McCallfc93cf92009-10-22 22:37:11 +00003415 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003416 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3417 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003418 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003419 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3420 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003421 }
3422
3423 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003424 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3425 }
3426
3427 unsigned Size = sizeof(ObjCObjectTypeImpl);
3428 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3429 void *Mem = Allocate(Size, TypeAlignment);
3430 ObjCObjectTypeImpl *T =
3431 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3432
3433 Types.push_back(T);
3434 ObjCObjectTypes.InsertNode(T, InsertPos);
3435 return QualType(T, 0);
3436}
3437
3438/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3439/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003440QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003441 llvm::FoldingSetNodeID ID;
3442 ObjCObjectPointerType::Profile(ID, ObjectT);
3443
3444 void *InsertPos = 0;
3445 if (ObjCObjectPointerType *QT =
3446 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3447 return QualType(QT, 0);
3448
3449 // Find the canonical object type.
3450 QualType Canonical;
3451 if (!ObjectT.isCanonical()) {
3452 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3453
3454 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003455 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3456 }
3457
Douglas Gregorf85bee62010-02-08 22:59:26 +00003458 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003459 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3460 ObjCObjectPointerType *QType =
3461 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003462
Steve Narofffb4330f2009-06-17 22:40:22 +00003463 Types.push_back(QType);
3464 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003465 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003466}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003467
Douglas Gregor1c283312010-08-11 12:19:30 +00003468/// getObjCInterfaceType - Return the unique reference to the type for the
3469/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003470QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3471 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003472 if (Decl->TypeForDecl)
3473 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003474
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003475 if (PrevDecl) {
3476 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3477 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3478 return QualType(PrevDecl->TypeForDecl, 0);
3479 }
3480
Douglas Gregor7671e532011-12-16 16:34:57 +00003481 // Prefer the definition, if there is one.
3482 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3483 Decl = Def;
3484
Douglas Gregor1c283312010-08-11 12:19:30 +00003485 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3486 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3487 Decl->TypeForDecl = T;
3488 Types.push_back(T);
3489 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003490}
3491
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003492/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3493/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003494/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003495/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003496/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003497QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003498 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003499 if (tofExpr->isTypeDependent()) {
3500 llvm::FoldingSetNodeID ID;
3501 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003502
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003503 void *InsertPos = 0;
3504 DependentTypeOfExprType *Canon
3505 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3506 if (Canon) {
3507 // We already have a "canonical" version of an identical, dependent
3508 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003509 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003510 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003511 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003512 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003513 Canon
3514 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003515 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3516 toe = Canon;
3517 }
3518 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003519 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003520 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003521 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003522 Types.push_back(toe);
3523 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003524}
3525
Steve Naroffa773cd52007-08-01 18:02:17 +00003526/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3527/// TypeOfType AST's. The only motivation to unique these nodes would be
3528/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003529/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003530/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003531QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003532 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003533 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003534 Types.push_back(tot);
3535 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003536}
3537
Anders Carlssonad6bd352009-06-24 21:24:56 +00003538
Anders Carlsson81df7b82009-06-24 19:06:50 +00003539/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3540/// DecltypeType AST's. The only motivation to unique these nodes would be
3541/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003542/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003543/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003544QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003545 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003546
3547 // C++0x [temp.type]p2:
3548 // If an expression e involves a template parameter, decltype(e) denotes a
3549 // unique dependent type. Two such decltype-specifiers refer to the same
3550 // type only if their expressions are equivalent (14.5.6.1).
3551 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003552 llvm::FoldingSetNodeID ID;
3553 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003554
Douglas Gregora21f6c32009-07-30 23:36:40 +00003555 void *InsertPos = 0;
3556 DependentDecltypeType *Canon
3557 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3558 if (Canon) {
3559 // We already have a "canonical" version of an equivalent, dependent
3560 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003561 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003562 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003563 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003564 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003565 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003566 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3567 dt = Canon;
3568 }
3569 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003570 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3571 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003572 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003573 Types.push_back(dt);
3574 return QualType(dt, 0);
3575}
3576
Alexis Hunte852b102011-05-24 22:41:36 +00003577/// getUnaryTransformationType - We don't unique these, since the memory
3578/// savings are minimal and these are rare.
3579QualType ASTContext::getUnaryTransformType(QualType BaseType,
3580 QualType UnderlyingType,
3581 UnaryTransformType::UTTKind Kind)
3582 const {
3583 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003584 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3585 Kind,
3586 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003587 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003588 Types.push_back(Ty);
3589 return QualType(Ty, 0);
3590}
3591
Richard Smith2a7d4812013-05-04 07:00:32 +00003592/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3593/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3594/// canonical deduced-but-dependent 'auto' type.
3595QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Richard Smith27d807c2013-04-30 13:56:41 +00003596 bool IsDependent) const {
Richard Smith2a7d4812013-05-04 07:00:32 +00003597 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
3598 return getAutoDeductType();
3599
3600 // Look in the folding set for an existing type.
Richard Smithb2bc2e62011-02-21 20:05:19 +00003601 void *InsertPos = 0;
Richard Smith2a7d4812013-05-04 07:00:32 +00003602 llvm::FoldingSetNodeID ID;
3603 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
3604 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3605 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003606
Richard Smith74aeef52013-04-26 16:15:35 +00003607 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003608 IsDecltypeAuto,
3609 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003610 Types.push_back(AT);
3611 if (InsertPos)
3612 AutoTypes.InsertNode(AT, InsertPos);
3613 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003614}
3615
Eli Friedman0dfb8892011-10-06 23:00:33 +00003616/// getAtomicType - Return the uniqued reference to the atomic type for
3617/// the given value type.
3618QualType ASTContext::getAtomicType(QualType T) const {
3619 // Unique pointers, to guarantee there is only one pointer of a particular
3620 // structure.
3621 llvm::FoldingSetNodeID ID;
3622 AtomicType::Profile(ID, T);
3623
3624 void *InsertPos = 0;
3625 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3626 return QualType(AT, 0);
3627
3628 // If the atomic value type isn't canonical, this won't be a canonical type
3629 // either, so fill in the canonical type field.
3630 QualType Canonical;
3631 if (!T.isCanonical()) {
3632 Canonical = getAtomicType(getCanonicalType(T));
3633
3634 // Get the new insert position for the node we care about.
3635 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3636 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3637 }
3638 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3639 Types.push_back(New);
3640 AtomicTypes.InsertNode(New, InsertPos);
3641 return QualType(New, 0);
3642}
3643
Richard Smith02e85f32011-04-14 22:09:26 +00003644/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3645QualType ASTContext::getAutoDeductType() const {
3646 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00003647 AutoDeductTy = QualType(
3648 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
3649 /*dependent*/false),
3650 0);
Richard Smith02e85f32011-04-14 22:09:26 +00003651 return AutoDeductTy;
3652}
3653
3654/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3655QualType ASTContext::getAutoRRefDeductType() const {
3656 if (AutoRRefDeductTy.isNull())
3657 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3658 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3659 return AutoRRefDeductTy;
3660}
3661
Chris Lattnerfb072462007-01-23 05:45:31 +00003662/// getTagDeclType - Return the unique reference to the type for the
3663/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003664QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003665 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003666 // FIXME: What is the design on getTagDeclType when it requires casting
3667 // away const? mutable?
3668 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003669}
3670
Mike Stump11289f42009-09-09 15:08:12 +00003671/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3672/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3673/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003674CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003675 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003676}
Chris Lattnerfb072462007-01-23 05:45:31 +00003677
Hans Wennborg27541db2011-10-27 08:29:09 +00003678/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3679CanQualType ASTContext::getIntMaxType() const {
3680 return getFromTargetType(Target->getIntMaxType());
3681}
3682
3683/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3684CanQualType ASTContext::getUIntMaxType() const {
3685 return getFromTargetType(Target->getUIntMaxType());
3686}
3687
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003688/// getSignedWCharType - Return the type of "signed wchar_t".
3689/// Used when in C++, as a GCC extension.
3690QualType ASTContext::getSignedWCharType() const {
3691 // FIXME: derive from "Target" ?
3692 return WCharTy;
3693}
3694
3695/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3696/// Used when in C++, as a GCC extension.
3697QualType ASTContext::getUnsignedWCharType() const {
3698 // FIXME: derive from "Target" ?
3699 return UnsignedIntTy;
3700}
3701
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00003702QualType ASTContext::getIntPtrType() const {
3703 return getFromTargetType(Target->getIntPtrType());
3704}
3705
3706QualType ASTContext::getUIntPtrType() const {
3707 return getCorrespondingUnsignedType(getIntPtrType());
3708}
3709
Hans Wennborg27541db2011-10-27 08:29:09 +00003710/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003711/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3712QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003713 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003714}
3715
Eli Friedman4e91899e2012-11-27 02:58:24 +00003716/// \brief Return the unique type for "pid_t" defined in
3717/// <sys/types.h>. We need this to compute the correct type for vfork().
3718QualType ASTContext::getProcessIDType() const {
3719 return getFromTargetType(Target->getProcessIDType());
3720}
3721
Chris Lattnera21ad802008-04-02 05:18:44 +00003722//===----------------------------------------------------------------------===//
3723// Type Operators
3724//===----------------------------------------------------------------------===//
3725
Jay Foad39c79802011-01-12 09:06:06 +00003726CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003727 // Push qualifiers into arrays, and then discard any remaining
3728 // qualifiers.
3729 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003730 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003731 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003732 QualType Result;
3733 if (isa<ArrayType>(Ty)) {
3734 Result = getArrayDecayedType(QualType(Ty,0));
3735 } else if (isa<FunctionType>(Ty)) {
3736 Result = getPointerType(QualType(Ty, 0));
3737 } else {
3738 Result = QualType(Ty, 0);
3739 }
3740
3741 return CanQualType::CreateUnsafe(Result);
3742}
3743
John McCall6c9dd522011-01-18 07:41:22 +00003744QualType ASTContext::getUnqualifiedArrayType(QualType type,
3745 Qualifiers &quals) {
3746 SplitQualType splitType = type.getSplitUnqualifiedType();
3747
3748 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3749 // the unqualified desugared type and then drops it on the floor.
3750 // We then have to strip that sugar back off with
3751 // getUnqualifiedDesugaredType(), which is silly.
3752 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003753 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003754
3755 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003756 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003757 quals = splitType.Quals;
3758 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003759 }
3760
John McCall6c9dd522011-01-18 07:41:22 +00003761 // Otherwise, recurse on the array's element type.
3762 QualType elementType = AT->getElementType();
3763 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3764
3765 // If that didn't change the element type, AT has no qualifiers, so we
3766 // can just use the results in splitType.
3767 if (elementType == unqualElementType) {
3768 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003769 quals = splitType.Quals;
3770 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003771 }
3772
3773 // Otherwise, add in the qualifiers from the outermost type, then
3774 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003775 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003776
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003777 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003778 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003779 CAT->getSizeModifier(), 0);
3780 }
3781
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003782 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003783 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003784 }
3785
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003786 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003787 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003788 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003789 VAT->getSizeModifier(),
3790 VAT->getIndexTypeCVRQualifiers(),
3791 VAT->getBracketsRange());
3792 }
3793
3794 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003795 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003796 DSAT->getSizeModifier(), 0,
3797 SourceRange());
3798}
3799
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003800/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3801/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3802/// they point to and return true. If T1 and T2 aren't pointer types
3803/// or pointer-to-member types, or if they are not similar at this
3804/// level, returns false and leaves T1 and T2 unchanged. Top-level
3805/// qualifiers on T1 and T2 are ignored. This function will typically
3806/// be called in a loop that successively "unwraps" pointer and
3807/// pointer-to-member types to compare them at each level.
3808bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3809 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3810 *T2PtrType = T2->getAs<PointerType>();
3811 if (T1PtrType && T2PtrType) {
3812 T1 = T1PtrType->getPointeeType();
3813 T2 = T2PtrType->getPointeeType();
3814 return true;
3815 }
3816
3817 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3818 *T2MPType = T2->getAs<MemberPointerType>();
3819 if (T1MPType && T2MPType &&
3820 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3821 QualType(T2MPType->getClass(), 0))) {
3822 T1 = T1MPType->getPointeeType();
3823 T2 = T2MPType->getPointeeType();
3824 return true;
3825 }
3826
David Blaikiebbafb8a2012-03-11 07:00:24 +00003827 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003828 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3829 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3830 if (T1OPType && T2OPType) {
3831 T1 = T1OPType->getPointeeType();
3832 T2 = T2OPType->getPointeeType();
3833 return true;
3834 }
3835 }
3836
3837 // FIXME: Block pointers, too?
3838
3839 return false;
3840}
3841
Jay Foad39c79802011-01-12 09:06:06 +00003842DeclarationNameInfo
3843ASTContext::getNameForTemplate(TemplateName Name,
3844 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003845 switch (Name.getKind()) {
3846 case TemplateName::QualifiedTemplate:
3847 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003848 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003849 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3850 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003851
John McCalld9dfe3a2011-06-30 08:33:18 +00003852 case TemplateName::OverloadedTemplate: {
3853 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3854 // DNInfo work in progress: CHECKME: what about DNLoc?
3855 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3856 }
3857
3858 case TemplateName::DependentTemplate: {
3859 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003860 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003861 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003862 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3863 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003864 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003865 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3866 // DNInfo work in progress: FIXME: source locations?
3867 DeclarationNameLoc DNLoc;
3868 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3869 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3870 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003871 }
3872 }
3873
John McCalld9dfe3a2011-06-30 08:33:18 +00003874 case TemplateName::SubstTemplateTemplateParm: {
3875 SubstTemplateTemplateParmStorage *subst
3876 = Name.getAsSubstTemplateTemplateParm();
3877 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3878 NameLoc);
3879 }
3880
3881 case TemplateName::SubstTemplateTemplateParmPack: {
3882 SubstTemplateTemplateParmPackStorage *subst
3883 = Name.getAsSubstTemplateTemplateParmPack();
3884 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3885 NameLoc);
3886 }
3887 }
3888
3889 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003890}
3891
Jay Foad39c79802011-01-12 09:06:06 +00003892TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003893 switch (Name.getKind()) {
3894 case TemplateName::QualifiedTemplate:
3895 case TemplateName::Template: {
3896 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003897 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003898 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003899 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3900
3901 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003902 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003903 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003904
John McCalld9dfe3a2011-06-30 08:33:18 +00003905 case TemplateName::OverloadedTemplate:
3906 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003907
John McCalld9dfe3a2011-06-30 08:33:18 +00003908 case TemplateName::DependentTemplate: {
3909 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3910 assert(DTN && "Non-dependent template names must refer to template decls.");
3911 return DTN->CanonicalTemplateName;
3912 }
3913
3914 case TemplateName::SubstTemplateTemplateParm: {
3915 SubstTemplateTemplateParmStorage *subst
3916 = Name.getAsSubstTemplateTemplateParm();
3917 return getCanonicalTemplateName(subst->getReplacement());
3918 }
3919
3920 case TemplateName::SubstTemplateTemplateParmPack: {
3921 SubstTemplateTemplateParmPackStorage *subst
3922 = Name.getAsSubstTemplateTemplateParmPack();
3923 TemplateTemplateParmDecl *canonParameter
3924 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3925 TemplateArgument canonArgPack
3926 = getCanonicalTemplateArgument(subst->getArgumentPack());
3927 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3928 }
3929 }
3930
3931 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003932}
3933
Douglas Gregoradee3e32009-11-11 23:06:43 +00003934bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3935 X = getCanonicalTemplateName(X);
3936 Y = getCanonicalTemplateName(Y);
3937 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3938}
3939
Mike Stump11289f42009-09-09 15:08:12 +00003940TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003941ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003942 switch (Arg.getKind()) {
3943 case TemplateArgument::Null:
3944 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003945
Douglas Gregora8e02e72009-07-28 23:00:59 +00003946 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003947 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003948
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003949 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00003950 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
3951 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003952 }
Mike Stump11289f42009-09-09 15:08:12 +00003953
Eli Friedmanb826a002012-09-26 02:36:12 +00003954 case TemplateArgument::NullPtr:
3955 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
3956 /*isNullPtr*/true);
3957
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003958 case TemplateArgument::Template:
3959 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003960
3961 case TemplateArgument::TemplateExpansion:
3962 return TemplateArgument(getCanonicalTemplateName(
3963 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003964 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003965
Douglas Gregora8e02e72009-07-28 23:00:59 +00003966 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003967 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003968
Douglas Gregora8e02e72009-07-28 23:00:59 +00003969 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003970 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003971
Douglas Gregora8e02e72009-07-28 23:00:59 +00003972 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003973 if (Arg.pack_size() == 0)
3974 return Arg;
3975
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003976 TemplateArgument *CanonArgs
3977 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003978 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003979 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003980 AEnd = Arg.pack_end();
3981 A != AEnd; (void)++A, ++Idx)
3982 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003983
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003984 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003985 }
3986 }
3987
3988 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003989 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003990}
3991
Douglas Gregor333489b2009-03-27 23:10:48 +00003992NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003993ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003994 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003995 return 0;
3996
3997 switch (NNS->getKind()) {
3998 case NestedNameSpecifier::Identifier:
3999 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004000 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004001 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4002 NNS->getAsIdentifier());
4003
4004 case NestedNameSpecifier::Namespace:
4005 // A namespace is canonical; build a nested-name-specifier with
4006 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004007 return NestedNameSpecifier::Create(*this, 0,
4008 NNS->getAsNamespace()->getOriginalNamespace());
4009
4010 case NestedNameSpecifier::NamespaceAlias:
4011 // A namespace is canonical; build a nested-name-specifier with
4012 // this namespace and no prefix.
4013 return NestedNameSpecifier::Create(*this, 0,
4014 NNS->getAsNamespaceAlias()->getNamespace()
4015 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004016
4017 case NestedNameSpecifier::TypeSpec:
4018 case NestedNameSpecifier::TypeSpecWithTemplate: {
4019 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004020
4021 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4022 // break it apart into its prefix and identifier, then reconsititute those
4023 // as the canonical nested-name-specifier. This is required to canonicalize
4024 // a dependent nested-name-specifier involving typedefs of dependent-name
4025 // types, e.g.,
4026 // typedef typename T::type T1;
4027 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004028 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4029 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004030 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004031
Eli Friedman5358a0a2012-03-03 04:09:56 +00004032 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4033 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4034 // first place?
John McCall33ddac02011-01-19 10:06:00 +00004035 return NestedNameSpecifier::Create(*this, 0, false,
4036 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004037 }
4038
4039 case NestedNameSpecifier::Global:
4040 // The global specifier is canonical and unique.
4041 return NNS;
4042 }
4043
David Blaikie8a40f702012-01-17 06:56:22 +00004044 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004045}
4046
Chris Lattner7adf0762008-08-04 07:31:14 +00004047
Jay Foad39c79802011-01-12 09:06:06 +00004048const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004049 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004050 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004051 // Handle the common positive case fast.
4052 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4053 return AT;
4054 }
Mike Stump11289f42009-09-09 15:08:12 +00004055
John McCall8ccfcb52009-09-24 19:53:00 +00004056 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004057 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00004058 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004059
John McCall8ccfcb52009-09-24 19:53:00 +00004060 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004061 // implements C99 6.7.3p8: "If the specification of an array type includes
4062 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004063
Chris Lattner7adf0762008-08-04 07:31:14 +00004064 // If we get here, we either have type qualifiers on the type, or we have
4065 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004066 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004067
John McCall33ddac02011-01-19 10:06:00 +00004068 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004069 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004070
Chris Lattner7adf0762008-08-04 07:31:14 +00004071 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004072 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00004073 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004074 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004075
Chris Lattner7adf0762008-08-04 07:31:14 +00004076 // Otherwise, we have an array and we have qualifiers on it. Push the
4077 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004078 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004079
Chris Lattner7adf0762008-08-04 07:31:14 +00004080 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4081 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4082 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004083 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004084 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4085 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4086 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004087 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004088
Mike Stump11289f42009-09-09 15:08:12 +00004089 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004090 = dyn_cast<DependentSizedArrayType>(ATy))
4091 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004092 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004093 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004094 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004095 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004096 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004097
Chris Lattner7adf0762008-08-04 07:31:14 +00004098 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004099 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004100 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004101 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004102 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004103 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004104}
4105
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004106QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004107 // C99 6.7.5.3p7:
4108 // A declaration of a parameter as "array of type" shall be
4109 // adjusted to "qualified pointer to type", where the type
4110 // qualifiers (if any) are those specified within the [ and ] of
4111 // the array type derivation.
4112 if (T->isArrayType())
4113 return getArrayDecayedType(T);
4114
4115 // C99 6.7.5.3p8:
4116 // A declaration of a parameter as "function returning type"
4117 // shall be adjusted to "pointer to function returning type", as
4118 // in 6.3.2.1.
4119 if (T->isFunctionType())
4120 return getPointerType(T);
4121
4122 return T;
4123}
4124
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004125QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004126 T = getVariableArrayDecayedType(T);
4127 T = getAdjustedParameterType(T);
4128 return T.getUnqualifiedType();
4129}
4130
Chris Lattnera21ad802008-04-02 05:18:44 +00004131/// getArrayDecayedType - Return the properly qualified result of decaying the
4132/// specified array type to a pointer. This operation is non-trivial when
4133/// handling typedefs etc. The canonical type of "T" must be an array type,
4134/// this returns a pointer to a properly qualified element of the array.
4135///
4136/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004137QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004138 // Get the element type with 'getAsArrayType' so that we don't lose any
4139 // typedefs in the element type of the array. This also handles propagation
4140 // of type qualifiers from the array type into the element type if present
4141 // (C99 6.7.3p8).
4142 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4143 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004144
Chris Lattner7adf0762008-08-04 07:31:14 +00004145 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004146
4147 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004148 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004149}
4150
John McCall33ddac02011-01-19 10:06:00 +00004151QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4152 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004153}
4154
John McCall33ddac02011-01-19 10:06:00 +00004155QualType ASTContext::getBaseElementType(QualType type) const {
4156 Qualifiers qs;
4157 while (true) {
4158 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004159 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004160 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004161
John McCall33ddac02011-01-19 10:06:00 +00004162 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004163 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004164 }
Mike Stump11289f42009-09-09 15:08:12 +00004165
John McCall33ddac02011-01-19 10:06:00 +00004166 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004167}
4168
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004169/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004170uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004171ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4172 uint64_t ElementCount = 1;
4173 do {
4174 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004175 CA = dyn_cast_or_null<ConstantArrayType>(
4176 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004177 } while (CA);
4178 return ElementCount;
4179}
4180
Steve Naroff0af91202007-04-27 21:51:21 +00004181/// getFloatingRank - Return a relative rank for floating point types.
4182/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004183static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004184 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004185 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004186
John McCall9dd450b2009-09-21 23:43:11 +00004187 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4188 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004189 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004190 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004191 case BuiltinType::Float: return FloatRank;
4192 case BuiltinType::Double: return DoubleRank;
4193 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004194 }
4195}
4196
Mike Stump11289f42009-09-09 15:08:12 +00004197/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4198/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004199/// 'typeDomain' is a real floating point or complex type.
4200/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004201QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4202 QualType Domain) const {
4203 FloatingRank EltRank = getFloatingRank(Size);
4204 if (Domain->isComplexType()) {
4205 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004206 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004207 case FloatRank: return FloatComplexTy;
4208 case DoubleRank: return DoubleComplexTy;
4209 case LongDoubleRank: return LongDoubleComplexTy;
4210 }
Steve Naroff0af91202007-04-27 21:51:21 +00004211 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004212
4213 assert(Domain->isRealFloatingType() && "Unknown domain!");
4214 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004215 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004216 case FloatRank: return FloatTy;
4217 case DoubleRank: return DoubleTy;
4218 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004219 }
David Blaikief47fa302012-01-17 02:30:50 +00004220 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004221}
4222
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004223/// getFloatingTypeOrder - Compare the rank of the two specified floating
4224/// point types, ignoring the domain of the type (i.e. 'double' ==
4225/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004226/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004227int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004228 FloatingRank LHSR = getFloatingRank(LHS);
4229 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004230
Chris Lattnerb90739d2008-04-06 23:38:49 +00004231 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004232 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004233 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004234 return 1;
4235 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004236}
4237
Chris Lattner76a00cf2008-04-06 22:59:24 +00004238/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4239/// routine will assert if passed a built-in type that isn't an integer or enum,
4240/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004241unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004242 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004243
Chris Lattner76a00cf2008-04-06 22:59:24 +00004244 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004245 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004246 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004247 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004248 case BuiltinType::Char_S:
4249 case BuiltinType::Char_U:
4250 case BuiltinType::SChar:
4251 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004252 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004253 case BuiltinType::Short:
4254 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004255 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004256 case BuiltinType::Int:
4257 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004258 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004259 case BuiltinType::Long:
4260 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004261 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004262 case BuiltinType::LongLong:
4263 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004264 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004265 case BuiltinType::Int128:
4266 case BuiltinType::UInt128:
4267 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004268 }
4269}
4270
Eli Friedman629ffb92009-08-20 04:21:42 +00004271/// \brief Whether this is a promotable bitfield reference according
4272/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4273///
4274/// \returns the type this bit-field will promote to, or NULL if no
4275/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004276QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004277 if (E->isTypeDependent() || E->isValueDependent())
4278 return QualType();
4279
Eli Friedman629ffb92009-08-20 04:21:42 +00004280 FieldDecl *Field = E->getBitField();
4281 if (!Field)
4282 return QualType();
4283
4284 QualType FT = Field->getType();
4285
Richard Smithcaf33902011-10-10 18:28:20 +00004286 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004287 uint64_t IntSize = getTypeSize(IntTy);
4288 // GCC extension compatibility: if the bit-field size is less than or equal
4289 // to the size of int, it gets promoted no matter what its type is.
4290 // For instance, unsigned long bf : 4 gets promoted to signed int.
4291 if (BitWidth < IntSize)
4292 return IntTy;
4293
4294 if (BitWidth == IntSize)
4295 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4296
4297 // Types bigger than int are not subject to promotions, and therefore act
4298 // like the base type.
4299 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4300 // is ridiculous.
4301 return QualType();
4302}
4303
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004304/// getPromotedIntegerType - Returns the type that Promotable will
4305/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4306/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004307QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004308 assert(!Promotable.isNull());
4309 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004310 if (const EnumType *ET = Promotable->getAs<EnumType>())
4311 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004312
4313 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4314 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4315 // (3.9.1) can be converted to a prvalue of the first of the following
4316 // types that can represent all the values of its underlying type:
4317 // int, unsigned int, long int, unsigned long int, long long int, or
4318 // unsigned long long int [...]
4319 // FIXME: Is there some better way to compute this?
4320 if (BT->getKind() == BuiltinType::WChar_S ||
4321 BT->getKind() == BuiltinType::WChar_U ||
4322 BT->getKind() == BuiltinType::Char16 ||
4323 BT->getKind() == BuiltinType::Char32) {
4324 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4325 uint64_t FromSize = getTypeSize(BT);
4326 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4327 LongLongTy, UnsignedLongLongTy };
4328 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4329 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4330 if (FromSize < ToSize ||
4331 (FromSize == ToSize &&
4332 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4333 return PromoteTypes[Idx];
4334 }
4335 llvm_unreachable("char type should fit into long long");
4336 }
4337 }
4338
4339 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004340 if (Promotable->isSignedIntegerType())
4341 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004342 uint64_t PromotableSize = getIntWidth(Promotable);
4343 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004344 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4345 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4346}
4347
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004348/// \brief Recurses in pointer/array types until it finds an objc retainable
4349/// type and returns its ownership.
4350Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4351 while (!T.isNull()) {
4352 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4353 return T.getObjCLifetime();
4354 if (T->isArrayType())
4355 T = getBaseElementType(T);
4356 else if (const PointerType *PT = T->getAs<PointerType>())
4357 T = PT->getPointeeType();
4358 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004359 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004360 else
4361 break;
4362 }
4363
4364 return Qualifiers::OCL_None;
4365}
4366
Mike Stump11289f42009-09-09 15:08:12 +00004367/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004368/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004369/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004370int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004371 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4372 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004373 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004374
Chris Lattner76a00cf2008-04-06 22:59:24 +00004375 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4376 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004377
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004378 unsigned LHSRank = getIntegerRank(LHSC);
4379 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004380
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004381 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4382 if (LHSRank == RHSRank) return 0;
4383 return LHSRank > RHSRank ? 1 : -1;
4384 }
Mike Stump11289f42009-09-09 15:08:12 +00004385
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004386 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4387 if (LHSUnsigned) {
4388 // If the unsigned [LHS] type is larger, return it.
4389 if (LHSRank >= RHSRank)
4390 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004391
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004392 // If the signed type can represent all values of the unsigned type, it
4393 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004394 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004395 return -1;
4396 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004397
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004398 // If the unsigned [RHS] type is larger, return it.
4399 if (RHSRank >= LHSRank)
4400 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004401
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004402 // If the signed type can represent all values of the unsigned type, it
4403 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004404 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004405 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004406}
Anders Carlsson98f07902007-08-17 05:31:46 +00004407
Anders Carlsson6d417272009-11-14 21:45:58 +00004408static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004409CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4410 DeclContext *DC, IdentifierInfo *Id) {
4411 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004412 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004413 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004414 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004415 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004416}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004417
Mike Stump11289f42009-09-09 15:08:12 +00004418// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004419QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004420 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00004421 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004422 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004423 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00004424 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004425
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004426 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004427
Anders Carlsson98f07902007-08-17 05:31:46 +00004428 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004429 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004430 // int flags;
4431 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004432 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004433 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004434 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004435 FieldTypes[3] = LongTy;
4436
Anders Carlsson98f07902007-08-17 05:31:46 +00004437 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004438 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004439 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004440 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004441 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004442 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004443 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004444 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004445 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004446 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004447 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004448 }
4449
Douglas Gregord5058122010-02-11 01:19:42 +00004450 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004451 }
Mike Stump11289f42009-09-09 15:08:12 +00004452
Anders Carlsson98f07902007-08-17 05:31:46 +00004453 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004454}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004455
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004456QualType ASTContext::getObjCSuperType() const {
4457 if (ObjCSuperType.isNull()) {
4458 RecordDecl *ObjCSuperTypeDecl =
4459 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4460 TUDecl->addDecl(ObjCSuperTypeDecl);
4461 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4462 }
4463 return ObjCSuperType;
4464}
4465
Douglas Gregor512b0772009-04-23 22:29:11 +00004466void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004467 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004468 assert(Rec && "Invalid CFConstantStringType");
4469 CFConstantStringTypeDecl = Rec->getDecl();
4470}
4471
Jay Foad39c79802011-01-12 09:06:06 +00004472QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004473 if (BlockDescriptorType)
4474 return getTagDeclType(BlockDescriptorType);
4475
4476 RecordDecl *T;
4477 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004478 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004479 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00004480 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004481
4482 QualType FieldTypes[] = {
4483 UnsignedLongTy,
4484 UnsignedLongTy,
4485 };
4486
4487 const char *FieldNames[] = {
4488 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004489 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004490 };
4491
4492 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004493 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00004494 SourceLocation(),
4495 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004496 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00004497 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004498 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004499 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004500 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00004501 T->addDecl(Field);
4502 }
4503
Douglas Gregord5058122010-02-11 01:19:42 +00004504 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004505
4506 BlockDescriptorType = T;
4507
4508 return getTagDeclType(BlockDescriptorType);
4509}
4510
Jay Foad39c79802011-01-12 09:06:06 +00004511QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004512 if (BlockDescriptorExtendedType)
4513 return getTagDeclType(BlockDescriptorExtendedType);
4514
4515 RecordDecl *T;
4516 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004517 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004518 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00004519 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004520
4521 QualType FieldTypes[] = {
4522 UnsignedLongTy,
4523 UnsignedLongTy,
4524 getPointerType(VoidPtrTy),
4525 getPointerType(VoidPtrTy)
4526 };
4527
4528 const char *FieldNames[] = {
4529 "reserved",
4530 "Size",
4531 "CopyFuncPtr",
4532 "DestroyFuncPtr"
4533 };
4534
4535 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004536 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004537 SourceLocation(),
4538 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004539 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004540 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004541 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004542 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004543 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004544 T->addDecl(Field);
4545 }
4546
Douglas Gregord5058122010-02-11 01:19:42 +00004547 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004548
4549 BlockDescriptorExtendedType = T;
4550
4551 return getTagDeclType(BlockDescriptorExtendedType);
4552}
4553
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004554/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4555/// requires copy/dispose. Note that this must match the logic
4556/// in buildByrefHelpers.
4557bool ASTContext::BlockRequiresCopying(QualType Ty,
4558 const VarDecl *D) {
4559 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4560 const Expr *copyExpr = getBlockVarCopyInits(D);
4561 if (!copyExpr && record->hasTrivialDestructor()) return false;
4562
Mike Stump94967902009-10-21 18:16:27 +00004563 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004564 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004565
4566 if (!Ty->isObjCRetainableType()) return false;
4567
4568 Qualifiers qs = Ty.getQualifiers();
4569
4570 // If we have lifetime, that dominates.
4571 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4572 assert(getLangOpts().ObjCAutoRefCount);
4573
4574 switch (lifetime) {
4575 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4576
4577 // These are just bits as far as the runtime is concerned.
4578 case Qualifiers::OCL_ExplicitNone:
4579 case Qualifiers::OCL_Autoreleasing:
4580 return false;
4581
4582 // Tell the runtime that this is ARC __weak, called by the
4583 // byref routines.
4584 case Qualifiers::OCL_Weak:
4585 // ARC __strong __block variables need to be retained.
4586 case Qualifiers::OCL_Strong:
4587 return true;
4588 }
4589 llvm_unreachable("fell out of lifetime switch!");
4590 }
4591 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4592 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004593}
4594
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004595bool ASTContext::getByrefLifetime(QualType Ty,
4596 Qualifiers::ObjCLifetime &LifeTime,
4597 bool &HasByrefExtendedLayout) const {
4598
4599 if (!getLangOpts().ObjC1 ||
4600 getLangOpts().getGC() != LangOptions::NonGC)
4601 return false;
4602
4603 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004604 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004605 HasByrefExtendedLayout = true;
4606 LifeTime = Qualifiers::OCL_None;
4607 }
4608 else if (getLangOpts().ObjCAutoRefCount)
4609 LifeTime = Ty.getObjCLifetime();
4610 // MRR.
4611 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4612 LifeTime = Qualifiers::OCL_ExplicitNone;
4613 else
4614 LifeTime = Qualifiers::OCL_None;
4615 return true;
4616}
4617
Douglas Gregorbab8a962011-09-08 01:46:34 +00004618TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4619 if (!ObjCInstanceTypeDecl)
4620 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4621 getTranslationUnitDecl(),
4622 SourceLocation(),
4623 SourceLocation(),
4624 &Idents.get("instancetype"),
4625 getTrivialTypeSourceInfo(getObjCIdType()));
4626 return ObjCInstanceTypeDecl;
4627}
4628
Anders Carlsson18acd442007-10-29 06:33:42 +00004629// This returns true if a type has been typedefed to BOOL:
4630// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004631static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004632 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004633 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4634 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004635
Anders Carlssond8499822007-10-29 05:01:08 +00004636 return false;
4637}
4638
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004639/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004640/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004641CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004642 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4643 return CharUnits::Zero();
4644
Ken Dyck40775002010-01-11 17:06:35 +00004645 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004646
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004647 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004648 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004649 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004650 // Treat arrays as pointers, since that's how they're passed in.
4651 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004652 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004653 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004654}
4655
4656static inline
4657std::string charUnitsToString(const CharUnits &CU) {
4658 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004659}
4660
John McCall351762c2011-02-07 10:33:21 +00004661/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004662/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004663std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4664 std::string S;
4665
David Chisnall950a9512009-11-17 19:33:30 +00004666 const BlockDecl *Decl = Expr->getBlockDecl();
4667 QualType BlockTy =
4668 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4669 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004670 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004671 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4672 BlockTy->getAs<FunctionType>()->getResultType(),
4673 S, true /*Extended*/);
4674 else
4675 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4676 S);
David Chisnall950a9512009-11-17 19:33:30 +00004677 // Compute size of all parameters.
4678 // Start with computing size of a pointer in number of bytes.
4679 // FIXME: There might(should) be a better way of doing this computation!
4680 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004681 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4682 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004683 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004684 E = Decl->param_end(); PI != E; ++PI) {
4685 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004686 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004687 if (sz.isZero())
4688 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004689 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004690 ParmOffset += sz;
4691 }
4692 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004693 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004694 // Block pointer and offset.
4695 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004696
4697 // Argument types.
4698 ParmOffset = PtrSize;
4699 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4700 Decl->param_end(); PI != E; ++PI) {
4701 ParmVarDecl *PVDecl = *PI;
4702 QualType PType = PVDecl->getOriginalType();
4703 if (const ArrayType *AT =
4704 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4705 // Use array's original type only if it has known number of
4706 // elements.
4707 if (!isa<ConstantArrayType>(AT))
4708 PType = PVDecl->getType();
4709 } else if (PType->isFunctionType())
4710 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004711 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004712 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4713 S, true /*Extended*/);
4714 else
4715 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004716 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004717 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004718 }
John McCall351762c2011-02-07 10:33:21 +00004719
4720 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004721}
4722
Douglas Gregora9d84932011-05-27 01:19:52 +00004723bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004724 std::string& S) {
4725 // Encode result type.
4726 getObjCEncodingForType(Decl->getResultType(), S);
4727 CharUnits ParmOffset;
4728 // Compute size of all parameters.
4729 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4730 E = Decl->param_end(); PI != E; ++PI) {
4731 QualType PType = (*PI)->getType();
4732 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004733 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004734 continue;
4735
David Chisnall50e4eba2010-12-30 14:05:53 +00004736 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004737 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004738 ParmOffset += sz;
4739 }
4740 S += charUnitsToString(ParmOffset);
4741 ParmOffset = CharUnits::Zero();
4742
4743 // Argument types.
4744 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4745 E = Decl->param_end(); PI != E; ++PI) {
4746 ParmVarDecl *PVDecl = *PI;
4747 QualType PType = PVDecl->getOriginalType();
4748 if (const ArrayType *AT =
4749 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4750 // Use array's original type only if it has known number of
4751 // elements.
4752 if (!isa<ConstantArrayType>(AT))
4753 PType = PVDecl->getType();
4754 } else if (PType->isFunctionType())
4755 PType = PVDecl->getType();
4756 getObjCEncodingForType(PType, S);
4757 S += charUnitsToString(ParmOffset);
4758 ParmOffset += getObjCEncodingTypeSize(PType);
4759 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004760
4761 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004762}
4763
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004764/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4765/// method parameter or return type. If Extended, include class names and
4766/// block object types.
4767void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4768 QualType T, std::string& S,
4769 bool Extended) const {
4770 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4771 getObjCEncodingForTypeQualifier(QT, S);
4772 // Encode parameter type.
4773 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4774 true /*OutermostType*/,
4775 false /*EncodingProperty*/,
4776 false /*StructField*/,
4777 Extended /*EncodeBlockParameters*/,
4778 Extended /*EncodeClassNames*/);
4779}
4780
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004781/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004782/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004783bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004784 std::string& S,
4785 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004786 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004787 // Encode return type.
4788 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4789 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004790 // Compute size of all parameters.
4791 // Start with computing size of a pointer in number of bytes.
4792 // FIXME: There might(should) be a better way of doing this computation!
4793 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004794 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004795 // The first two arguments (self and _cmd) are pointers; account for
4796 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004797 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004798 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004799 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004800 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004801 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004802 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004803 continue;
4804
Ken Dyck40775002010-01-11 17:06:35 +00004805 assert (sz.isPositive() &&
4806 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004807 ParmOffset += sz;
4808 }
Ken Dyck40775002010-01-11 17:06:35 +00004809 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004810 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004811 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004812
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004813 // Argument types.
4814 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004815 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004816 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004817 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004818 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004819 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004820 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4821 // Use array's original type only if it has known number of
4822 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004823 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004824 PType = PVDecl->getType();
4825 } else if (PType->isFunctionType())
4826 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004827 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4828 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004829 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004830 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004831 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004832
4833 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004834}
4835
Daniel Dunbar4932b362008-08-28 04:38:10 +00004836/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004837/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004838/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4839/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004840/// Property attributes are stored as a comma-delimited C string. The simple
4841/// attributes readonly and bycopy are encoded as single characters. The
4842/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4843/// encoded as single characters, followed by an identifier. Property types
4844/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004845/// these attributes are defined by the following enumeration:
4846/// @code
4847/// enum PropertyAttributes {
4848/// kPropertyReadOnly = 'R', // property is read-only.
4849/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4850/// kPropertyByref = '&', // property is a reference to the value last assigned
4851/// kPropertyDynamic = 'D', // property is dynamic
4852/// kPropertyGetter = 'G', // followed by getter selector name
4853/// kPropertySetter = 'S', // followed by setter selector name
4854/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004855/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004856/// kPropertyWeak = 'W' // 'weak' property
4857/// kPropertyStrong = 'P' // property GC'able
4858/// kPropertyNonAtomic = 'N' // property non-atomic
4859/// };
4860/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004861void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004862 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004863 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004864 // Collect information from the property implementation decl(s).
4865 bool Dynamic = false;
4866 ObjCPropertyImplDecl *SynthesizePID = 0;
4867
4868 // FIXME: Duplicated code due to poor abstraction.
4869 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004870 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004871 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4872 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004873 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004874 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004875 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004876 if (PID->getPropertyDecl() == PD) {
4877 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4878 Dynamic = true;
4879 } else {
4880 SynthesizePID = PID;
4881 }
4882 }
4883 }
4884 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004885 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004886 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004887 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004888 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004889 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004890 if (PID->getPropertyDecl() == PD) {
4891 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4892 Dynamic = true;
4893 } else {
4894 SynthesizePID = PID;
4895 }
4896 }
Mike Stump11289f42009-09-09 15:08:12 +00004897 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004898 }
4899 }
4900
4901 // FIXME: This is not very efficient.
4902 S = "T";
4903
4904 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004905 // GCC has some special rules regarding encoding of properties which
4906 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004907 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004908 true /* outermost type */,
4909 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004910
4911 if (PD->isReadOnly()) {
4912 S += ",R";
4913 } else {
4914 switch (PD->getSetterKind()) {
4915 case ObjCPropertyDecl::Assign: break;
4916 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004917 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004918 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004919 }
4920 }
4921
4922 // It really isn't clear at all what this means, since properties
4923 // are "dynamic by default".
4924 if (Dynamic)
4925 S += ",D";
4926
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004927 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4928 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004929
Daniel Dunbar4932b362008-08-28 04:38:10 +00004930 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4931 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004932 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004933 }
4934
4935 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4936 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004937 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004938 }
4939
4940 if (SynthesizePID) {
4941 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4942 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004943 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004944 }
4945
4946 // FIXME: OBJCGC: weak & strong
4947}
4948
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004949/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004950/// Another legacy compatibility encoding: 32-bit longs are encoded as
4951/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004952/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4953///
4954void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004955 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004956 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004957 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004958 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004959 else
Jay Foad39c79802011-01-12 09:06:06 +00004960 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004961 PointeeTy = IntTy;
4962 }
4963 }
4964}
4965
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004966void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004967 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004968 // We follow the behavior of gcc, expanding structures which are
4969 // directly pointed to, and expanding embedded structures. Note that
4970 // these rules are sufficient to prevent recursive encoding of the
4971 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004972 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004973 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004974}
4975
John McCall393a78d2012-12-20 02:45:14 +00004976static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
4977 BuiltinType::Kind kind) {
4978 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004979 case BuiltinType::Void: return 'v';
4980 case BuiltinType::Bool: return 'B';
4981 case BuiltinType::Char_U:
4982 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00004983 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00004984 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00004985 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00004986 case BuiltinType::UInt: return 'I';
4987 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00004988 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004989 case BuiltinType::UInt128: return 'T';
4990 case BuiltinType::ULongLong: return 'Q';
4991 case BuiltinType::Char_S:
4992 case BuiltinType::SChar: return 'c';
4993 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004994 case BuiltinType::WChar_S:
4995 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004996 case BuiltinType::Int: return 'i';
4997 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00004998 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004999 case BuiltinType::LongLong: return 'q';
5000 case BuiltinType::Int128: return 't';
5001 case BuiltinType::Float: return 'f';
5002 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005003 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005004 case BuiltinType::NullPtr: return '*'; // like char*
5005
5006 case BuiltinType::Half:
5007 // FIXME: potentially need @encodes for these!
5008 return ' ';
5009
5010 case BuiltinType::ObjCId:
5011 case BuiltinType::ObjCClass:
5012 case BuiltinType::ObjCSel:
5013 llvm_unreachable("@encoding ObjC primitive type");
5014
5015 // OpenCL and placeholder types don't need @encodings.
5016 case BuiltinType::OCLImage1d:
5017 case BuiltinType::OCLImage1dArray:
5018 case BuiltinType::OCLImage1dBuffer:
5019 case BuiltinType::OCLImage2d:
5020 case BuiltinType::OCLImage2dArray:
5021 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005022 case BuiltinType::OCLEvent:
Guy Benyei61054192013-02-07 10:55:47 +00005023 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005024 case BuiltinType::Dependent:
5025#define BUILTIN_TYPE(KIND, ID)
5026#define PLACEHOLDER_TYPE(KIND, ID) \
5027 case BuiltinType::KIND:
5028#include "clang/AST/BuiltinTypes.def"
5029 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005030 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005031 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005032}
5033
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005034static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5035 EnumDecl *Enum = ET->getDecl();
5036
5037 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5038 if (!Enum->isFixed())
5039 return 'i';
5040
5041 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005042 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5043 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005044}
5045
Jay Foad39c79802011-01-12 09:06:06 +00005046static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005047 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005048 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005049 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005050 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5051 // The GNU runtime requires more information; bitfields are encoded as b,
5052 // then the offset (in bits) of the first element, then the type of the
5053 // bitfield, then the size in bits. For example, in this structure:
5054 //
5055 // struct
5056 // {
5057 // int integer;
5058 // int flags:2;
5059 // };
5060 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5061 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5062 // information is not especially sensible, but we're stuck with it for
5063 // compatibility with GCC, although providing it breaks anything that
5064 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005065 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005066 const RecordDecl *RD = FD->getParent();
5067 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005068 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005069 if (const EnumType *ET = T->getAs<EnumType>())
5070 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005071 else {
5072 const BuiltinType *BT = T->castAs<BuiltinType>();
5073 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5074 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005075 }
Richard Smithcaf33902011-10-10 18:28:20 +00005076 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005077}
5078
Daniel Dunbar07d07852009-10-18 21:17:35 +00005079// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005080void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5081 bool ExpandPointedToStructures,
5082 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005083 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005084 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005085 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005086 bool StructField,
5087 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005088 bool EncodeClassNames,
5089 bool EncodePointerToObjCTypedef) const {
John McCall393a78d2012-12-20 02:45:14 +00005090 CanQualType CT = getCanonicalType(T);
5091 switch (CT->getTypeClass()) {
5092 case Type::Builtin:
5093 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005094 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005095 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005096 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5097 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5098 else
5099 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005100 return;
Mike Stump11289f42009-09-09 15:08:12 +00005101
John McCall393a78d2012-12-20 02:45:14 +00005102 case Type::Complex: {
5103 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005104 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00005105 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00005106 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005107 return;
5108 }
John McCall393a78d2012-12-20 02:45:14 +00005109
5110 case Type::Atomic: {
5111 const AtomicType *AT = T->castAs<AtomicType>();
5112 S += 'A';
5113 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5114 false, false);
5115 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005116 }
John McCall393a78d2012-12-20 02:45:14 +00005117
5118 // encoding for pointer or reference types.
5119 case Type::Pointer:
5120 case Type::LValueReference:
5121 case Type::RValueReference: {
5122 QualType PointeeTy;
5123 if (isa<PointerType>(CT)) {
5124 const PointerType *PT = T->castAs<PointerType>();
5125 if (PT->isObjCSelType()) {
5126 S += ':';
5127 return;
5128 }
5129 PointeeTy = PT->getPointeeType();
5130 } else {
5131 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5132 }
5133
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005134 bool isReadOnly = false;
5135 // For historical/compatibility reasons, the read-only qualifier of the
5136 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5137 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005138 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005139 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005140 if (OutermostType && T.isConstQualified()) {
5141 isReadOnly = true;
5142 S += 'r';
5143 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005144 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005145 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005146 while (P->getAs<PointerType>())
5147 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005148 if (P.isConstQualified()) {
5149 isReadOnly = true;
5150 S += 'r';
5151 }
5152 }
5153 if (isReadOnly) {
5154 // Another legacy compatibility encoding. Some ObjC qualifier and type
5155 // combinations need to be rearranged.
5156 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005157 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005158 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005159 }
Mike Stump11289f42009-09-09 15:08:12 +00005160
Anders Carlssond8499822007-10-29 05:01:08 +00005161 if (PointeeTy->isCharType()) {
5162 // char pointer types should be encoded as '*' unless it is a
5163 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005164 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005165 S += '*';
5166 return;
5167 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005168 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005169 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5170 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5171 S += '#';
5172 return;
5173 }
5174 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5175 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5176 S += '@';
5177 return;
5178 }
5179 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005180 }
Anders Carlssond8499822007-10-29 05:01:08 +00005181 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005182 getLegacyIntegralTypeEncoding(PointeeTy);
5183
Mike Stump11289f42009-09-09 15:08:12 +00005184 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005185 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005186 return;
5187 }
John McCall393a78d2012-12-20 02:45:14 +00005188
5189 case Type::ConstantArray:
5190 case Type::IncompleteArray:
5191 case Type::VariableArray: {
5192 const ArrayType *AT = cast<ArrayType>(CT);
5193
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005194 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005195 // Incomplete arrays are encoded as a pointer to the array element.
5196 S += '^';
5197
Mike Stump11289f42009-09-09 15:08:12 +00005198 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005199 false, ExpandStructures, FD);
5200 } else {
5201 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005202
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005203 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
5204 if (getTypeSize(CAT->getElementType()) == 0)
5205 S += '0';
5206 else
5207 S += llvm::utostr(CAT->getSize().getZExtValue());
5208 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005209 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005210 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5211 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005212 S += '0';
5213 }
Mike Stump11289f42009-09-09 15:08:12 +00005214
5215 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005216 false, ExpandStructures, FD);
5217 S += ']';
5218 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005219 return;
5220 }
Mike Stump11289f42009-09-09 15:08:12 +00005221
John McCall393a78d2012-12-20 02:45:14 +00005222 case Type::FunctionNoProto:
5223 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005224 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005225 return;
Mike Stump11289f42009-09-09 15:08:12 +00005226
John McCall393a78d2012-12-20 02:45:14 +00005227 case Type::Record: {
5228 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005229 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005230 // Anonymous structures print as '?'
5231 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5232 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005233 if (ClassTemplateSpecializationDecl *Spec
5234 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5235 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005236 llvm::raw_string_ostream OS(S);
5237 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005238 TemplateArgs.data(),
5239 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005240 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005241 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005242 } else {
5243 S += '?';
5244 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005245 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005246 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005247 if (!RDecl->isUnion()) {
5248 getObjCEncodingForStructureImpl(RDecl, S, FD);
5249 } else {
5250 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5251 FieldEnd = RDecl->field_end();
5252 Field != FieldEnd; ++Field) {
5253 if (FD) {
5254 S += '"';
5255 S += Field->getNameAsString();
5256 S += '"';
5257 }
Mike Stump11289f42009-09-09 15:08:12 +00005258
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005259 // Special case bit-fields.
5260 if (Field->isBitField()) {
5261 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00005262 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005263 } else {
5264 QualType qt = Field->getType();
5265 getLegacyIntegralTypeEncoding(qt);
5266 getObjCEncodingForTypeImpl(qt, S, false, true,
5267 FD, /*OutermostType*/false,
5268 /*EncodingProperty*/false,
5269 /*StructField*/true);
5270 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005271 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005272 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005273 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005274 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005275 return;
5276 }
Mike Stump11289f42009-09-09 15:08:12 +00005277
John McCall393a78d2012-12-20 02:45:14 +00005278 case Type::BlockPointer: {
5279 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005280 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005281 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005282 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005283
5284 S += '<';
5285 // Block return type
5286 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5287 ExpandPointedToStructures, ExpandStructures,
5288 FD,
5289 false /* OutermostType */,
5290 EncodingProperty,
5291 false /* StructField */,
5292 EncodeBlockParameters,
5293 EncodeClassNames);
5294 // Block self
5295 S += "@?";
5296 // Block parameters
5297 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5298 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5299 E = FPT->arg_type_end(); I && (I != E); ++I) {
5300 getObjCEncodingForTypeImpl(*I, S,
5301 ExpandPointedToStructures,
5302 ExpandStructures,
5303 FD,
5304 false /* OutermostType */,
5305 EncodingProperty,
5306 false /* StructField */,
5307 EncodeBlockParameters,
5308 EncodeClassNames);
5309 }
5310 }
5311 S += '>';
5312 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005313 return;
5314 }
Mike Stump11289f42009-09-09 15:08:12 +00005315
John McCall393a78d2012-12-20 02:45:14 +00005316 case Type::ObjCObject:
5317 case Type::ObjCInterface: {
5318 // Ignore protocol qualifiers when mangling at this level.
5319 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005320
John McCall393a78d2012-12-20 02:45:14 +00005321 // The assumption seems to be that this assert will succeed
5322 // because nested levels will have filtered out 'id' and 'Class'.
5323 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005324 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005325 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005326 S += '{';
5327 const IdentifierInfo *II = OI->getIdentifier();
5328 S += II->getName();
5329 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005330 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005331 DeepCollectObjCIvars(OI, true, Ivars);
5332 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005333 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005334 if (Field->isBitField())
5335 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005336 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005337 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5338 false, false, false, false, false,
5339 EncodePointerToObjCTypedef);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005340 }
5341 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005342 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005343 }
Mike Stump11289f42009-09-09 15:08:12 +00005344
John McCall393a78d2012-12-20 02:45:14 +00005345 case Type::ObjCObjectPointer: {
5346 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005347 if (OPT->isObjCIdType()) {
5348 S += '@';
5349 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005350 }
Mike Stump11289f42009-09-09 15:08:12 +00005351
Steve Narofff0c86112009-10-28 22:03:49 +00005352 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5353 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5354 // Since this is a binary compatibility issue, need to consult with runtime
5355 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005356 S += '#';
5357 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005358 }
Mike Stump11289f42009-09-09 15:08:12 +00005359
Chris Lattnere7cabb92009-07-13 00:10:46 +00005360 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005361 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005362 ExpandPointedToStructures,
5363 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005364 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005365 // Note that we do extended encoding of protocol qualifer list
5366 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005367 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00005368 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5369 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005370 S += '<';
5371 S += (*I)->getNameAsString();
5372 S += '>';
5373 }
5374 S += '"';
5375 }
5376 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005377 }
Mike Stump11289f42009-09-09 15:08:12 +00005378
Chris Lattnere7cabb92009-07-13 00:10:46 +00005379 QualType PointeeTy = OPT->getPointeeType();
5380 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005381 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5382 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005383 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005384 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005385 // {...};
5386 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00005387 getObjCEncodingForTypeImpl(PointeeTy, S,
5388 false, ExpandPointedToStructures,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005389 NULL,
5390 false, false, false, false, false,
5391 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005392 return;
5393 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005394
5395 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005396 if (OPT->getInterfaceDecl() &&
5397 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005398 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005399 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00005400 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5401 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005402 S += '<';
5403 S += (*I)->getNameAsString();
5404 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005405 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005406 S += '"';
5407 }
5408 return;
5409 }
Mike Stump11289f42009-09-09 15:08:12 +00005410
John McCalla9e6e8d2010-05-17 23:56:34 +00005411 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005412 // FIXME: we shoul do better than that. 'M' is available.
5413 case Type::MemberPointer:
John McCalla9e6e8d2010-05-17 23:56:34 +00005414 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005415
John McCall393a78d2012-12-20 02:45:14 +00005416 case Type::Vector:
5417 case Type::ExtVector:
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005418 // This matches gcc's encoding, even though technically it is
5419 // insufficient.
5420 // FIXME. We should do a better job than gcc.
5421 return;
John McCall393a78d2012-12-20 02:45:14 +00005422
Richard Smith27d807c2013-04-30 13:56:41 +00005423 case Type::Auto:
5424 // We could see an undeduced auto type here during error recovery.
5425 // Just ignore it.
5426 return;
5427
John McCall393a78d2012-12-20 02:45:14 +00005428#define ABSTRACT_TYPE(KIND, BASE)
5429#define TYPE(KIND, BASE)
5430#define DEPENDENT_TYPE(KIND, BASE) \
5431 case Type::KIND:
5432#define NON_CANONICAL_TYPE(KIND, BASE) \
5433 case Type::KIND:
5434#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5435 case Type::KIND:
5436#include "clang/AST/TypeNodes.def"
5437 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005438 }
John McCall393a78d2012-12-20 02:45:14 +00005439 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005440}
5441
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005442void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5443 std::string &S,
5444 const FieldDecl *FD,
5445 bool includeVBases) const {
5446 assert(RDecl && "Expected non-null RecordDecl");
5447 assert(!RDecl->isUnion() && "Should not be called for unions");
5448 if (!RDecl->getDefinition())
5449 return;
5450
5451 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5452 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5453 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5454
5455 if (CXXRec) {
5456 for (CXXRecordDecl::base_class_iterator
5457 BI = CXXRec->bases_begin(),
5458 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5459 if (!BI->isVirtual()) {
5460 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005461 if (base->isEmpty())
5462 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005463 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005464 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5465 std::make_pair(offs, base));
5466 }
5467 }
5468 }
5469
5470 unsigned i = 0;
5471 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5472 FieldEnd = RDecl->field_end();
5473 Field != FieldEnd; ++Field, ++i) {
5474 uint64_t offs = layout.getFieldOffset(i);
5475 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005476 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005477 }
5478
5479 if (CXXRec && includeVBases) {
5480 for (CXXRecordDecl::base_class_iterator
5481 BI = CXXRec->vbases_begin(),
5482 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5483 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005484 if (base->isEmpty())
5485 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005486 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005487 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5488 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5489 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005490 }
5491 }
5492
5493 CharUnits size;
5494 if (CXXRec) {
5495 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5496 } else {
5497 size = layout.getSize();
5498 }
5499
5500 uint64_t CurOffs = 0;
5501 std::multimap<uint64_t, NamedDecl *>::iterator
5502 CurLayObj = FieldOrBaseOffsets.begin();
5503
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005504 if (CXXRec && CXXRec->isDynamicClass() &&
5505 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005506 if (FD) {
5507 S += "\"_vptr$";
5508 std::string recname = CXXRec->getNameAsString();
5509 if (recname.empty()) recname = "?";
5510 S += recname;
5511 S += '"';
5512 }
5513 S += "^^?";
5514 CurOffs += getTypeSize(VoidPtrTy);
5515 }
5516
5517 if (!RDecl->hasFlexibleArrayMember()) {
5518 // Mark the end of the structure.
5519 uint64_t offs = toBits(size);
5520 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5521 std::make_pair(offs, (NamedDecl*)0));
5522 }
5523
5524 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5525 assert(CurOffs <= CurLayObj->first);
5526
5527 if (CurOffs < CurLayObj->first) {
5528 uint64_t padding = CurLayObj->first - CurOffs;
5529 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5530 // packing/alignment of members is different that normal, in which case
5531 // the encoding will be out-of-sync with the real layout.
5532 // If the runtime switches to just consider the size of types without
5533 // taking into account alignment, we could make padding explicit in the
5534 // encoding (e.g. using arrays of chars). The encoding strings would be
5535 // longer then though.
5536 CurOffs += padding;
5537 }
5538
5539 NamedDecl *dcl = CurLayObj->second;
5540 if (dcl == 0)
5541 break; // reached end of structure.
5542
5543 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5544 // We expand the bases without their virtual bases since those are going
5545 // in the initial structure. Note that this differs from gcc which
5546 // expands virtual bases each time one is encountered in the hierarchy,
5547 // making the encoding type bigger than it really is.
5548 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005549 assert(!base->isEmpty());
5550 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005551 } else {
5552 FieldDecl *field = cast<FieldDecl>(dcl);
5553 if (FD) {
5554 S += '"';
5555 S += field->getNameAsString();
5556 S += '"';
5557 }
5558
5559 if (field->isBitField()) {
5560 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00005561 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005562 } else {
5563 QualType qt = field->getType();
5564 getLegacyIntegralTypeEncoding(qt);
5565 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5566 /*OutermostType*/false,
5567 /*EncodingProperty*/false,
5568 /*StructField*/true);
5569 CurOffs += getTypeSize(field->getType());
5570 }
5571 }
5572 }
5573}
5574
Mike Stump11289f42009-09-09 15:08:12 +00005575void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005576 std::string& S) const {
5577 if (QT & Decl::OBJC_TQ_In)
5578 S += 'n';
5579 if (QT & Decl::OBJC_TQ_Inout)
5580 S += 'N';
5581 if (QT & Decl::OBJC_TQ_Out)
5582 S += 'o';
5583 if (QT & Decl::OBJC_TQ_Bycopy)
5584 S += 'O';
5585 if (QT & Decl::OBJC_TQ_Byref)
5586 S += 'R';
5587 if (QT & Decl::OBJC_TQ_Oneway)
5588 S += 'V';
5589}
5590
Douglas Gregor3ea72692011-08-12 05:46:01 +00005591TypedefDecl *ASTContext::getObjCIdDecl() const {
5592 if (!ObjCIdDecl) {
5593 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5594 T = getObjCObjectPointerType(T);
5595 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5596 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5597 getTranslationUnitDecl(),
5598 SourceLocation(), SourceLocation(),
5599 &Idents.get("id"), IdInfo);
5600 }
5601
5602 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005603}
5604
Douglas Gregor52e02802011-08-12 06:17:30 +00005605TypedefDecl *ASTContext::getObjCSelDecl() const {
5606 if (!ObjCSelDecl) {
5607 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5608 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5609 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5610 getTranslationUnitDecl(),
5611 SourceLocation(), SourceLocation(),
5612 &Idents.get("SEL"), SelInfo);
5613 }
5614 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005615}
5616
Douglas Gregor0a586182011-08-12 05:59:41 +00005617TypedefDecl *ASTContext::getObjCClassDecl() const {
5618 if (!ObjCClassDecl) {
5619 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5620 T = getObjCObjectPointerType(T);
5621 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5622 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5623 getTranslationUnitDecl(),
5624 SourceLocation(), SourceLocation(),
5625 &Idents.get("Class"), ClassInfo);
5626 }
5627
5628 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005629}
5630
Douglas Gregord53ae832012-01-17 18:09:05 +00005631ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5632 if (!ObjCProtocolClassDecl) {
5633 ObjCProtocolClassDecl
5634 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5635 SourceLocation(),
5636 &Idents.get("Protocol"),
5637 /*PrevDecl=*/0,
5638 SourceLocation(), true);
5639 }
5640
5641 return ObjCProtocolClassDecl;
5642}
5643
Meador Inge5d3fb222012-06-16 03:34:49 +00005644//===----------------------------------------------------------------------===//
5645// __builtin_va_list Construction Functions
5646//===----------------------------------------------------------------------===//
5647
5648static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5649 // typedef char* __builtin_va_list;
5650 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5651 TypeSourceInfo *TInfo
5652 = Context->getTrivialTypeSourceInfo(CharPtrType);
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
5663static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5664 // typedef void* __builtin_va_list;
5665 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5666 TypeSourceInfo *TInfo
5667 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5668
5669 TypedefDecl *VaListTypeDecl
5670 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5671 Context->getTranslationUnitDecl(),
5672 SourceLocation(), SourceLocation(),
5673 &Context->Idents.get("__builtin_va_list"),
5674 TInfo);
5675 return VaListTypeDecl;
5676}
5677
Tim Northover9bb857a2013-01-31 12:13:10 +00005678static TypedefDecl *
5679CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5680 RecordDecl *VaListTagDecl;
5681 if (Context->getLangOpts().CPlusPlus) {
5682 // namespace std { struct __va_list {
5683 NamespaceDecl *NS;
5684 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5685 Context->getTranslationUnitDecl(),
5686 /*Inline*/false, SourceLocation(),
5687 SourceLocation(), &Context->Idents.get("std"),
5688 /*PrevDecl*/0);
5689
5690 VaListTagDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5691 Context->getTranslationUnitDecl(),
5692 SourceLocation(), SourceLocation(),
5693 &Context->Idents.get("__va_list"));
5694 VaListTagDecl->setDeclContext(NS);
5695 } else {
5696 // struct __va_list
5697 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5698 Context->getTranslationUnitDecl(),
5699 &Context->Idents.get("__va_list"));
5700 }
5701
5702 VaListTagDecl->startDefinition();
5703
5704 const size_t NumFields = 5;
5705 QualType FieldTypes[NumFields];
5706 const char *FieldNames[NumFields];
5707
5708 // void *__stack;
5709 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5710 FieldNames[0] = "__stack";
5711
5712 // void *__gr_top;
5713 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5714 FieldNames[1] = "__gr_top";
5715
5716 // void *__vr_top;
5717 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5718 FieldNames[2] = "__vr_top";
5719
5720 // int __gr_offs;
5721 FieldTypes[3] = Context->IntTy;
5722 FieldNames[3] = "__gr_offs";
5723
5724 // int __vr_offs;
5725 FieldTypes[4] = Context->IntTy;
5726 FieldNames[4] = "__vr_offs";
5727
5728 // Create fields
5729 for (unsigned i = 0; i < NumFields; ++i) {
5730 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5731 VaListTagDecl,
5732 SourceLocation(),
5733 SourceLocation(),
5734 &Context->Idents.get(FieldNames[i]),
5735 FieldTypes[i], /*TInfo=*/0,
5736 /*BitWidth=*/0,
5737 /*Mutable=*/false,
5738 ICIS_NoInit);
5739 Field->setAccess(AS_public);
5740 VaListTagDecl->addDecl(Field);
5741 }
5742 VaListTagDecl->completeDefinition();
5743 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5744 Context->VaListTagTy = VaListTagType;
5745
5746 // } __builtin_va_list;
5747 TypedefDecl *VaListTypedefDecl
5748 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5749 Context->getTranslationUnitDecl(),
5750 SourceLocation(), SourceLocation(),
5751 &Context->Idents.get("__builtin_va_list"),
5752 Context->getTrivialTypeSourceInfo(VaListTagType));
5753
5754 return VaListTypedefDecl;
5755}
5756
Meador Inge5d3fb222012-06-16 03:34:49 +00005757static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5758 // typedef struct __va_list_tag {
5759 RecordDecl *VaListTagDecl;
5760
5761 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5762 Context->getTranslationUnitDecl(),
5763 &Context->Idents.get("__va_list_tag"));
5764 VaListTagDecl->startDefinition();
5765
5766 const size_t NumFields = 5;
5767 QualType FieldTypes[NumFields];
5768 const char *FieldNames[NumFields];
5769
5770 // unsigned char gpr;
5771 FieldTypes[0] = Context->UnsignedCharTy;
5772 FieldNames[0] = "gpr";
5773
5774 // unsigned char fpr;
5775 FieldTypes[1] = Context->UnsignedCharTy;
5776 FieldNames[1] = "fpr";
5777
5778 // unsigned short reserved;
5779 FieldTypes[2] = Context->UnsignedShortTy;
5780 FieldNames[2] = "reserved";
5781
5782 // void* overflow_arg_area;
5783 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5784 FieldNames[3] = "overflow_arg_area";
5785
5786 // void* reg_save_area;
5787 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5788 FieldNames[4] = "reg_save_area";
5789
5790 // Create fields
5791 for (unsigned i = 0; i < NumFields; ++i) {
5792 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5793 SourceLocation(),
5794 SourceLocation(),
5795 &Context->Idents.get(FieldNames[i]),
5796 FieldTypes[i], /*TInfo=*/0,
5797 /*BitWidth=*/0,
5798 /*Mutable=*/false,
5799 ICIS_NoInit);
5800 Field->setAccess(AS_public);
5801 VaListTagDecl->addDecl(Field);
5802 }
5803 VaListTagDecl->completeDefinition();
5804 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005805 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005806
5807 // } __va_list_tag;
5808 TypedefDecl *VaListTagTypedefDecl
5809 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5810 Context->getTranslationUnitDecl(),
5811 SourceLocation(), SourceLocation(),
5812 &Context->Idents.get("__va_list_tag"),
5813 Context->getTrivialTypeSourceInfo(VaListTagType));
5814 QualType VaListTagTypedefType =
5815 Context->getTypedefType(VaListTagTypedefDecl);
5816
5817 // typedef __va_list_tag __builtin_va_list[1];
5818 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5819 QualType VaListTagArrayType
5820 = Context->getConstantArrayType(VaListTagTypedefType,
5821 Size, ArrayType::Normal, 0);
5822 TypeSourceInfo *TInfo
5823 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5824 TypedefDecl *VaListTypedefDecl
5825 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5826 Context->getTranslationUnitDecl(),
5827 SourceLocation(), SourceLocation(),
5828 &Context->Idents.get("__builtin_va_list"),
5829 TInfo);
5830
5831 return VaListTypedefDecl;
5832}
5833
5834static TypedefDecl *
5835CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5836 // typedef struct __va_list_tag {
5837 RecordDecl *VaListTagDecl;
5838 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5839 Context->getTranslationUnitDecl(),
5840 &Context->Idents.get("__va_list_tag"));
5841 VaListTagDecl->startDefinition();
5842
5843 const size_t NumFields = 4;
5844 QualType FieldTypes[NumFields];
5845 const char *FieldNames[NumFields];
5846
5847 // unsigned gp_offset;
5848 FieldTypes[0] = Context->UnsignedIntTy;
5849 FieldNames[0] = "gp_offset";
5850
5851 // unsigned fp_offset;
5852 FieldTypes[1] = Context->UnsignedIntTy;
5853 FieldNames[1] = "fp_offset";
5854
5855 // void* overflow_arg_area;
5856 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5857 FieldNames[2] = "overflow_arg_area";
5858
5859 // void* reg_save_area;
5860 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5861 FieldNames[3] = "reg_save_area";
5862
5863 // Create fields
5864 for (unsigned i = 0; i < NumFields; ++i) {
5865 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5866 VaListTagDecl,
5867 SourceLocation(),
5868 SourceLocation(),
5869 &Context->Idents.get(FieldNames[i]),
5870 FieldTypes[i], /*TInfo=*/0,
5871 /*BitWidth=*/0,
5872 /*Mutable=*/false,
5873 ICIS_NoInit);
5874 Field->setAccess(AS_public);
5875 VaListTagDecl->addDecl(Field);
5876 }
5877 VaListTagDecl->completeDefinition();
5878 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005879 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005880
5881 // } __va_list_tag;
5882 TypedefDecl *VaListTagTypedefDecl
5883 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5884 Context->getTranslationUnitDecl(),
5885 SourceLocation(), SourceLocation(),
5886 &Context->Idents.get("__va_list_tag"),
5887 Context->getTrivialTypeSourceInfo(VaListTagType));
5888 QualType VaListTagTypedefType =
5889 Context->getTypedefType(VaListTagTypedefDecl);
5890
5891 // typedef __va_list_tag __builtin_va_list[1];
5892 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5893 QualType VaListTagArrayType
5894 = Context->getConstantArrayType(VaListTagTypedefType,
5895 Size, ArrayType::Normal,0);
5896 TypeSourceInfo *TInfo
5897 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5898 TypedefDecl *VaListTypedefDecl
5899 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5900 Context->getTranslationUnitDecl(),
5901 SourceLocation(), SourceLocation(),
5902 &Context->Idents.get("__builtin_va_list"),
5903 TInfo);
5904
5905 return VaListTypedefDecl;
5906}
5907
5908static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5909 // typedef int __builtin_va_list[4];
5910 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5911 QualType IntArrayType
5912 = Context->getConstantArrayType(Context->IntTy,
5913 Size, ArrayType::Normal, 0);
5914 TypedefDecl *VaListTypedefDecl
5915 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5916 Context->getTranslationUnitDecl(),
5917 SourceLocation(), SourceLocation(),
5918 &Context->Idents.get("__builtin_va_list"),
5919 Context->getTrivialTypeSourceInfo(IntArrayType));
5920
5921 return VaListTypedefDecl;
5922}
5923
Logan Chien57086ce2012-10-10 06:56:20 +00005924static TypedefDecl *
5925CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5926 RecordDecl *VaListDecl;
5927 if (Context->getLangOpts().CPlusPlus) {
5928 // namespace std { struct __va_list {
5929 NamespaceDecl *NS;
5930 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5931 Context->getTranslationUnitDecl(),
5932 /*Inline*/false, SourceLocation(),
5933 SourceLocation(), &Context->Idents.get("std"),
5934 /*PrevDecl*/0);
5935
5936 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5937 Context->getTranslationUnitDecl(),
5938 SourceLocation(), SourceLocation(),
5939 &Context->Idents.get("__va_list"));
5940
5941 VaListDecl->setDeclContext(NS);
5942
5943 } else {
5944 // struct __va_list {
5945 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
5946 Context->getTranslationUnitDecl(),
5947 &Context->Idents.get("__va_list"));
5948 }
5949
5950 VaListDecl->startDefinition();
5951
5952 // void * __ap;
5953 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5954 VaListDecl,
5955 SourceLocation(),
5956 SourceLocation(),
5957 &Context->Idents.get("__ap"),
5958 Context->getPointerType(Context->VoidTy),
5959 /*TInfo=*/0,
5960 /*BitWidth=*/0,
5961 /*Mutable=*/false,
5962 ICIS_NoInit);
5963 Field->setAccess(AS_public);
5964 VaListDecl->addDecl(Field);
5965
5966 // };
5967 VaListDecl->completeDefinition();
5968
5969 // typedef struct __va_list __builtin_va_list;
5970 TypeSourceInfo *TInfo
5971 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
5972
5973 TypedefDecl *VaListTypeDecl
5974 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5975 Context->getTranslationUnitDecl(),
5976 SourceLocation(), SourceLocation(),
5977 &Context->Idents.get("__builtin_va_list"),
5978 TInfo);
5979
5980 return VaListTypeDecl;
5981}
5982
Ulrich Weigand47445072013-05-06 16:26:41 +00005983static TypedefDecl *
5984CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
5985 // typedef struct __va_list_tag {
5986 RecordDecl *VaListTagDecl;
5987 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5988 Context->getTranslationUnitDecl(),
5989 &Context->Idents.get("__va_list_tag"));
5990 VaListTagDecl->startDefinition();
5991
5992 const size_t NumFields = 4;
5993 QualType FieldTypes[NumFields];
5994 const char *FieldNames[NumFields];
5995
5996 // long __gpr;
5997 FieldTypes[0] = Context->LongTy;
5998 FieldNames[0] = "__gpr";
5999
6000 // long __fpr;
6001 FieldTypes[1] = Context->LongTy;
6002 FieldNames[1] = "__fpr";
6003
6004 // void *__overflow_arg_area;
6005 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6006 FieldNames[2] = "__overflow_arg_area";
6007
6008 // void *__reg_save_area;
6009 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6010 FieldNames[3] = "__reg_save_area";
6011
6012 // Create fields
6013 for (unsigned i = 0; i < NumFields; ++i) {
6014 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6015 VaListTagDecl,
6016 SourceLocation(),
6017 SourceLocation(),
6018 &Context->Idents.get(FieldNames[i]),
6019 FieldTypes[i], /*TInfo=*/0,
6020 /*BitWidth=*/0,
6021 /*Mutable=*/false,
6022 ICIS_NoInit);
6023 Field->setAccess(AS_public);
6024 VaListTagDecl->addDecl(Field);
6025 }
6026 VaListTagDecl->completeDefinition();
6027 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6028 Context->VaListTagTy = VaListTagType;
6029
6030 // } __va_list_tag;
6031 TypedefDecl *VaListTagTypedefDecl
6032 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6033 Context->getTranslationUnitDecl(),
6034 SourceLocation(), SourceLocation(),
6035 &Context->Idents.get("__va_list_tag"),
6036 Context->getTrivialTypeSourceInfo(VaListTagType));
6037 QualType VaListTagTypedefType =
6038 Context->getTypedefType(VaListTagTypedefDecl);
6039
6040 // typedef __va_list_tag __builtin_va_list[1];
6041 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6042 QualType VaListTagArrayType
6043 = Context->getConstantArrayType(VaListTagTypedefType,
6044 Size, ArrayType::Normal,0);
6045 TypeSourceInfo *TInfo
6046 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
6047 TypedefDecl *VaListTypedefDecl
6048 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6049 Context->getTranslationUnitDecl(),
6050 SourceLocation(), SourceLocation(),
6051 &Context->Idents.get("__builtin_va_list"),
6052 TInfo);
6053
6054 return VaListTypedefDecl;
6055}
6056
Meador Inge5d3fb222012-06-16 03:34:49 +00006057static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6058 TargetInfo::BuiltinVaListKind Kind) {
6059 switch (Kind) {
6060 case TargetInfo::CharPtrBuiltinVaList:
6061 return CreateCharPtrBuiltinVaListDecl(Context);
6062 case TargetInfo::VoidPtrBuiltinVaList:
6063 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006064 case TargetInfo::AArch64ABIBuiltinVaList:
6065 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006066 case TargetInfo::PowerABIBuiltinVaList:
6067 return CreatePowerABIBuiltinVaListDecl(Context);
6068 case TargetInfo::X86_64ABIBuiltinVaList:
6069 return CreateX86_64ABIBuiltinVaListDecl(Context);
6070 case TargetInfo::PNaClABIBuiltinVaList:
6071 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006072 case TargetInfo::AAPCSABIBuiltinVaList:
6073 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006074 case TargetInfo::SystemZBuiltinVaList:
6075 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006076 }
6077
6078 llvm_unreachable("Unhandled __builtin_va_list type kind");
6079}
6080
6081TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6082 if (!BuiltinVaListDecl)
6083 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6084
6085 return BuiltinVaListDecl;
6086}
6087
Meador Ingecfb60902012-07-01 15:57:25 +00006088QualType ASTContext::getVaListTagType() const {
6089 // Force the creation of VaListTagTy by building the __builtin_va_list
6090 // declaration.
6091 if (VaListTagTy.isNull())
6092 (void) getBuiltinVaListDecl();
6093
6094 return VaListTagTy;
6095}
6096
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006097void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006098 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006099 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006100
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006101 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006102}
6103
John McCalld28ae272009-12-02 08:04:21 +00006104/// \brief Retrieve the template name that corresponds to a non-empty
6105/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006106TemplateName
6107ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6108 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006109 unsigned size = End - Begin;
6110 assert(size > 1 && "set is not overloaded!");
6111
6112 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6113 size * sizeof(FunctionTemplateDecl*));
6114 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6115
6116 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006117 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006118 NamedDecl *D = *I;
6119 assert(isa<FunctionTemplateDecl>(D) ||
6120 (isa<UsingShadowDecl>(D) &&
6121 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6122 *Storage++ = D;
6123 }
6124
6125 return TemplateName(OT);
6126}
6127
Douglas Gregordc572a32009-03-30 22:58:21 +00006128/// \brief Retrieve the template name that represents a qualified
6129/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006130TemplateName
6131ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6132 bool TemplateKeyword,
6133 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006134 assert(NNS && "Missing nested-name-specifier in qualified template name");
6135
Douglas Gregorc42075a2010-02-04 18:10:26 +00006136 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006137 llvm::FoldingSetNodeID ID;
6138 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6139
6140 void *InsertPos = 0;
6141 QualifiedTemplateName *QTN =
6142 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6143 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006144 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6145 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006146 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6147 }
6148
6149 return TemplateName(QTN);
6150}
6151
6152/// \brief Retrieve the template name that represents a dependent
6153/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006154TemplateName
6155ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6156 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006157 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006158 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006159
6160 llvm::FoldingSetNodeID ID;
6161 DependentTemplateName::Profile(ID, NNS, Name);
6162
6163 void *InsertPos = 0;
6164 DependentTemplateName *QTN =
6165 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6166
6167 if (QTN)
6168 return TemplateName(QTN);
6169
6170 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6171 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006172 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6173 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006174 } else {
6175 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006176 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6177 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006178 DependentTemplateName *CheckQTN =
6179 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6180 assert(!CheckQTN && "Dependent type name canonicalization broken");
6181 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006182 }
6183
6184 DependentTemplateNames.InsertNode(QTN, InsertPos);
6185 return TemplateName(QTN);
6186}
6187
Douglas Gregor71395fa2009-11-04 00:56:37 +00006188/// \brief Retrieve the template name that represents a dependent
6189/// template name such as \c MetaFun::template operator+.
6190TemplateName
6191ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006192 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006193 assert((!NNS || NNS->isDependent()) &&
6194 "Nested name specifier must be dependent");
6195
6196 llvm::FoldingSetNodeID ID;
6197 DependentTemplateName::Profile(ID, NNS, Operator);
6198
6199 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006200 DependentTemplateName *QTN
6201 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006202
6203 if (QTN)
6204 return TemplateName(QTN);
6205
6206 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6207 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006208 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6209 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006210 } else {
6211 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006212 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6213 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006214
6215 DependentTemplateName *CheckQTN
6216 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6217 assert(!CheckQTN && "Dependent template name canonicalization broken");
6218 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006219 }
6220
6221 DependentTemplateNames.InsertNode(QTN, InsertPos);
6222 return TemplateName(QTN);
6223}
6224
Douglas Gregor5590be02011-01-15 06:45:20 +00006225TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006226ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6227 TemplateName replacement) const {
6228 llvm::FoldingSetNodeID ID;
6229 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6230
6231 void *insertPos = 0;
6232 SubstTemplateTemplateParmStorage *subst
6233 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6234
6235 if (!subst) {
6236 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6237 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6238 }
6239
6240 return TemplateName(subst);
6241}
6242
6243TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006244ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6245 const TemplateArgument &ArgPack) const {
6246 ASTContext &Self = const_cast<ASTContext &>(*this);
6247 llvm::FoldingSetNodeID ID;
6248 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6249
6250 void *InsertPos = 0;
6251 SubstTemplateTemplateParmPackStorage *Subst
6252 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6253
6254 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006255 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006256 ArgPack.pack_size(),
6257 ArgPack.pack_begin());
6258 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6259 }
6260
6261 return TemplateName(Subst);
6262}
6263
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006264/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006265/// TargetInfo, produce the corresponding type. The unsigned @p Type
6266/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006267CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006268 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006269 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006270 case TargetInfo::SignedShort: return ShortTy;
6271 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6272 case TargetInfo::SignedInt: return IntTy;
6273 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6274 case TargetInfo::SignedLong: return LongTy;
6275 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6276 case TargetInfo::SignedLongLong: return LongLongTy;
6277 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6278 }
6279
David Blaikie83d382b2011-09-23 05:06:16 +00006280 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006281}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006282
6283//===----------------------------------------------------------------------===//
6284// Type Predicates.
6285//===----------------------------------------------------------------------===//
6286
Fariborz Jahanian96207692009-02-18 21:49:28 +00006287/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6288/// garbage collection attribute.
6289///
John McCall553d45a2011-01-12 00:34:59 +00006290Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006291 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006292 return Qualifiers::GCNone;
6293
David Blaikiebbafb8a2012-03-11 07:00:24 +00006294 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006295 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6296
6297 // Default behaviour under objective-C's gc is for ObjC pointers
6298 // (or pointers to them) be treated as though they were declared
6299 // as __strong.
6300 if (GCAttrs == Qualifiers::GCNone) {
6301 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6302 return Qualifiers::Strong;
6303 else if (Ty->isPointerType())
6304 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6305 } else {
6306 // It's not valid to set GC attributes on anything that isn't a
6307 // pointer.
6308#ifndef NDEBUG
6309 QualType CT = Ty->getCanonicalTypeInternal();
6310 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6311 CT = AT->getElementType();
6312 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6313#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006314 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006315 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006316}
6317
Chris Lattner49af6a42008-04-07 06:51:04 +00006318//===----------------------------------------------------------------------===//
6319// Type Compatibility Testing
6320//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006321
Mike Stump11289f42009-09-09 15:08:12 +00006322/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006323/// compatible.
6324static bool areCompatVectorTypes(const VectorType *LHS,
6325 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006326 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006327 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006328 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006329}
6330
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006331bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6332 QualType SecondVec) {
6333 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6334 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6335
6336 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6337 return true;
6338
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006339 // Treat Neon vector types and most AltiVec vector types as if they are the
6340 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006341 const VectorType *First = FirstVec->getAs<VectorType>();
6342 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006343 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006344 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006345 First->getVectorKind() != VectorType::AltiVecPixel &&
6346 First->getVectorKind() != VectorType::AltiVecBool &&
6347 Second->getVectorKind() != VectorType::AltiVecPixel &&
6348 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006349 return true;
6350
6351 return false;
6352}
6353
Steve Naroff8e6aee52009-07-23 01:01:38 +00006354//===----------------------------------------------------------------------===//
6355// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6356//===----------------------------------------------------------------------===//
6357
6358/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6359/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006360bool
6361ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6362 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006363 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006364 return true;
6365 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6366 E = rProto->protocol_end(); PI != E; ++PI)
6367 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6368 return true;
6369 return false;
6370}
6371
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006372/// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
Steve Naroff8e6aee52009-07-23 01:01:38 +00006373/// return true if lhs's protocols conform to rhs's protocol; false
6374/// otherwise.
6375bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
6376 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
6377 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
6378 return false;
6379}
6380
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006381/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6382/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006383bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6384 QualType rhs) {
6385 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6386 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6387 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6388
6389 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6390 E = lhsQID->qual_end(); I != E; ++I) {
6391 bool match = false;
6392 ObjCProtocolDecl *lhsProto = *I;
6393 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6394 E = rhsOPT->qual_end(); J != E; ++J) {
6395 ObjCProtocolDecl *rhsProto = *J;
6396 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6397 match = true;
6398 break;
6399 }
6400 }
6401 if (!match)
6402 return false;
6403 }
6404 return true;
6405}
6406
Steve Naroff8e6aee52009-07-23 01:01:38 +00006407/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6408/// ObjCQualifiedIDType.
6409bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6410 bool compare) {
6411 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006412 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006413 lhs->isObjCIdType() || lhs->isObjCClassType())
6414 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006415 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006416 rhs->isObjCIdType() || rhs->isObjCClassType())
6417 return true;
6418
6419 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006420 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006421
Steve Naroff8e6aee52009-07-23 01:01:38 +00006422 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006423
Steve Naroff8e6aee52009-07-23 01:01:38 +00006424 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006425 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006426 // make sure we check the class hierarchy.
6427 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6428 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6429 E = lhsQID->qual_end(); I != E; ++I) {
6430 // when comparing an id<P> on lhs with a static type on rhs,
6431 // see if static class implements all of id's protocols, directly or
6432 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006433 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006434 return false;
6435 }
6436 }
6437 // If there are no qualifiers and no interface, we have an 'id'.
6438 return true;
6439 }
Mike Stump11289f42009-09-09 15:08:12 +00006440 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006441 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6442 E = lhsQID->qual_end(); I != E; ++I) {
6443 ObjCProtocolDecl *lhsProto = *I;
6444 bool match = false;
6445
6446 // when comparing an id<P> on lhs with a static type on rhs,
6447 // see if static class implements all of id's protocols, directly or
6448 // through its super class and categories.
6449 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6450 E = rhsOPT->qual_end(); J != E; ++J) {
6451 ObjCProtocolDecl *rhsProto = *J;
6452 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6453 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6454 match = true;
6455 break;
6456 }
6457 }
Mike Stump11289f42009-09-09 15:08:12 +00006458 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006459 // make sure we check the class hierarchy.
6460 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6461 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6462 E = lhsQID->qual_end(); I != E; ++I) {
6463 // when comparing an id<P> on lhs with a static type on rhs,
6464 // see if static class implements all of id's protocols, directly or
6465 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006466 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006467 match = true;
6468 break;
6469 }
6470 }
6471 }
6472 if (!match)
6473 return false;
6474 }
Mike Stump11289f42009-09-09 15:08:12 +00006475
Steve Naroff8e6aee52009-07-23 01:01:38 +00006476 return true;
6477 }
Mike Stump11289f42009-09-09 15:08:12 +00006478
Steve Naroff8e6aee52009-07-23 01:01:38 +00006479 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6480 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6481
Mike Stump11289f42009-09-09 15:08:12 +00006482 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006483 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006484 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006485 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6486 E = lhsOPT->qual_end(); I != E; ++I) {
6487 ObjCProtocolDecl *lhsProto = *I;
6488 bool match = false;
6489
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006490 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006491 // see if static class implements all of id's protocols, directly or
6492 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006493 // First, lhs protocols in the qualifier list must be found, direct
6494 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006495 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6496 E = rhsQID->qual_end(); J != E; ++J) {
6497 ObjCProtocolDecl *rhsProto = *J;
6498 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6499 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6500 match = true;
6501 break;
6502 }
6503 }
6504 if (!match)
6505 return false;
6506 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006507
6508 // Static class's protocols, or its super class or category protocols
6509 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6510 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6511 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6512 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6513 // This is rather dubious but matches gcc's behavior. If lhs has
6514 // no type qualifier and its class has no static protocol(s)
6515 // assume that it is mismatch.
6516 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6517 return false;
6518 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6519 LHSInheritedProtocols.begin(),
6520 E = LHSInheritedProtocols.end(); I != E; ++I) {
6521 bool match = false;
6522 ObjCProtocolDecl *lhsProto = (*I);
6523 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6524 E = rhsQID->qual_end(); J != E; ++J) {
6525 ObjCProtocolDecl *rhsProto = *J;
6526 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6527 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6528 match = true;
6529 break;
6530 }
6531 }
6532 if (!match)
6533 return false;
6534 }
6535 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006536 return true;
6537 }
6538 return false;
6539}
6540
Eli Friedman47f77112008-08-22 00:56:42 +00006541/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006542/// compatible for assignment from RHS to LHS. This handles validation of any
6543/// protocol qualifiers on the LHS or RHS.
6544///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006545bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6546 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006547 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6548 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6549
Steve Naroff1329fa02009-07-15 18:40:39 +00006550 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006551 if (LHS->isObjCUnqualifiedIdOrClass() ||
6552 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006553 return true;
6554
John McCall8b07ec22010-05-15 11:32:37 +00006555 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006556 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6557 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006558 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006559
6560 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6561 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6562 QualType(RHSOPT,0));
6563
John McCall8b07ec22010-05-15 11:32:37 +00006564 // If we have 2 user-defined types, fall into that path.
6565 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006566 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006567
Steve Naroff8e6aee52009-07-23 01:01:38 +00006568 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006569}
6570
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006571/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006572/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006573/// arguments in block literals. When passed as arguments, passing 'A*' where
6574/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6575/// not OK. For the return type, the opposite is not OK.
6576bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6577 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006578 const ObjCObjectPointerType *RHSOPT,
6579 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006580 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006581 return true;
6582
6583 if (LHSOPT->isObjCBuiltinType()) {
6584 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6585 }
6586
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006587 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006588 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6589 QualType(RHSOPT,0),
6590 false);
6591
6592 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6593 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6594 if (LHS && RHS) { // We have 2 user-defined types.
6595 if (LHS != RHS) {
6596 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006597 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006598 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006599 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006600 }
6601 else
6602 return true;
6603 }
6604 return false;
6605}
6606
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006607/// getIntersectionOfProtocols - This routine finds the intersection of set
6608/// of protocols inherited from two distinct objective-c pointer objects.
6609/// It is used to build composite qualifier list of the composite type of
6610/// the conditional expression involving two objective-c pointer objects.
6611static
6612void getIntersectionOfProtocols(ASTContext &Context,
6613 const ObjCObjectPointerType *LHSOPT,
6614 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006615 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006616
John McCall8b07ec22010-05-15 11:32:37 +00006617 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6618 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6619 assert(LHS->getInterface() && "LHS must have an interface base");
6620 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006621
6622 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6623 unsigned LHSNumProtocols = LHS->getNumProtocols();
6624 if (LHSNumProtocols > 0)
6625 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6626 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006627 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006628 Context.CollectInheritedProtocols(LHS->getInterface(),
6629 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006630 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6631 LHSInheritedProtocols.end());
6632 }
6633
6634 unsigned RHSNumProtocols = RHS->getNumProtocols();
6635 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006636 ObjCProtocolDecl **RHSProtocols =
6637 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006638 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6639 if (InheritedProtocolSet.count(RHSProtocols[i]))
6640 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006641 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006642 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006643 Context.CollectInheritedProtocols(RHS->getInterface(),
6644 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006645 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6646 RHSInheritedProtocols.begin(),
6647 E = RHSInheritedProtocols.end(); I != E; ++I)
6648 if (InheritedProtocolSet.count((*I)))
6649 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006650 }
6651}
6652
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006653/// areCommonBaseCompatible - Returns common base class of the two classes if
6654/// one found. Note that this is O'2 algorithm. But it will be called as the
6655/// last type comparison in a ?-exp of ObjC pointer types before a
6656/// warning is issued. So, its invokation is extremely rare.
6657QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006658 const ObjCObjectPointerType *Lptr,
6659 const ObjCObjectPointerType *Rptr) {
6660 const ObjCObjectType *LHS = Lptr->getObjectType();
6661 const ObjCObjectType *RHS = Rptr->getObjectType();
6662 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6663 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006664 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006665 return QualType();
6666
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006667 do {
John McCall8b07ec22010-05-15 11:32:37 +00006668 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006669 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006670 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006671 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6672
6673 QualType Result = QualType(LHS, 0);
6674 if (!Protocols.empty())
6675 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6676 Result = getObjCObjectPointerType(Result);
6677 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006678 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006679 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006680
6681 return QualType();
6682}
6683
John McCall8b07ec22010-05-15 11:32:37 +00006684bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6685 const ObjCObjectType *RHS) {
6686 assert(LHS->getInterface() && "LHS is not an interface type");
6687 assert(RHS->getInterface() && "RHS is not an interface type");
6688
Chris Lattner49af6a42008-04-07 06:51:04 +00006689 // Verify that the base decls are compatible: the RHS must be a subclass of
6690 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006691 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006692 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006693
Chris Lattner49af6a42008-04-07 06:51:04 +00006694 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6695 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006696 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006697 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006698
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006699 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6700 // more detailed analysis is required.
6701 if (RHS->getNumProtocols() == 0) {
6702 // OK, if LHS is a superclass of RHS *and*
6703 // this superclass is assignment compatible with LHS.
6704 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006705 bool IsSuperClass =
6706 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6707 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006708 // OK if conversion of LHS to SuperClass results in narrowing of types
6709 // ; i.e., SuperClass may implement at least one of the protocols
6710 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6711 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6712 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006713 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006714 // If super class has no protocols, it is not a match.
6715 if (SuperClassInheritedProtocols.empty())
6716 return false;
6717
6718 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6719 LHSPE = LHS->qual_end();
6720 LHSPI != LHSPE; LHSPI++) {
6721 bool SuperImplementsProtocol = false;
6722 ObjCProtocolDecl *LHSProto = (*LHSPI);
6723
6724 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6725 SuperClassInheritedProtocols.begin(),
6726 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6727 ObjCProtocolDecl *SuperClassProto = (*I);
6728 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6729 SuperImplementsProtocol = true;
6730 break;
6731 }
6732 }
6733 if (!SuperImplementsProtocol)
6734 return false;
6735 }
6736 return true;
6737 }
6738 return false;
6739 }
Mike Stump11289f42009-09-09 15:08:12 +00006740
John McCall8b07ec22010-05-15 11:32:37 +00006741 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6742 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006743 LHSPI != LHSPE; LHSPI++) {
6744 bool RHSImplementsProtocol = false;
6745
6746 // If the RHS doesn't implement the protocol on the left, the types
6747 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006748 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6749 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006750 RHSPI != RHSPE; RHSPI++) {
6751 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006752 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006753 break;
6754 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006755 }
6756 // FIXME: For better diagnostics, consider passing back the protocol name.
6757 if (!RHSImplementsProtocol)
6758 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006759 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006760 // The RHS implements all protocols listed on the LHS.
6761 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006762}
6763
Steve Naroffb7605152009-02-12 17:52:19 +00006764bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6765 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006766 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6767 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006768
Steve Naroff7cae42b2009-07-10 23:34:53 +00006769 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006770 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006771
6772 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6773 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006774}
6775
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006776bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6777 return canAssignObjCInterfaces(
6778 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6779 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6780}
6781
Mike Stump11289f42009-09-09 15:08:12 +00006782/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006783/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006784/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006785/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006786bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6787 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006788 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006789 return hasSameType(LHS, RHS);
6790
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006791 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006792}
6793
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006794bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006795 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006796}
6797
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006798bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6799 return !mergeTypes(LHS, RHS, true).isNull();
6800}
6801
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006802/// mergeTransparentUnionType - if T is a transparent union type and a member
6803/// of T is compatible with SubType, return the merged type, else return
6804/// QualType()
6805QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6806 bool OfBlockPointer,
6807 bool Unqualified) {
6808 if (const RecordType *UT = T->getAsUnionType()) {
6809 RecordDecl *UD = UT->getDecl();
6810 if (UD->hasAttr<TransparentUnionAttr>()) {
6811 for (RecordDecl::field_iterator it = UD->field_begin(),
6812 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006813 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006814 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6815 if (!MT.isNull())
6816 return MT;
6817 }
6818 }
6819 }
6820
6821 return QualType();
6822}
6823
6824/// mergeFunctionArgumentTypes - merge two types which appear as function
6825/// argument types
6826QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6827 bool OfBlockPointer,
6828 bool Unqualified) {
6829 // GNU extension: two types are compatible if they appear as a function
6830 // argument, one of the types is a transparent union type and the other
6831 // type is compatible with a union member
6832 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6833 Unqualified);
6834 if (!lmerge.isNull())
6835 return lmerge;
6836
6837 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6838 Unqualified);
6839 if (!rmerge.isNull())
6840 return rmerge;
6841
6842 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6843}
6844
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006845QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006846 bool OfBlockPointer,
6847 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006848 const FunctionType *lbase = lhs->getAs<FunctionType>();
6849 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006850 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6851 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006852 bool allLTypes = true;
6853 bool allRTypes = true;
6854
6855 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006856 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006857 if (OfBlockPointer) {
6858 QualType RHS = rbase->getResultType();
6859 QualType LHS = lbase->getResultType();
6860 bool UnqualifiedResult = Unqualified;
6861 if (!UnqualifiedResult)
6862 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006863 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006864 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006865 else
John McCall8c6b56f2010-12-15 01:06:38 +00006866 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6867 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006868 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006869
6870 if (Unqualified)
6871 retType = retType.getUnqualifiedType();
6872
6873 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6874 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6875 if (Unqualified) {
6876 LRetType = LRetType.getUnqualifiedType();
6877 RRetType = RRetType.getUnqualifiedType();
6878 }
6879
6880 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006881 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006882 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006883 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006884
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006885 // FIXME: double check this
6886 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6887 // rbase->getRegParmAttr() != 0 &&
6888 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006889 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6890 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006891
Douglas Gregor8c940862010-01-18 17:14:39 +00006892 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00006893 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00006894 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006895
John McCall8c6b56f2010-12-15 01:06:38 +00006896 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006897 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6898 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006899 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6900 return QualType();
6901
John McCall31168b02011-06-15 23:02:42 +00006902 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6903 return QualType();
6904
John McCall8c6b56f2010-12-15 01:06:38 +00006905 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6906 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006907
Rafael Espindola8778c282012-11-29 16:09:03 +00006908 if (lbaseInfo.getNoReturn() != NoReturn)
6909 allLTypes = false;
6910 if (rbaseInfo.getNoReturn() != NoReturn)
6911 allRTypes = false;
6912
John McCall31168b02011-06-15 23:02:42 +00006913 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006914
Eli Friedman47f77112008-08-22 00:56:42 +00006915 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006916 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6917 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006918 unsigned lproto_nargs = lproto->getNumArgs();
6919 unsigned rproto_nargs = rproto->getNumArgs();
6920
6921 // Compatible functions must have the same number of arguments
6922 if (lproto_nargs != rproto_nargs)
6923 return QualType();
6924
6925 // Variadic and non-variadic functions aren't compatible
6926 if (lproto->isVariadic() != rproto->isVariadic())
6927 return QualType();
6928
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006929 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6930 return QualType();
6931
Fariborz Jahanian97676972011-09-28 21:52:05 +00006932 if (LangOpts.ObjCAutoRefCount &&
6933 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6934 return QualType();
6935
Eli Friedman47f77112008-08-22 00:56:42 +00006936 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006937 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00006938 for (unsigned i = 0; i < lproto_nargs; i++) {
6939 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6940 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006941 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6942 OfBlockPointer,
6943 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006944 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006945
6946 if (Unqualified)
6947 argtype = argtype.getUnqualifiedType();
6948
Eli Friedman47f77112008-08-22 00:56:42 +00006949 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006950 if (Unqualified) {
6951 largtype = largtype.getUnqualifiedType();
6952 rargtype = rargtype.getUnqualifiedType();
6953 }
6954
Chris Lattner465fa322008-10-05 17:34:18 +00006955 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6956 allLTypes = false;
6957 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6958 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006959 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006960
Eli Friedman47f77112008-08-22 00:56:42 +00006961 if (allLTypes) return lhs;
6962 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006963
6964 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6965 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00006966 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006967 }
6968
6969 if (lproto) allRTypes = false;
6970 if (rproto) allLTypes = false;
6971
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006972 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006973 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006974 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006975 if (proto->isVariadic()) return QualType();
6976 // Check that the types are compatible with the types that
6977 // would result from default argument promotions (C99 6.7.5.3p15).
6978 // The only types actually affected are promotable integer
6979 // types and floats, which would be passed as a different
6980 // type depending on whether the prototype is visible.
6981 unsigned proto_nargs = proto->getNumArgs();
6982 for (unsigned i = 0; i < proto_nargs; ++i) {
6983 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00006984
Eli Friedman448ce402012-08-30 00:44:15 +00006985 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00006986 // to pass enum values.
Eli Friedman448ce402012-08-30 00:44:15 +00006987 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
6988 argTy = Enum->getDecl()->getIntegerType();
6989 if (argTy.isNull())
6990 return QualType();
6991 }
Douglas Gregor2973d402010-02-03 19:27:29 +00006992
Eli Friedman47f77112008-08-22 00:56:42 +00006993 if (argTy->isPromotableIntegerType() ||
6994 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6995 return QualType();
6996 }
6997
6998 if (allLTypes) return lhs;
6999 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007000
7001 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7002 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007003 return getFunctionType(retType,
7004 ArrayRef<QualType>(proto->arg_type_begin(),
7005 proto->getNumArgs()),
7006 EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007007 }
7008
7009 if (allLTypes) return lhs;
7010 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007011 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007012}
7013
John McCall433c2e62013-03-21 00:10:07 +00007014/// Given that we have an enum type and a non-enum type, try to merge them.
7015static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7016 QualType other, bool isBlockReturnType) {
7017 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7018 // a signed integer type, or an unsigned integer type.
7019 // Compatibility is based on the underlying type, not the promotion
7020 // type.
7021 QualType underlyingType = ET->getDecl()->getIntegerType();
7022 if (underlyingType.isNull()) return QualType();
7023 if (Context.hasSameType(underlyingType, other))
7024 return other;
7025
7026 // In block return types, we're more permissive and accept any
7027 // integral type of the same size.
7028 if (isBlockReturnType && other->isIntegerType() &&
7029 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7030 return other;
7031
7032 return QualType();
7033}
7034
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007035QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007036 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007037 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007038 // C++ [expr]: If an expression initially has the type "reference to T", the
7039 // type is adjusted to "T" prior to any further analysis, the expression
7040 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007041 // expression is an lvalue unless the reference is an rvalue reference and
7042 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007043 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7044 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007045
7046 if (Unqualified) {
7047 LHS = LHS.getUnqualifiedType();
7048 RHS = RHS.getUnqualifiedType();
7049 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007050
Eli Friedman47f77112008-08-22 00:56:42 +00007051 QualType LHSCan = getCanonicalType(LHS),
7052 RHSCan = getCanonicalType(RHS);
7053
7054 // If two types are identical, they are compatible.
7055 if (LHSCan == RHSCan)
7056 return LHS;
7057
John McCall8ccfcb52009-09-24 19:53:00 +00007058 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007059 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7060 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007061 if (LQuals != RQuals) {
7062 // If any of these qualifiers are different, we have a type
7063 // mismatch.
7064 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007065 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7066 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007067 return QualType();
7068
7069 // Exactly one GC qualifier difference is allowed: __strong is
7070 // okay if the other type has no GC qualifier but is an Objective
7071 // C object pointer (i.e. implicitly strong by default). We fix
7072 // this by pretending that the unqualified type was actually
7073 // qualified __strong.
7074 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7075 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7076 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7077
7078 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7079 return QualType();
7080
7081 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7082 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7083 }
7084 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7085 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7086 }
Eli Friedman47f77112008-08-22 00:56:42 +00007087 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007088 }
7089
7090 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007091
Eli Friedmandcca6332009-06-01 01:22:52 +00007092 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7093 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007094
Chris Lattnerfd652912008-01-14 05:45:46 +00007095 // We want to consider the two function types to be the same for these
7096 // comparisons, just force one to the other.
7097 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7098 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007099
7100 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007101 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7102 LHSClass = Type::ConstantArray;
7103 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7104 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007105
John McCall8b07ec22010-05-15 11:32:37 +00007106 // ObjCInterfaces are just specialized ObjCObjects.
7107 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7108 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7109
Nate Begemance4d7fc2008-04-18 23:10:10 +00007110 // Canonicalize ExtVector -> Vector.
7111 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7112 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007113
Chris Lattner95554662008-04-07 05:43:21 +00007114 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007115 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007116 // Note that we only have special rules for turning block enum
7117 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007118 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007119 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007120 }
John McCall9dd450b2009-09-21 23:43:11 +00007121 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007122 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007123 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007124 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007125 if (OfBlockPointer && !BlockReturnType) {
7126 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7127 return LHS;
7128 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7129 return RHS;
7130 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007131
Eli Friedman47f77112008-08-22 00:56:42 +00007132 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007133 }
Eli Friedman47f77112008-08-22 00:56:42 +00007134
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007135 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007136 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007137#define TYPE(Class, Base)
7138#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007139#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007140#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7141#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7142#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007143 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007144
Richard Smith27d807c2013-04-30 13:56:41 +00007145 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007146 case Type::LValueReference:
7147 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007148 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007149 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007150
John McCall8b07ec22010-05-15 11:32:37 +00007151 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007152 case Type::IncompleteArray:
7153 case Type::VariableArray:
7154 case Type::FunctionProto:
7155 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007156 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007157
Chris Lattnerfd652912008-01-14 05:45:46 +00007158 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007159 {
7160 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007161 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7162 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007163 if (Unqualified) {
7164 LHSPointee = LHSPointee.getUnqualifiedType();
7165 RHSPointee = RHSPointee.getUnqualifiedType();
7166 }
7167 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7168 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007169 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007170 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007171 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007172 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007173 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007174 return getPointerType(ResultType);
7175 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007176 case Type::BlockPointer:
7177 {
7178 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007179 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7180 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007181 if (Unqualified) {
7182 LHSPointee = LHSPointee.getUnqualifiedType();
7183 RHSPointee = RHSPointee.getUnqualifiedType();
7184 }
7185 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7186 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007187 if (ResultType.isNull()) return QualType();
7188 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7189 return LHS;
7190 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7191 return RHS;
7192 return getBlockPointerType(ResultType);
7193 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007194 case Type::Atomic:
7195 {
7196 // Merge two pointer types, while trying to preserve typedef info
7197 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7198 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7199 if (Unqualified) {
7200 LHSValue = LHSValue.getUnqualifiedType();
7201 RHSValue = RHSValue.getUnqualifiedType();
7202 }
7203 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7204 Unqualified);
7205 if (ResultType.isNull()) return QualType();
7206 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7207 return LHS;
7208 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7209 return RHS;
7210 return getAtomicType(ResultType);
7211 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007212 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007213 {
7214 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7215 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7216 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7217 return QualType();
7218
7219 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7220 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007221 if (Unqualified) {
7222 LHSElem = LHSElem.getUnqualifiedType();
7223 RHSElem = RHSElem.getUnqualifiedType();
7224 }
7225
7226 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007227 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007228 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7229 return LHS;
7230 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7231 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007232 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7233 ArrayType::ArraySizeModifier(), 0);
7234 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7235 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007236 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7237 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007238 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7239 return LHS;
7240 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7241 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007242 if (LVAT) {
7243 // FIXME: This isn't correct! But tricky to implement because
7244 // the array's size has to be the size of LHS, but the type
7245 // has to be different.
7246 return LHS;
7247 }
7248 if (RVAT) {
7249 // FIXME: This isn't correct! But tricky to implement because
7250 // the array's size has to be the size of RHS, but the type
7251 // has to be different.
7252 return RHS;
7253 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007254 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7255 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007256 return getIncompleteArrayType(ResultType,
7257 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007258 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007259 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007260 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007261 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007262 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007263 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007264 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007265 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007266 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007267 case Type::Complex:
7268 // Distinct complex types are incompatible.
7269 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007270 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007271 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007272 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7273 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007274 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007275 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007276 case Type::ObjCObject: {
7277 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007278 // FIXME: This should be type compatibility, e.g. whether
7279 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007280 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7281 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7282 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007283 return LHS;
7284
Eli Friedman47f77112008-08-22 00:56:42 +00007285 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007286 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007287 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007288 if (OfBlockPointer) {
7289 if (canAssignObjCInterfacesInBlockPointer(
7290 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007291 RHS->getAs<ObjCObjectPointerType>(),
7292 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007293 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007294 return QualType();
7295 }
John McCall9dd450b2009-09-21 23:43:11 +00007296 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7297 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007298 return LHS;
7299
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007300 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007301 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007302 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007303
David Blaikie8a40f702012-01-17 06:56:22 +00007304 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007305}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007306
Fariborz Jahanian97676972011-09-28 21:52:05 +00007307bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7308 const FunctionProtoType *FromFunctionType,
7309 const FunctionProtoType *ToFunctionType) {
7310 if (FromFunctionType->hasAnyConsumedArgs() !=
7311 ToFunctionType->hasAnyConsumedArgs())
7312 return false;
7313 FunctionProtoType::ExtProtoInfo FromEPI =
7314 FromFunctionType->getExtProtoInfo();
7315 FunctionProtoType::ExtProtoInfo ToEPI =
7316 ToFunctionType->getExtProtoInfo();
7317 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
7318 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
7319 ArgIdx != NumArgs; ++ArgIdx) {
7320 if (FromEPI.ConsumedArguments[ArgIdx] !=
7321 ToEPI.ConsumedArguments[ArgIdx])
7322 return false;
7323 }
7324 return true;
7325}
7326
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007327/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7328/// 'RHS' attributes and returns the merged version; including for function
7329/// return types.
7330QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7331 QualType LHSCan = getCanonicalType(LHS),
7332 RHSCan = getCanonicalType(RHS);
7333 // If two types are identical, they are compatible.
7334 if (LHSCan == RHSCan)
7335 return LHS;
7336 if (RHSCan->isFunctionType()) {
7337 if (!LHSCan->isFunctionType())
7338 return QualType();
7339 QualType OldReturnType =
7340 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7341 QualType NewReturnType =
7342 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7343 QualType ResReturnType =
7344 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7345 if (ResReturnType.isNull())
7346 return QualType();
7347 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7348 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7349 // In either case, use OldReturnType to build the new function type.
7350 const FunctionType *F = LHS->getAs<FunctionType>();
7351 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007352 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7353 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007354 QualType ResultType
Jordan Rose5c382722013-03-08 21:51:21 +00007355 = getFunctionType(OldReturnType,
7356 ArrayRef<QualType>(FPT->arg_type_begin(),
7357 FPT->getNumArgs()),
7358 EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007359 return ResultType;
7360 }
7361 }
7362 return QualType();
7363 }
7364
7365 // If the qualifiers are different, the types can still be merged.
7366 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7367 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7368 if (LQuals != RQuals) {
7369 // If any of these qualifiers are different, we have a type mismatch.
7370 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7371 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7372 return QualType();
7373
7374 // Exactly one GC qualifier difference is allowed: __strong is
7375 // okay if the other type has no GC qualifier but is an Objective
7376 // C object pointer (i.e. implicitly strong by default). We fix
7377 // this by pretending that the unqualified type was actually
7378 // qualified __strong.
7379 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7380 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7381 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7382
7383 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7384 return QualType();
7385
7386 if (GC_L == Qualifiers::Strong)
7387 return LHS;
7388 if (GC_R == Qualifiers::Strong)
7389 return RHS;
7390 return QualType();
7391 }
7392
7393 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7394 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7395 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7396 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7397 if (ResQT == LHSBaseQT)
7398 return LHS;
7399 if (ResQT == RHSBaseQT)
7400 return RHS;
7401 }
7402 return QualType();
7403}
7404
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007405//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007406// Integer Predicates
7407//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007408
Jay Foad39c79802011-01-12 09:06:06 +00007409unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00007410 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00007411 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007412 if (T->isBooleanType())
7413 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007414 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007415 return (unsigned)getTypeSize(T);
7416}
7417
Abramo Bagnara13640492012-09-09 10:21:24 +00007418QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007419 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007420
7421 // Turn <4 x signed int> -> <4 x unsigned int>
7422 if (const VectorType *VTy = T->getAs<VectorType>())
7423 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007424 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007425
7426 // For enums, we return the unsigned version of the base type.
7427 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007428 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007429
7430 const BuiltinType *BTy = T->getAs<BuiltinType>();
7431 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007432 switch (BTy->getKind()) {
7433 case BuiltinType::Char_S:
7434 case BuiltinType::SChar:
7435 return UnsignedCharTy;
7436 case BuiltinType::Short:
7437 return UnsignedShortTy;
7438 case BuiltinType::Int:
7439 return UnsignedIntTy;
7440 case BuiltinType::Long:
7441 return UnsignedLongTy;
7442 case BuiltinType::LongLong:
7443 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007444 case BuiltinType::Int128:
7445 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007446 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007447 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007448 }
7449}
7450
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007451ASTMutationListener::~ASTMutationListener() { }
7452
Chris Lattnerecd79c62009-06-14 00:45:47 +00007453
7454//===----------------------------------------------------------------------===//
7455// Builtin Type Computation
7456//===----------------------------------------------------------------------===//
7457
7458/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007459/// pointer over the consumed characters. This returns the resultant type. If
7460/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7461/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7462/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007463///
7464/// RequiresICE is filled in on return to indicate whether the value is required
7465/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007466static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007467 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007468 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007469 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007470 // Modifiers.
7471 int HowLong = 0;
7472 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007473 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007474
Chris Lattnerdc226c22010-10-01 22:42:38 +00007475 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007476 bool Done = false;
7477 while (!Done) {
7478 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007479 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007480 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007481 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007482 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007483 case 'S':
7484 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7485 assert(!Signed && "Can't use 'S' modifier multiple times!");
7486 Signed = true;
7487 break;
7488 case 'U':
7489 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7490 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7491 Unsigned = true;
7492 break;
7493 case 'L':
7494 assert(HowLong <= 2 && "Can't have LLLL modifier");
7495 ++HowLong;
7496 break;
7497 }
7498 }
7499
7500 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007501
Chris Lattnerecd79c62009-06-14 00:45:47 +00007502 // Read the base type.
7503 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007504 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007505 case 'v':
7506 assert(HowLong == 0 && !Signed && !Unsigned &&
7507 "Bad modifiers used with 'v'!");
7508 Type = Context.VoidTy;
7509 break;
7510 case 'f':
7511 assert(HowLong == 0 && !Signed && !Unsigned &&
7512 "Bad modifiers used with 'f'!");
7513 Type = Context.FloatTy;
7514 break;
7515 case 'd':
7516 assert(HowLong < 2 && !Signed && !Unsigned &&
7517 "Bad modifiers used with 'd'!");
7518 if (HowLong)
7519 Type = Context.LongDoubleTy;
7520 else
7521 Type = Context.DoubleTy;
7522 break;
7523 case 's':
7524 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7525 if (Unsigned)
7526 Type = Context.UnsignedShortTy;
7527 else
7528 Type = Context.ShortTy;
7529 break;
7530 case 'i':
7531 if (HowLong == 3)
7532 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7533 else if (HowLong == 2)
7534 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7535 else if (HowLong == 1)
7536 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7537 else
7538 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7539 break;
7540 case 'c':
7541 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7542 if (Signed)
7543 Type = Context.SignedCharTy;
7544 else if (Unsigned)
7545 Type = Context.UnsignedCharTy;
7546 else
7547 Type = Context.CharTy;
7548 break;
7549 case 'b': // boolean
7550 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7551 Type = Context.BoolTy;
7552 break;
7553 case 'z': // size_t.
7554 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7555 Type = Context.getSizeType();
7556 break;
7557 case 'F':
7558 Type = Context.getCFConstantStringType();
7559 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007560 case 'G':
7561 Type = Context.getObjCIdType();
7562 break;
7563 case 'H':
7564 Type = Context.getObjCSelType();
7565 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007566 case 'M':
7567 Type = Context.getObjCSuperType();
7568 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007569 case 'a':
7570 Type = Context.getBuiltinVaListType();
7571 assert(!Type.isNull() && "builtin va list type not initialized!");
7572 break;
7573 case 'A':
7574 // This is a "reference" to a va_list; however, what exactly
7575 // this means depends on how va_list is defined. There are two
7576 // different kinds of va_list: ones passed by value, and ones
7577 // passed by reference. An example of a by-value va_list is
7578 // x86, where va_list is a char*. An example of by-ref va_list
7579 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7580 // we want this argument to be a char*&; for x86-64, we want
7581 // it to be a __va_list_tag*.
7582 Type = Context.getBuiltinVaListType();
7583 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007584 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007585 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007586 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007587 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007588 break;
7589 case 'V': {
7590 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007591 unsigned NumElements = strtoul(Str, &End, 10);
7592 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007593 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007594
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007595 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7596 RequiresICE, false);
7597 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007598
7599 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007600 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007601 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007602 break;
7603 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007604 case 'E': {
7605 char *End;
7606
7607 unsigned NumElements = strtoul(Str, &End, 10);
7608 assert(End != Str && "Missing vector size");
7609
7610 Str = End;
7611
7612 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7613 false);
7614 Type = Context.getExtVectorType(ElementType, NumElements);
7615 break;
7616 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007617 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007618 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7619 false);
7620 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007621 Type = Context.getComplexType(ElementType);
7622 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007623 }
7624 case 'Y' : {
7625 Type = Context.getPointerDiffType();
7626 break;
7627 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007628 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007629 Type = Context.getFILEType();
7630 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007631 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007632 return QualType();
7633 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007634 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007635 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007636 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007637 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007638 else
7639 Type = Context.getjmp_bufType();
7640
Mike Stump2adb4da2009-07-28 23:47:15 +00007641 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007642 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007643 return QualType();
7644 }
7645 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007646 case 'K':
7647 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7648 Type = Context.getucontext_tType();
7649
7650 if (Type.isNull()) {
7651 Error = ASTContext::GE_Missing_ucontext;
7652 return QualType();
7653 }
7654 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007655 case 'p':
7656 Type = Context.getProcessIDType();
7657 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007658 }
Mike Stump11289f42009-09-09 15:08:12 +00007659
Chris Lattnerdc226c22010-10-01 22:42:38 +00007660 // If there are modifiers and if we're allowed to parse them, go for it.
7661 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007662 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007663 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007664 default: Done = true; --Str; break;
7665 case '*':
7666 case '&': {
7667 // Both pointers and references can have their pointee types
7668 // qualified with an address space.
7669 char *End;
7670 unsigned AddrSpace = strtoul(Str, &End, 10);
7671 if (End != Str && AddrSpace != 0) {
7672 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7673 Str = End;
7674 }
7675 if (c == '*')
7676 Type = Context.getPointerType(Type);
7677 else
7678 Type = Context.getLValueReferenceType(Type);
7679 break;
7680 }
7681 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7682 case 'C':
7683 Type = Type.withConst();
7684 break;
7685 case 'D':
7686 Type = Context.getVolatileType(Type);
7687 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007688 case 'R':
7689 Type = Type.withRestrict();
7690 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007691 }
7692 }
Chris Lattner84733392010-10-01 07:13:18 +00007693
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007694 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007695 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007696
Chris Lattnerecd79c62009-06-14 00:45:47 +00007697 return Type;
7698}
7699
7700/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007701QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007702 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007703 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007704 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007705
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007706 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007707
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007708 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007709 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007710 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7711 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007712 if (Error != GE_None)
7713 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007714
7715 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7716
Chris Lattnerecd79c62009-06-14 00:45:47 +00007717 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007718 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007719 if (Error != GE_None)
7720 return QualType();
7721
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007722 // If this argument is required to be an IntegerConstantExpression and the
7723 // caller cares, fill in the bitmask we return.
7724 if (RequiresICE && IntegerConstantArgs)
7725 *IntegerConstantArgs |= 1 << ArgTypes.size();
7726
Chris Lattnerecd79c62009-06-14 00:45:47 +00007727 // Do array -> pointer decay. The builtin should use the decayed type.
7728 if (Ty->isArrayType())
7729 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007730
Chris Lattnerecd79c62009-06-14 00:45:47 +00007731 ArgTypes.push_back(Ty);
7732 }
7733
7734 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7735 "'.' should only occur at end of builtin type list!");
7736
John McCall991eb4b2010-12-21 00:44:39 +00007737 FunctionType::ExtInfo EI;
7738 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7739
7740 bool Variadic = (TypeStr[0] == '.');
7741
7742 // We really shouldn't be making a no-proto type here, especially in C++.
7743 if (ArgTypes.empty() && Variadic)
7744 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007745
John McCalldb40c7f2010-12-14 08:05:40 +00007746 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007747 EPI.ExtInfo = EI;
7748 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007749
Jordan Rose5c382722013-03-08 21:51:21 +00007750 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007751}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007752
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007753GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
7754 GVALinkage External = GVA_StrongExternal;
7755
7756 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007757 switch (L) {
7758 case NoLinkage:
7759 case InternalLinkage:
7760 case UniqueExternalLinkage:
7761 return GVA_Internal;
7762
7763 case ExternalLinkage:
7764 switch (FD->getTemplateSpecializationKind()) {
7765 case TSK_Undeclared:
7766 case TSK_ExplicitSpecialization:
7767 External = GVA_StrongExternal;
7768 break;
7769
7770 case TSK_ExplicitInstantiationDefinition:
7771 return GVA_ExplicitTemplateInstantiation;
7772
7773 case TSK_ExplicitInstantiationDeclaration:
7774 case TSK_ImplicitInstantiation:
7775 External = GVA_TemplateInstantiation;
7776 break;
7777 }
7778 }
7779
7780 if (!FD->isInlined())
7781 return External;
7782
David Blaikiebbafb8a2012-03-11 07:00:24 +00007783 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007784 // GNU or C99 inline semantics. Determine whether this symbol should be
7785 // externally visible.
7786 if (FD->isInlineDefinitionExternallyVisible())
7787 return External;
7788
7789 // C99 inline semantics, where the symbol is not externally visible.
7790 return GVA_C99Inline;
7791 }
7792
7793 // C++0x [temp.explicit]p9:
7794 // [ Note: The intent is that an inline function that is the subject of
7795 // an explicit instantiation declaration will still be implicitly
7796 // instantiated when used so that the body can be considered for
7797 // inlining, but that no out-of-line copy of the inline function would be
7798 // generated in the translation unit. -- end note ]
7799 if (FD->getTemplateSpecializationKind()
7800 == TSK_ExplicitInstantiationDeclaration)
7801 return GVA_C99Inline;
7802
7803 return GVA_CXXInline;
7804}
7805
7806GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7807 // If this is a static data member, compute the kind of template
7808 // specialization. Otherwise, this variable is not part of a
7809 // template.
7810 TemplateSpecializationKind TSK = TSK_Undeclared;
7811 if (VD->isStaticDataMember())
7812 TSK = VD->getTemplateSpecializationKind();
7813
7814 Linkage L = VD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007815
7816 switch (L) {
7817 case NoLinkage:
7818 case InternalLinkage:
7819 case UniqueExternalLinkage:
7820 return GVA_Internal;
7821
7822 case ExternalLinkage:
7823 switch (TSK) {
7824 case TSK_Undeclared:
7825 case TSK_ExplicitSpecialization:
7826 return GVA_StrongExternal;
7827
7828 case TSK_ExplicitInstantiationDeclaration:
7829 llvm_unreachable("Variable should not be instantiated");
7830 // Fall through to treat this like any other instantiation.
7831
7832 case TSK_ExplicitInstantiationDefinition:
7833 return GVA_ExplicitTemplateInstantiation;
7834
7835 case TSK_ImplicitInstantiation:
7836 return GVA_TemplateInstantiation;
7837 }
7838 }
7839
David Blaikie8a40f702012-01-17 06:56:22 +00007840 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007841}
7842
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007843bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007844 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7845 if (!VD->isFileVarDecl())
7846 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00007847 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7848 // We never need to emit an uninstantiated function template.
7849 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7850 return false;
7851 } else
7852 return false;
7853
7854 // If this is a member of a class template, we do not need to emit it.
7855 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007856 return false;
7857
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007858 // Weak references don't produce any output by themselves.
7859 if (D->hasAttr<WeakRefAttr>())
7860 return false;
7861
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007862 // Aliases and used decls are required.
7863 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7864 return true;
7865
7866 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7867 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007868 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007869 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007870
7871 // Constructors and destructors are required.
7872 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7873 return true;
7874
John McCall6bd2a892013-01-25 22:31:03 +00007875 // The key function for a class is required. This rule only comes
7876 // into play when inline functions can be key functions, though.
7877 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7878 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7879 const CXXRecordDecl *RD = MD->getParent();
7880 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7881 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7882 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7883 return true;
7884 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007885 }
7886 }
7887
7888 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7889
7890 // static, static inline, always_inline, and extern inline functions can
7891 // always be deferred. Normal inline functions can be deferred in C99/C++.
7892 // Implicit template instantiations can also be deferred in C++.
7893 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007894 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007895 return false;
7896 return true;
7897 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007898
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007899 const VarDecl *VD = cast<VarDecl>(D);
7900 assert(VD->isFileVarDecl() && "Expected file scoped var");
7901
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007902 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7903 return false;
7904
Richard Smitha0e5e542012-11-12 21:38:00 +00007905 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007906 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smitha0e5e542012-11-12 21:38:00 +00007907 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7908 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007909
Richard Smitha0e5e542012-11-12 21:38:00 +00007910 // Variables that have destruction with side-effects are required.
7911 if (VD->getType().isDestructedType())
7912 return true;
7913
7914 // Variables that have initialization with side-effects are required.
7915 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7916 return true;
7917
7918 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007919}
Charles Davis53c59df2010-08-16 03:33:14 +00007920
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007921CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davis99202b32010-11-09 18:04:24 +00007922 // Pass through to the C++ ABI object
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007923 return ABI->getDefaultMethodCallConv(isVariadic);
7924}
7925
7926CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
John McCall359b8852013-01-25 22:30:49 +00007927 if (CC == CC_C && !LangOpts.MRTD &&
7928 getTargetInfo().getCXXABI().isMemberFunctionCCDefault())
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007929 return CC_Default;
7930 return CC;
Charles Davis99202b32010-11-09 18:04:24 +00007931}
7932
Jay Foad39c79802011-01-12 09:06:06 +00007933bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007934 // Pass through to the C++ ABI object
7935 return ABI->isNearlyEmpty(RD);
7936}
7937
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007938MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00007939 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00007940 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00007941 case TargetCXXABI::GenericItanium:
7942 case TargetCXXABI::GenericARM:
7943 case TargetCXXABI::iOS:
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007944 return createItaniumMangleContext(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00007945 case TargetCXXABI::Microsoft:
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007946 return createMicrosoftMangleContext(*this, getDiagnostics());
7947 }
David Blaikie83d382b2011-09-23 05:06:16 +00007948 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007949}
7950
Charles Davis53c59df2010-08-16 03:33:14 +00007951CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007952
7953size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00007954 return ASTRecordLayouts.getMemorySize()
7955 + llvm::capacity_in_bytes(ObjCLayouts)
7956 + llvm::capacity_in_bytes(KeyFunctions)
7957 + llvm::capacity_in_bytes(ObjCImpls)
7958 + llvm::capacity_in_bytes(BlockVarCopyInits)
7959 + llvm::capacity_in_bytes(DeclAttrs)
7960 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7961 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7962 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7963 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7964 + llvm::capacity_in_bytes(OverriddenMethods)
7965 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007966 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00007967 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007968}
Ted Kremenek540017e2011-10-06 05:00:56 +00007969
David Blaikie095deba2012-11-14 01:52:05 +00007970void ASTContext::addUnnamedTag(const TagDecl *Tag) {
7971 // FIXME: This mangling should be applied to function local classes too
7972 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl() ||
7973 !isa<CXXRecordDecl>(Tag->getParent()) || Tag->getLinkage() != ExternalLinkage)
7974 return;
7975
7976 std::pair<llvm::DenseMap<const DeclContext *, unsigned>::iterator, bool> P =
7977 UnnamedMangleContexts.insert(std::make_pair(Tag->getParent(), 0));
7978 UnnamedMangleNumbers.insert(std::make_pair(Tag, P.first->second++));
7979}
7980
7981int ASTContext::getUnnamedTagManglingNumber(const TagDecl *Tag) const {
7982 llvm::DenseMap<const TagDecl *, unsigned>::const_iterator I =
7983 UnnamedMangleNumbers.find(Tag);
7984 return I != UnnamedMangleNumbers.end() ? I->second : -1;
7985}
7986
Douglas Gregor63798542012-02-20 19:44:39 +00007987unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7988 CXXRecordDecl *Lambda = CallOperator->getParent();
7989 return LambdaMangleContexts[Lambda->getDeclContext()]
7990 .getManglingNumber(CallOperator);
7991}
7992
7993
Ted Kremenek540017e2011-10-06 05:00:56 +00007994void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7995 ParamIndices[D] = index;
7996}
7997
7998unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7999 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8000 assert(I != ParamIndices.end() &&
8001 "ParmIndices lacks entry set by ParmVarDecl");
8002 return I->second;
8003}