blob: 21a16a6d98267ec112979783f4ffcabb9a4cf824 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000015#include "CXXABI.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000016#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000018#include "clang/AST/CharUnits.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000019#include "clang/AST/Comment.h"
Dmitri Gribenkoaa580812012-08-09 00:03:17 +000020#include "clang/AST/CommentCommandTraits.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000021#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000022#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000023#include "clang/AST/DeclTemplate.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000024#include "clang/AST/Expr.h"
John McCallea1471e2010-05-20 01:18:31 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000026#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000027#include "clang/AST/Mangle.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000028#include "clang/AST/RecordLayout.h"
29#include "clang/AST/TypeLoc.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000030#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000031#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000032#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000033#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000034#include "llvm/ADT/StringExtras.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000035#include "llvm/Support/Capacity.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000036#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000037#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +000038#include <map>
Anders Carlsson29445a02009-07-18 21:19:52 +000039
Reid Spencer5f016e22007-07-11 17:01:13 +000040using namespace clang;
41
Douglas Gregor18274032010-07-03 00:47:00 +000042unsigned ASTContext::NumImplicitDefaultConstructors;
43unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000044unsigned ASTContext::NumImplicitCopyConstructors;
45unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000046unsigned ASTContext::NumImplicitMoveConstructors;
47unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000048unsigned ASTContext::NumImplicitCopyAssignmentOperators;
49unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000050unsigned ASTContext::NumImplicitMoveAssignmentOperators;
51unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000052unsigned ASTContext::NumImplicitDestructors;
53unsigned ASTContext::NumImplicitDestructorsDeclared;
54
Reid Spencer5f016e22007-07-11 17:01:13 +000055enum FloatingRank {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +000056 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Reid Spencer5f016e22007-07-11 17:01:13 +000057};
58
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000059RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +000060 if (!CommentsLoaded && ExternalSource) {
61 ExternalSource->ReadComments();
62 CommentsLoaded = true;
63 }
64
65 assert(D);
66
Dmitri Gribenkoc3fee352012-06-28 16:19:39 +000067 // User can not attach documentation to implicit declarations.
68 if (D->isImplicit())
69 return NULL;
70
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +000071 // User can not attach documentation to implicit instantiations.
72 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
73 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
74 return NULL;
75 }
76
Dmitri Gribenkodce750b2012-08-20 22:36:31 +000077 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
78 if (VD->isStaticDataMember() &&
79 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
80 return NULL;
81 }
82
83 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
84 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
85 return NULL;
86 }
87
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +000088 if (const ClassTemplateSpecializationDecl *CTSD =
89 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
90 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
91 if (TSK == TSK_ImplicitInstantiation ||
92 TSK == TSK_Undeclared)
93 return NULL;
94 }
95
Dmitri Gribenkodce750b2012-08-20 22:36:31 +000096 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
97 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
98 return NULL;
99 }
Fariborz Jahanian099ecfb2013-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 Gribenkoaa0cd852012-06-20 00:34:58 +0000106 // TODO: handle comments for function parameters properly.
107 if (isa<ParmVarDecl>(D))
108 return NULL;
109
Dmitri Gribenko96b09862012-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 Gribenko811c8202012-07-06 18:19:34 +0000117 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaa0cd852012-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 Gribenkoabd56c82012-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 Gribenko96b09862012-07-31 22:37:06 +0000131 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +0000132 isa<RedeclarableTemplateDecl>(D) ||
133 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000134 DeclLoc = D->getLocStart();
135 else
136 DeclLoc = D->getLocation();
137
Dmitri Gribenkoaa0cd852012-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 Gribenkoaa0cd852012-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 Gribenkoa444f182012-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 Gribenko6fd7d302013-04-10 15:35:17 +0000149 RawComment CommentAtDeclLoc(
150 SourceMgr, SourceRange(DeclLoc), false,
151 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoa444f182012-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 Gribenkoaa0cd852012-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 Gribenko811c8202012-07-06 18:19:34 +0000177 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Dmitri Gribenko9c006762012-07-06 23:27:33 +0000178 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000179 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000180 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaa0cd852012-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 Gribenko811c8202012-07-06 18:19:34 +0000187 return *Comment;
Dmitri Gribenkoaa0cd852012-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 Gribenko811c8202012-07-06 18:19:34 +0000198 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000199 return NULL;
200
201 // Decompose the end of the comment.
202 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000203 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaa0cd852012-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 Gribenko8bdb58a2012-06-27 23:43:37 +0000221 // There should be no other declarations or preprocessor directives between
222 // comment and declaration.
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000223 if (Text.find_first_of(",;{}#@") != StringRef::npos)
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000224 return NULL;
225
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000226 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000227}
228
Dmitri Gribenkoc41ace92012-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 Gribenko2125c902012-08-22 17:44:32 +0000232/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000233const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregorcd81df22012-08-13 16:37:30 +0000234 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000235 // Is this function declaration part of a function template?
Douglas Gregorcd81df22012-08-13 16:37:30 +0000236 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko2125c902012-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 Gregorcd81df22012-08-13 16:37:30 +0000253 }
Dmitri Gribenko2125c902012-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 Gribenkoc41ace92012-08-14 17:17:18 +0000298 return D;
299}
300} // unnamed namespace
301
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000302const RawComment *ASTContext::getRawCommentForAnyRedecl(
303 const Decl *D,
304 const Decl **OriginalDecl) const {
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000305 D = adjustDeclToTemplate(D);
Douglas Gregorcd81df22012-08-13 16:37:30 +0000306
Dmitri Gribenkof50555e2012-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 Gribenko1599eac2012-08-16 18:19:43 +0000313 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
314 if (OriginalDecl)
315 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000316 return Raw.getRaw();
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000317 }
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000318 }
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000319 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000320
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000321 // Search for comments attached to declarations in the redeclaration chain.
322 const RawComment *RC = NULL;
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000323 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkof50555e2012-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 Gribenko1599eac2012-08-16 18:19:43 +0000333 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000334 break;
335 }
336 } else {
337 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000338 OriginalDeclForRC = *I;
Dmitri Gribenkof50555e2012-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 Gribenko1599eac2012-08-16 18:19:43 +0000345 Raw.setOriginalDecl(*I);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000346 RedeclComments[*I] = Raw;
347 if (RC)
348 break;
349 }
350 }
351
Dmitri Gribenko8376f592012-06-28 16:25:36 +0000352 // If we found a comment, it should be a documentation comment.
353 assert(!RC || RC->isDocumentation());
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000354
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000355 if (OriginalDecl)
356 *OriginalDecl = OriginalDeclForRC;
357
Dmitri Gribenkof50555e2012-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 Gribenko1599eac2012-08-16 18:19:43 +0000362 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkof50555e2012-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 Gribenkoaa0cd852012-06-20 00:34:58 +0000372 return RC;
373}
374
Fariborz Jahanianbf967be2012-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 Gregord3297242013-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 Jahanianbf967be2012-10-10 18:34:52 +0000387 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregord3297242013-01-16 23:00:23 +0000388 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000389 ObjCMethod->isInstanceMethod()))
390 Redeclared.push_back(RedeclaredMethod);
391 }
392 }
393}
394
Fariborz Jahanian749ace62012-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 Gribenko19523542012-09-29 11:40:46 +0000409comments::FullComment *ASTContext::getCommentForDecl(
410 const Decl *D,
411 const Preprocessor *PP) const {
Fariborz Jahanianfbff0c42013-05-13 17:27:00 +0000412 if (D->isInvalidDecl())
413 return NULL;
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000414 D = adjustDeclToTemplate(D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000415
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000416 const Decl *Canonical = D->getCanonicalDecl();
417 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
418 ParsedComments.find(Canonical);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000419
420 if (Pos != ParsedComments.end()) {
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000421 if (Canonical != D) {
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000422 comments::FullComment *FC = Pos->second;
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000423 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000424 return CFC;
425 }
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000426 return Pos->second;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000427 }
428
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000429 const Decl *OriginalDecl;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000430
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000431 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000432 if (!RC) {
433 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko1e905da2012-11-03 14:24:57 +0000434 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanianc328d9c2013-01-12 00:28:34 +0000435 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000436 if (OMD && OMD->isPropertyAccessor())
437 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
438 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
439 return cloneFullComment(FC, D);
Fariborz Jahanianc328d9c2013-01-12 00:28:34 +0000440 if (OMD)
Dmitri Gribenko1e905da2012-11-03 14:24:57 +0000441 addRedeclaredMethods(OMD, Overridden);
442 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000443 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
444 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
445 return cloneFullComment(FC, D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000446 }
Fariborz Jahanian4857fdc2013-05-02 15:44:16 +0000447 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +0000448 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000449 // does not have one of its own.
Fariborz Jahanian41170b52013-01-25 22:48:32 +0000450 QualType QT = TD->getUnderlyingType();
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +0000451 if (const TagType *TT = QT->getAs<TagType>())
452 if (const Decl *TD = TT->getDecl())
453 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000454 return cloneFullComment(FC, D);
Fariborz Jahanian41170b52013-01-25 22:48:32 +0000455 }
Fariborz Jahanian622bb4a2013-04-26 20:55:38 +0000456 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
457 while (IC->getSuperClass()) {
458 IC = IC->getSuperClass();
459 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
460 return cloneFullComment(FC, D);
461 }
462 }
463 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
464 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
465 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
466 return cloneFullComment(FC, D);
467 }
468 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
469 if (!(RD = RD->getDefinition()))
470 return NULL;
471 // Check non-virtual bases.
472 for (CXXRecordDecl::base_class_const_iterator I =
473 RD->bases_begin(), E = RD->bases_end(); I != E; ++I) {
Fariborz Jahanian91efca02013-04-26 23:34:36 +0000474 if (I->isVirtual() || (I->getAccessSpecifier() != AS_public))
Fariborz Jahanian622bb4a2013-04-26 20:55:38 +0000475 continue;
476 QualType Ty = I->getType();
477 if (Ty.isNull())
478 continue;
479 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
480 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
481 continue;
482
483 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
484 return cloneFullComment(FC, D);
485 }
486 }
487 // Check virtual bases.
488 for (CXXRecordDecl::base_class_const_iterator I =
489 RD->vbases_begin(), E = RD->vbases_end(); I != E; ++I) {
Fariborz Jahanian91efca02013-04-26 23:34:36 +0000490 if (I->getAccessSpecifier() != AS_public)
491 continue;
Fariborz Jahanian622bb4a2013-04-26 20:55:38 +0000492 QualType Ty = I->getType();
493 if (Ty.isNull())
494 continue;
495 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
496 if (!(VirtualBase= VirtualBase->getDefinition()))
497 continue;
498 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
499 return cloneFullComment(FC, D);
500 }
501 }
502 }
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000503 return NULL;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000504 }
505
Dmitri Gribenko4b41c652012-08-22 18:12:19 +0000506 // If the RawComment was attached to other redeclaration of this Decl, we
507 // should parse the comment in context of that other Decl. This is important
508 // because comments can contain references to parameter names which can be
509 // different across redeclarations.
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000510 if (D != OriginalDecl)
Dmitri Gribenko19523542012-09-29 11:40:46 +0000511 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000512
Dmitri Gribenko19523542012-09-29 11:40:46 +0000513 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000514 ParsedComments[Canonical] = FC;
515 return FC;
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000516}
517
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000518void
519ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
520 TemplateTemplateParmDecl *Parm) {
521 ID.AddInteger(Parm->getDepth());
522 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +0000523 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000524
525 TemplateParameterList *Params = Parm->getTemplateParameters();
526 ID.AddInteger(Params->size());
527 for (TemplateParameterList::const_iterator P = Params->begin(),
528 PEnd = Params->end();
529 P != PEnd; ++P) {
530 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
531 ID.AddInteger(0);
532 ID.AddBoolean(TTP->isParameterPack());
533 continue;
534 }
535
536 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
537 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000538 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000539 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000540 if (NTTP->isExpandedParameterPack()) {
541 ID.AddBoolean(true);
542 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000543 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
544 QualType T = NTTP->getExpansionType(I);
545 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
546 }
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000547 } else
548 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000549 continue;
550 }
551
552 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
553 ID.AddInteger(2);
554 Profile(ID, TTP);
555 }
556}
557
558TemplateTemplateParmDecl *
559ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +0000560 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000561 // Check if we already have a canonical template template parameter.
562 llvm::FoldingSetNodeID ID;
563 CanonicalTemplateTemplateParm::Profile(ID, TTP);
564 void *InsertPos = 0;
565 CanonicalTemplateTemplateParm *Canonical
566 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
567 if (Canonical)
568 return Canonical->getParam();
569
570 // Build a canonical template parameter list.
571 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000572 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000573 CanonParams.reserve(Params->size());
574 for (TemplateParameterList::const_iterator P = Params->begin(),
575 PEnd = Params->end();
576 P != PEnd; ++P) {
577 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
578 CanonParams.push_back(
579 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000580 SourceLocation(),
581 SourceLocation(),
582 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000583 TTP->getIndex(), 0, false,
584 TTP->isParameterPack()));
585 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000586 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
587 QualType T = getCanonicalType(NTTP->getType());
588 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
589 NonTypeTemplateParmDecl *Param;
590 if (NTTP->isExpandedParameterPack()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000591 SmallVector<QualType, 2> ExpandedTypes;
592 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000593 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
594 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
595 ExpandedTInfos.push_back(
596 getTrivialTypeSourceInfo(ExpandedTypes.back()));
597 }
598
599 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000600 SourceLocation(),
601 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000602 NTTP->getDepth(),
603 NTTP->getPosition(), 0,
604 T,
605 TInfo,
606 ExpandedTypes.data(),
607 ExpandedTypes.size(),
608 ExpandedTInfos.data());
609 } else {
610 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000611 SourceLocation(),
612 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000613 NTTP->getDepth(),
614 NTTP->getPosition(), 0,
615 T,
616 NTTP->isParameterPack(),
617 TInfo);
618 }
619 CanonParams.push_back(Param);
620
621 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000622 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
623 cast<TemplateTemplateParmDecl>(*P)));
624 }
625
626 TemplateTemplateParmDecl *CanonTTP
627 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
628 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000629 TTP->getPosition(),
630 TTP->isParameterPack(),
631 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000632 TemplateParameterList::Create(*this, SourceLocation(),
633 SourceLocation(),
634 CanonParams.data(),
635 CanonParams.size(),
636 SourceLocation()));
637
638 // Get the new insert position for the node we care about.
639 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
640 assert(Canonical == 0 && "Shouldn't be in the map!");
641 (void)Canonical;
642
643 // Create the canonical template template parameter entry.
644 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
645 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
646 return CanonTTP;
647}
648
Charles Davis071cc7d2010-08-16 03:33:14 +0000649CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000650 if (!LangOpts.CPlusPlus) return 0;
651
John McCallb8b2c9d2013-01-25 22:30:49 +0000652 switch (T.getCXXABI().getKind()) {
653 case TargetCXXABI::GenericARM:
654 case TargetCXXABI::iOS:
John McCallee79a4c2010-08-21 22:46:04 +0000655 return CreateARMCXXABI(*this);
Tim Northoverc264e162013-01-31 12:13:10 +0000656 case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
John McCallb8b2c9d2013-01-25 22:30:49 +0000657 case TargetCXXABI::GenericItanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000658 return CreateItaniumCXXABI(*this);
John McCallb8b2c9d2013-01-25 22:30:49 +0000659 case TargetCXXABI::Microsoft:
Charles Davis20cf7172010-08-19 02:18:14 +0000660 return CreateMicrosoftCXXABI(*this);
661 }
David Blaikie7530c032012-01-17 06:56:22 +0000662 llvm_unreachable("Invalid CXXABI type!");
Charles Davis071cc7d2010-08-16 03:33:14 +0000663}
664
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000665static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000666 const LangOptions &LOpts) {
667 if (LOpts.FakeAddressSpaceMap) {
668 // The fake address space map must have a distinct entry for each
669 // language-specific address space.
670 static const unsigned FakeAddrSpaceMap[] = {
671 1, // opencl_global
672 2, // opencl_local
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +0000673 3, // opencl_constant
674 4, // cuda_device
675 5, // cuda_constant
676 6 // cuda_shared
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000677 };
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000678 return &FakeAddrSpaceMap;
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000679 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000680 return &T.getAddressSpaceMap();
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000681 }
682}
683
Douglas Gregor3e3cd932011-09-01 20:23:19 +0000684ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000685 const TargetInfo *t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000686 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000687 Builtin::Context &builtins,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000688 unsigned size_reserve,
689 bool DelayInitialization)
690 : FunctionProtoTypes(this_()),
691 TemplateSpecializationTypes(this_()),
692 DependentTemplateSpecializationTypes(this_()),
693 SubstTemplateTemplateParmPacks(this_()),
694 GlobalNestedNameSpecifier(0),
695 Int128Decl(0), UInt128Decl(0),
Meador Ingec5613b22012-06-16 03:34:49 +0000696 BuiltinVaListDecl(0),
Douglas Gregora6ea10e2012-01-17 18:09:05 +0000697 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanian96171302012-08-30 18:49:41 +0000698 BOOLDecl(0),
Douglas Gregore97179c2011-09-08 01:46:34 +0000699 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000700 FILEDecl(0),
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +0000701 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
702 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
703 cudaConfigureCallDecl(0),
Douglas Gregore6649772011-12-03 00:30:27 +0000704 NullTypeSourceInfo(QualType()),
705 FirstLocalImport(), LastLocalImport(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000706 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor30c42402011-09-27 22:38:19 +0000707 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000708 Idents(idents), Selectors(sels),
709 BuiltinInfo(builtins),
710 DeclarationNames(*this),
Douglas Gregor30c42402011-09-27 22:38:19 +0000711 ExternalSource(0), Listener(0),
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000712 Comments(SM), CommentsLoaded(false),
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +0000713 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000714 LastSDM(0, 0),
Fariborz Jahanianf7992132013-01-04 18:45:40 +0000715 UniqueBlockByRefTypeID(0)
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000716{
Mike Stump1eb44332009-09-09 15:08:12 +0000717 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000718 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000719
720 if (!DelayInitialization) {
721 assert(t && "No target supplied for ASTContext initialization");
722 InitBuiltinTypes(*t);
723 }
Daniel Dunbare91593e2008-08-11 04:54:23 +0000724}
725
Reid Spencer5f016e22007-07-11 17:01:13 +0000726ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000727 // Release the DenseMaps associated with DeclContext objects.
728 // FIXME: Is this the ideal solution?
729 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000730
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000731 // Call all of the deallocation functions.
732 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
733 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000734
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000735 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000736 // because they can contain DenseMaps.
737 for (llvm::DenseMap<const ObjCContainerDecl*,
738 const ASTRecordLayout*>::iterator
739 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
740 // Increment in loop to prevent using deallocated memory.
741 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
742 R->Destroy(*this);
743
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000744 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
745 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
746 // Increment in loop to prevent using deallocated memory.
747 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
748 R->Destroy(*this);
749 }
Douglas Gregor63200642010-08-30 16:49:28 +0000750
751 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
752 AEnd = DeclAttrs.end();
753 A != AEnd; ++A)
754 A->second->~AttrVec();
755}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000756
Douglas Gregor00545312010-05-23 18:26:36 +0000757void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
758 Deallocations.push_back(std::make_pair(Callback, Data));
759}
760
Mike Stump1eb44332009-09-09 15:08:12 +0000761void
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000762ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000763 ExternalSource.reset(Source.take());
764}
765
Reid Spencer5f016e22007-07-11 17:01:13 +0000766void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000767 llvm::errs() << "\n*** AST Context Stats:\n";
768 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000769
Douglas Gregordbe833d2009-05-26 14:40:08 +0000770 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000771#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000772#define ABSTRACT_TYPE(Name, Parent)
773#include "clang/AST/TypeNodes.def"
774 0 // Extra
775 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000776
Reid Spencer5f016e22007-07-11 17:01:13 +0000777 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
778 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000779 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000780 }
781
Douglas Gregordbe833d2009-05-26 14:40:08 +0000782 unsigned Idx = 0;
783 unsigned TotalBytes = 0;
784#define TYPE(Name, Parent) \
785 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000786 llvm::errs() << " " << counts[Idx] << " " << #Name \
787 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000788 TotalBytes += counts[Idx] * sizeof(Name##Type); \
789 ++Idx;
790#define ABSTRACT_TYPE(Name, Parent)
791#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000792
Chandler Carruthcd92a652011-07-04 05:32:14 +0000793 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
794
Douglas Gregor4923aa22010-07-02 20:37:36 +0000795 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000796 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
797 << NumImplicitDefaultConstructors
798 << " implicit default constructors created\n";
799 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
800 << NumImplicitCopyConstructors
801 << " implicit copy constructors created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000802 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000803 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
804 << NumImplicitMoveConstructors
805 << " implicit move constructors created\n";
806 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
807 << NumImplicitCopyAssignmentOperators
808 << " implicit copy assignment operators created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000809 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000810 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
811 << NumImplicitMoveAssignmentOperators
812 << " implicit move assignment operators created\n";
813 llvm::errs() << NumImplicitDestructorsDeclared << "/"
814 << NumImplicitDestructors
815 << " implicit destructors created\n";
816
Douglas Gregor2cf26342009-04-09 22:27:44 +0000817 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000818 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000819 ExternalSource->PrintStats();
820 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000821
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000822 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000823}
824
Douglas Gregor772eeae2011-08-12 06:49:56 +0000825TypedefDecl *ASTContext::getInt128Decl() const {
826 if (!Int128Decl) {
827 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
828 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
829 getTranslationUnitDecl(),
830 SourceLocation(),
831 SourceLocation(),
832 &Idents.get("__int128_t"),
833 TInfo);
834 }
835
836 return Int128Decl;
837}
838
839TypedefDecl *ASTContext::getUInt128Decl() const {
840 if (!UInt128Decl) {
841 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
842 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
843 getTranslationUnitDecl(),
844 SourceLocation(),
845 SourceLocation(),
846 &Idents.get("__uint128_t"),
847 TInfo);
848 }
849
850 return UInt128Decl;
851}
Reid Spencer5f016e22007-07-11 17:01:13 +0000852
John McCalle27ec8a2009-10-23 23:03:21 +0000853void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000854 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000855 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000856 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000857}
858
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000859void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
860 assert((!this->Target || this->Target == &Target) &&
861 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000862 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000863
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000864 this->Target = &Target;
865
866 ABI.reset(createCXXABI(Target));
867 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
868
Reid Spencer5f016e22007-07-11 17:01:13 +0000869 // C99 6.2.5p19.
870 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000871
Reid Spencer5f016e22007-07-11 17:01:13 +0000872 // C99 6.2.5p2.
873 InitBuiltinType(BoolTy, BuiltinType::Bool);
874 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000875 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000876 InitBuiltinType(CharTy, BuiltinType::Char_S);
877 else
878 InitBuiltinType(CharTy, BuiltinType::Char_U);
879 // C99 6.2.5p4.
880 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
881 InitBuiltinType(ShortTy, BuiltinType::Short);
882 InitBuiltinType(IntTy, BuiltinType::Int);
883 InitBuiltinType(LongTy, BuiltinType::Long);
884 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000885
Reid Spencer5f016e22007-07-11 17:01:13 +0000886 // C99 6.2.5p6.
887 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
888 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
889 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
890 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
891 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000892
Reid Spencer5f016e22007-07-11 17:01:13 +0000893 // C99 6.2.5p10.
894 InitBuiltinType(FloatTy, BuiltinType::Float);
895 InitBuiltinType(DoubleTy, BuiltinType::Double);
896 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000897
Chris Lattner2df9ced2009-04-30 02:43:43 +0000898 // GNU extension, 128-bit integers.
899 InitBuiltinType(Int128Ty, BuiltinType::Int128);
900 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
901
Hans Wennborg15f92ba2013-05-10 10:08:40 +0000902 // C++ 3.9.1p5
903 if (TargetInfo::isTypeSigned(Target.getWCharType()))
904 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
905 else // -fshort-wchar makes wchar_t be unsigned.
906 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
907 if (LangOpts.CPlusPlus && LangOpts.WChar)
908 WideCharTy = WCharTy;
909 else {
910 // C99 (or C++ using -fno-wchar).
911 WideCharTy = getFromTargetType(Target.getWCharType());
912 }
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000913
James Molloy392da482012-05-04 10:55:22 +0000914 WIntTy = getFromTargetType(Target.getWIntType());
915
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000916 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
917 InitBuiltinType(Char16Ty, BuiltinType::Char16);
918 else // C99
919 Char16Ty = getFromTargetType(Target.getChar16Type());
920
921 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
922 InitBuiltinType(Char32Ty, BuiltinType::Char32);
923 else // C99
924 Char32Ty = getFromTargetType(Target.getChar32Type());
925
Douglas Gregor898574e2008-12-05 23:32:09 +0000926 // Placeholder type for type-dependent expressions whose type is
927 // completely unknown. No code should ever check a type against
928 // DependentTy and users should never see it; however, it is here to
929 // help diagnose failures to properly check for type-dependent
930 // expressions.
931 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000932
John McCall2a984ca2010-10-12 00:20:44 +0000933 // Placeholder type for functions.
934 InitBuiltinType(OverloadTy, BuiltinType::Overload);
935
John McCall864c0412011-04-26 20:42:42 +0000936 // Placeholder type for bound members.
937 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
938
John McCall3c3b7f92011-10-25 17:37:35 +0000939 // Placeholder type for pseudo-objects.
940 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
941
John McCall1de4d4e2011-04-07 08:22:57 +0000942 // "any" type; useful for debugger-like clients.
943 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
944
John McCall0ddaeb92011-10-17 18:09:15 +0000945 // Placeholder type for unbridged ARC casts.
946 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
947
Eli Friedmana6c66ce2012-08-31 00:14:07 +0000948 // Placeholder type for builtin functions.
949 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
950
Reid Spencer5f016e22007-07-11 17:01:13 +0000951 // C99 6.2.5p11.
952 FloatComplexTy = getComplexType(FloatTy);
953 DoubleComplexTy = getComplexType(DoubleTy);
954 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000955
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000956 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000957 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
958 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000959 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeib13621d2012-12-18 14:38:23 +0000960
961 if (LangOpts.OpenCL) {
962 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
963 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
964 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
965 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
966 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
967 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000968
Guy Benyei21f18c42013-02-07 10:55:47 +0000969 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000970 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeib13621d2012-12-18 14:38:23 +0000971 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000972
973 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian93a49942012-04-16 21:03:30 +0000974 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
975 SignedCharTy : BoolTy);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000976
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000977 ObjCConstantStringType = QualType();
Fariborz Jahanianf7992132013-01-04 18:45:40 +0000978
979 ObjCSuperType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000980
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000981 // void * type
982 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000983
984 // nullptr type (C++0x 2.14.7)
985 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000986
987 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
988 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingefb40e3f2012-07-01 15:57:25 +0000989
990 // Builtin type used to help define __builtin_va_list.
991 VaListTagTy = QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000992}
993
David Blaikied6471f72011-09-25 23:23:43 +0000994DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000995 return SourceMgr.getDiagnostics();
996}
997
Douglas Gregor63200642010-08-30 16:49:28 +0000998AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
999 AttrVec *&Result = DeclAttrs[D];
1000 if (!Result) {
1001 void *Mem = Allocate(sizeof(AttrVec));
1002 Result = new (Mem) AttrVec;
1003 }
1004
1005 return *Result;
1006}
1007
1008/// \brief Erase the attributes corresponding to the given declaration.
1009void ASTContext::eraseDeclAttrs(const Decl *D) {
1010 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1011 if (Pos != DeclAttrs.end()) {
1012 Pos->second->~AttrVec();
1013 DeclAttrs.erase(Pos);
1014 }
1015}
1016
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001017MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +00001018ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001019 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +00001020 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +00001021 = InstantiatedFromStaticDataMember.find(Var);
1022 if (Pos == InstantiatedFromStaticDataMember.end())
1023 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001024
Douglas Gregor7caa6822009-07-24 20:34:43 +00001025 return Pos->second;
1026}
1027
Mike Stump1eb44332009-09-09 15:08:12 +00001028void
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001029ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +00001030 TemplateSpecializationKind TSK,
1031 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001032 assert(Inst->isStaticDataMember() && "Not a static data member");
1033 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1034 assert(!InstantiatedFromStaticDataMember[Inst] &&
1035 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001036 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +00001037 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +00001038}
1039
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001040FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1041 const FunctionDecl *FD){
1042 assert(FD && "Specialization is 0");
1043 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +00001044 = ClassScopeSpecializationPattern.find(FD);
1045 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001046 return 0;
1047
1048 return Pos->second;
1049}
1050
1051void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1052 FunctionDecl *Pattern) {
1053 assert(FD && "Specialization is 0");
1054 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +00001055 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001056}
1057
John McCall7ba107a2009-11-18 02:36:19 +00001058NamedDecl *
John McCalled976492009-12-04 22:46:56 +00001059ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +00001060 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +00001061 = InstantiatedFromUsingDecl.find(UUD);
1062 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +00001063 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001064
Anders Carlsson0d8df782009-08-29 19:37:28 +00001065 return Pos->second;
1066}
1067
1068void
John McCalled976492009-12-04 22:46:56 +00001069ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1070 assert((isa<UsingDecl>(Pattern) ||
1071 isa<UnresolvedUsingValueDecl>(Pattern) ||
1072 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1073 "pattern decl is not a using decl");
1074 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1075 InstantiatedFromUsingDecl[Inst] = Pattern;
1076}
1077
1078UsingShadowDecl *
1079ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1080 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1081 = InstantiatedFromUsingShadowDecl.find(Inst);
1082 if (Pos == InstantiatedFromUsingShadowDecl.end())
1083 return 0;
1084
1085 return Pos->second;
1086}
1087
1088void
1089ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1090 UsingShadowDecl *Pattern) {
1091 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1092 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00001093}
1094
Anders Carlssond8b285f2009-09-01 04:26:58 +00001095FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1096 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1097 = InstantiatedFromUnnamedFieldDecl.find(Field);
1098 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1099 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001100
Anders Carlssond8b285f2009-09-01 04:26:58 +00001101 return Pos->second;
1102}
1103
1104void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1105 FieldDecl *Tmpl) {
1106 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1107 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1108 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1109 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +00001110
Anders Carlssond8b285f2009-09-01 04:26:58 +00001111 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1112}
1113
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +00001114bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
1115 const FieldDecl *LastFD) const {
1116 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001117 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +00001118}
1119
Fariborz Jahanian340fa242011-05-02 17:20:56 +00001120bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
1121 const FieldDecl *LastFD) const {
1122 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001123 FD->getBitWidthValue(*this) == 0 &&
1124 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +00001125}
1126
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001127bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
1128 const FieldDecl *LastFD) const {
1129 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001130 FD->getBitWidthValue(*this) &&
1131 LastFD->getBitWidthValue(*this));
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001132}
1133
Chad Rosierdd7fddb2011-08-04 23:34:15 +00001134bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001135 const FieldDecl *LastFD) const {
1136 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001137 LastFD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001138}
1139
Chad Rosierdd7fddb2011-08-04 23:34:15 +00001140bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001141 const FieldDecl *LastFD) const {
1142 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001143 FD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001144}
1145
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001146ASTContext::overridden_cxx_method_iterator
1147ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1148 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001149 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001150 if (Pos == OverriddenMethods.end())
1151 return 0;
1152
1153 return Pos->second.begin();
1154}
1155
1156ASTContext::overridden_cxx_method_iterator
1157ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1158 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001159 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001160 if (Pos == OverriddenMethods.end())
1161 return 0;
1162
1163 return Pos->second.end();
1164}
1165
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001166unsigned
1167ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1168 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001169 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001170 if (Pos == OverriddenMethods.end())
1171 return 0;
1172
1173 return Pos->second.size();
1174}
1175
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001176void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1177 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001178 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001179 OverriddenMethods[Method].push_back(Overridden);
1180}
1181
Dmitri Gribenko1e905da2012-11-03 14:24:57 +00001182void ASTContext::getOverriddenMethods(
1183 const NamedDecl *D,
1184 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001185 assert(D);
1186
1187 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis685d1042013-04-17 00:09:03 +00001188 Overridden.append(overridden_methods_begin(CXXMethod),
1189 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001190 return;
1191 }
1192
1193 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1194 if (!Method)
1195 return;
1196
Argyrios Kyrtzidis740ae672012-10-09 18:19:01 +00001197 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1198 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisbc0a2bb2012-10-09 20:08:43 +00001199 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001200}
1201
Douglas Gregore6649772011-12-03 00:30:27 +00001202void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1203 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1204 assert(!Import->isFromASTFile() && "Non-local import declaration");
1205 if (!FirstLocalImport) {
1206 FirstLocalImport = Import;
1207 LastLocalImport = Import;
1208 return;
1209 }
1210
1211 LastLocalImport->NextLocalImport = Import;
1212 LastLocalImport = Import;
1213}
1214
Chris Lattner464175b2007-07-18 17:52:12 +00001215//===----------------------------------------------------------------------===//
1216// Type Sizing and Analysis
1217//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +00001218
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001219/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1220/// scalar floating point type.
1221const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +00001222 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001223 assert(BT && "Not a floating point type!");
1224 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001225 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001226 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001227 case BuiltinType::Float: return Target->getFloatFormat();
1228 case BuiltinType::Double: return Target->getDoubleFormat();
1229 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001230 }
1231}
1232
Ken Dyck8b752f12010-01-27 17:10:57 +00001233/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +00001234/// specified decl. Note that bitfields do not have a valid alignment, so
1235/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +00001236/// If @p RefAsPointee, references are treated like their underlying type
1237/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +00001238CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001239 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +00001240
John McCall4081a5c2010-10-08 18:24:19 +00001241 bool UseAlignAttrOnly = false;
1242 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1243 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +00001244
John McCall4081a5c2010-10-08 18:24:19 +00001245 // __attribute__((aligned)) can increase or decrease alignment
1246 // *except* on a struct or struct member, where it only increases
1247 // alignment unless 'packed' is also specified.
1248 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +00001249 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +00001250 // ignore that possibility; Sema should diagnose it.
1251 if (isa<FieldDecl>(D)) {
1252 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1253 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1254 } else {
1255 UseAlignAttrOnly = true;
1256 }
1257 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +00001258 else if (isa<FieldDecl>(D))
1259 UseAlignAttrOnly =
1260 D->hasAttr<PackedAttr>() ||
1261 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +00001262
John McCallba4f5d52011-01-20 07:57:12 +00001263 // If we're using the align attribute only, just ignore everything
1264 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +00001265 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +00001266 // do nothing
1267
John McCall4081a5c2010-10-08 18:24:19 +00001268 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001269 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001270 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001271 if (RefAsPointee)
1272 T = RT->getPointeeType();
1273 else
1274 T = getPointerType(RT->getPointeeType());
1275 }
1276 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +00001277 // Adjust alignments of declarations with array type by the
1278 // large-array alignment on the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001279 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +00001280 const ArrayType *arrayType;
1281 if (MinWidth && (arrayType = getAsArrayType(T))) {
1282 if (isa<VariableArrayType>(arrayType))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001283 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall3b657512011-01-19 10:06:00 +00001284 else if (isa<ConstantArrayType>(arrayType) &&
1285 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001286 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +00001287
John McCall3b657512011-01-19 10:06:00 +00001288 // Walk through any array types while we're at it.
1289 T = getBaseElementType(arrayType);
1290 }
Chad Rosier9f1210c2011-07-26 07:03:04 +00001291 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigand6b203512013-05-06 16:23:57 +00001292 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1293 if (VD->hasGlobalStorage())
1294 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1295 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001296 }
John McCallba4f5d52011-01-20 07:57:12 +00001297
1298 // Fields can be subject to extra alignment constraints, like if
1299 // the field is packed, the struct is packed, or the struct has a
1300 // a max-field-alignment constraint (#pragma pack). So calculate
1301 // the actual alignment of the field within the struct, and then
1302 // (as we're expected to) constrain that by the alignment of the type.
1303 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1304 // So calculate the alignment of the field.
1305 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1306
1307 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +00001308 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +00001309
1310 // Use the GCD of that and the offset within the record.
1311 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1312 if (offset > 0) {
1313 // Alignment is always a power of 2, so the GCD will be a power of 2,
1314 // which means we get to do this crazy thing instead of Euclid's.
1315 uint64_t lowBitOfOffset = offset & (~offset + 1);
1316 if (lowBitOfOffset < fieldAlign)
1317 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1318 }
1319
1320 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +00001321 }
Chris Lattneraf707ab2009-01-24 21:53:27 +00001322 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001323
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001324 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001325}
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001326
John McCall929bbfb2012-08-21 04:10:00 +00001327// getTypeInfoDataSizeInChars - Return the size of a type, in
1328// chars. If the type is a record, its data size is returned. This is
1329// the size of the memcpy that's performed when assigning this type
1330// using a trivial copy/move assignment operator.
1331std::pair<CharUnits, CharUnits>
1332ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1333 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1334
1335 // In C++, objects can sometimes be allocated into the tail padding
1336 // of a base-class subobject. We decide whether that's possible
1337 // during class layout, so here we can just trust the layout results.
1338 if (getLangOpts().CPlusPlus) {
1339 if (const RecordType *RT = T->getAs<RecordType>()) {
1340 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1341 sizeAndAlign.first = layout.getDataSize();
1342 }
1343 }
1344
1345 return sizeAndAlign;
1346}
1347
John McCallea1471e2010-05-20 01:18:31 +00001348std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001349ASTContext::getTypeInfoInChars(const Type *T) const {
John McCallea1471e2010-05-20 01:18:31 +00001350 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001351 return std::make_pair(toCharUnitsFromBits(Info.first),
1352 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +00001353}
1354
1355std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001356ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +00001357 return getTypeInfoInChars(T.getTypePtr());
1358}
1359
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001360std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1361 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1362 if (it != MemoizedTypeInfo.end())
1363 return it->second;
1364
1365 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1366 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1367 return Info;
1368}
1369
1370/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1371/// method does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +00001372///
1373/// FIXME: Pointers into different addr spaces could have different sizes and
1374/// alignment requirements: getPointerInfo should take an AddrSpace, this
1375/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001376std::pair<uint64_t, unsigned>
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001377ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +00001378 uint64_t Width=0;
1379 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +00001380 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001381#define TYPE(Class, Base)
1382#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +00001383#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +00001384#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1385#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +00001386 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +00001387
Chris Lattner692233e2007-07-13 22:27:08 +00001388 case Type::FunctionNoProto:
1389 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +00001390 // GCC extension: alignof(function) = 32 bits
1391 Width = 0;
1392 Align = 32;
1393 break;
1394
Douglas Gregor72564e72009-02-26 23:50:07 +00001395 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +00001396 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +00001397 Width = 0;
1398 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1399 break;
1400
Steve Narofffb22d962007-08-30 01:06:46 +00001401 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001402 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001403
Chris Lattner98be4942008-03-05 18:54:05 +00001404 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001405 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001406 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1407 "Overflow in array type bit size evaluation");
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001408 Width = EltInfo.first*Size;
Chris Lattner030d8842007-07-19 22:06:24 +00001409 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +00001410 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +00001411 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +00001412 }
Nate Begeman213541a2008-04-18 23:10:10 +00001413 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +00001414 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001415 const VectorType *VT = cast<VectorType>(T);
1416 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1417 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +00001418 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001419 // If the alignment is not a power of 2, round up to the next power of 2.
1420 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +00001421 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001422 Align = llvm::NextPowerOf2(Align);
1423 Width = llvm::RoundUpToAlignment(Width, Align);
1424 }
Chad Rosierf9e9af72012-07-13 23:57:43 +00001425 // Adjust the alignment based on the target max.
1426 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1427 if (TargetVectorAlign && TargetVectorAlign < Align)
1428 Align = TargetVectorAlign;
Chris Lattner030d8842007-07-19 22:06:24 +00001429 break;
1430 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001431
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001432 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +00001433 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001434 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001435 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +00001436 // GCC extension: alignof(void) = 8 bits.
1437 Width = 0;
1438 Align = 8;
1439 break;
1440
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001441 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001442 Width = Target->getBoolWidth();
1443 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001444 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001445 case BuiltinType::Char_S:
1446 case BuiltinType::Char_U:
1447 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001448 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001449 Width = Target->getCharWidth();
1450 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001451 break;
Chris Lattner3f59c972010-12-25 23:25:43 +00001452 case BuiltinType::WChar_S:
1453 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001454 Width = Target->getWCharWidth();
1455 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001456 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001457 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001458 Width = Target->getChar16Width();
1459 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001460 break;
1461 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001462 Width = Target->getChar32Width();
1463 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001464 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001465 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001466 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001467 Width = Target->getShortWidth();
1468 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001469 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001470 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001471 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001472 Width = Target->getIntWidth();
1473 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001474 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001475 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001476 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001477 Width = Target->getLongWidth();
1478 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001479 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001480 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001481 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001482 Width = Target->getLongLongWidth();
1483 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001484 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +00001485 case BuiltinType::Int128:
1486 case BuiltinType::UInt128:
1487 Width = 128;
1488 Align = 128; // int128_t is 128-bit aligned on all targets.
1489 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001490 case BuiltinType::Half:
1491 Width = Target->getHalfWidth();
1492 Align = Target->getHalfAlign();
1493 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001494 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001495 Width = Target->getFloatWidth();
1496 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001497 break;
1498 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001499 Width = Target->getDoubleWidth();
1500 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001501 break;
1502 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001503 Width = Target->getLongDoubleWidth();
1504 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001505 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001506 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001507 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1508 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +00001509 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001510 case BuiltinType::ObjCId:
1511 case BuiltinType::ObjCClass:
1512 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001513 Width = Target->getPointerWidth(0);
1514 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001515 break;
Guy Benyei21f18c42013-02-07 10:55:47 +00001516 case BuiltinType::OCLSampler:
1517 // Samplers are modeled as integers.
1518 Width = Target->getIntWidth();
1519 Align = Target->getIntAlign();
1520 break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00001521 case BuiltinType::OCLEvent:
Guy Benyeib13621d2012-12-18 14:38:23 +00001522 case BuiltinType::OCLImage1d:
1523 case BuiltinType::OCLImage1dArray:
1524 case BuiltinType::OCLImage1dBuffer:
1525 case BuiltinType::OCLImage2d:
1526 case BuiltinType::OCLImage2dArray:
1527 case BuiltinType::OCLImage3d:
1528 // Currently these types are pointers to opaque types.
1529 Width = Target->getPointerWidth(0);
1530 Align = Target->getPointerAlign(0);
1531 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001532 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +00001533 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001534 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001535 Width = Target->getPointerWidth(0);
1536 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001537 break;
Steve Naroff485eeff2008-09-24 15:05:44 +00001538 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001539 unsigned AS = getTargetAddressSpace(
1540 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001541 Width = Target->getPointerWidth(AS);
1542 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +00001543 break;
1544 }
Sebastian Redl5d484e82009-11-23 17:18:46 +00001545 case Type::LValueReference:
1546 case Type::RValueReference: {
1547 // alignof and sizeof should never enter this code path here, so we go
1548 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001549 unsigned AS = getTargetAddressSpace(
1550 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001551 Width = Target->getPointerWidth(AS);
1552 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +00001553 break;
1554 }
Chris Lattnerf72a4432008-03-08 08:34:58 +00001555 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001556 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001557 Width = Target->getPointerWidth(AS);
1558 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +00001559 break;
1560 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00001561 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +00001562 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Reid Kleckner84e9ab42013-03-28 20:02:56 +00001563 llvm::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001564 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001565 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001566 case Type::Complex: {
1567 // Complex types have the same alignment as their elements, but twice the
1568 // size.
Mike Stump1eb44332009-09-09 15:08:12 +00001569 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +00001570 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001571 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +00001572 Align = EltInfo.second;
1573 break;
1574 }
John McCallc12c5bb2010-05-15 11:32:37 +00001575 case Type::ObjCObject:
1576 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +00001577 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001578 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +00001579 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001580 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001581 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +00001582 break;
1583 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001584 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001585 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001586 const TagType *TT = cast<TagType>(T);
1587
1588 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001589 Width = 8;
1590 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001591 break;
1592 }
Mike Stump1eb44332009-09-09 15:08:12 +00001593
Daniel Dunbar1d751182008-11-08 05:48:37 +00001594 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001595 return getTypeInfo(ET->getDecl()->getIntegerType());
1596
Daniel Dunbar1d751182008-11-08 05:48:37 +00001597 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001598 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001599 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001600 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001601 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001602 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001603
Chris Lattner9fcfe922009-10-22 05:17:15 +00001604 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001605 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1606 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001607
Richard Smith34b41d92011-02-20 03:19:35 +00001608 case Type::Auto: {
1609 const AutoType *A = cast<AutoType>(T);
Richard Smithdc7a4f52013-04-30 13:56:41 +00001610 assert(!A->getDeducedType().isNull() &&
1611 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001612 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001613 }
1614
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001615 case Type::Paren:
1616 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1617
Douglas Gregor18857642009-04-30 17:32:17 +00001618 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001619 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001620 std::pair<uint64_t, unsigned> Info
1621 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001622 // If the typedef has an aligned attribute on it, it overrides any computed
1623 // alignment we have. This violates the GCC documentation (which says that
1624 // attribute(aligned) can only round up) but matches its implementation.
1625 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1626 Align = AttrAlign;
1627 else
1628 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001629 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001630 break;
Chris Lattner71763312008-04-06 22:05:18 +00001631 }
Douglas Gregor18857642009-04-30 17:32:17 +00001632
1633 case Type::TypeOfExpr:
1634 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1635 .getTypePtr());
1636
1637 case Type::TypeOf:
1638 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1639
Anders Carlsson395b4752009-06-24 19:06:50 +00001640 case Type::Decltype:
1641 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1642 .getTypePtr());
1643
Sean Huntca63c202011-05-24 22:41:36 +00001644 case Type::UnaryTransform:
1645 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1646
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001647 case Type::Elaborated:
1648 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001649
John McCall9d156a72011-01-06 01:58:22 +00001650 case Type::Attributed:
1651 return getTypeInfo(
1652 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1653
Richard Smith3e4c6c42011-05-05 21:57:07 +00001654 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00001655 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +00001656 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +00001657 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1658 // A type alias template specialization may refer to a typedef with the
1659 // aligned attribute on it.
1660 if (TST->isTypeAlias())
1661 return getTypeInfo(TST->getAliasedType().getTypePtr());
1662 else
1663 return getTypeInfo(getCanonicalType(T));
1664 }
1665
Eli Friedmanb001de72011-10-06 23:00:33 +00001666 case Type::Atomic: {
John McCall9eda3ab2013-03-07 21:37:17 +00001667 // Start with the base type information.
Eli Friedman2be46072011-10-14 20:59:01 +00001668 std::pair<uint64_t, unsigned> Info
1669 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1670 Width = Info.first;
1671 Align = Info.second;
John McCall9eda3ab2013-03-07 21:37:17 +00001672
1673 // If the size of the type doesn't exceed the platform's max
1674 // atomic promotion width, make the size and alignment more
1675 // favorable to atomic operations:
1676 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1677 // Round the size up to a power of 2.
1678 if (!llvm::isPowerOf2_64(Width))
1679 Width = llvm::NextPowerOf2(Width);
1680
1681 // Set the alignment equal to the size.
Eli Friedman2be46072011-10-14 20:59:01 +00001682 Align = static_cast<unsigned>(Width);
1683 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001684 }
1685
Douglas Gregor18857642009-04-30 17:32:17 +00001686 }
Mike Stump1eb44332009-09-09 15:08:12 +00001687
Eli Friedman2be46072011-10-14 20:59:01 +00001688 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001689 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001690}
1691
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001692/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1693CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1694 return CharUnits::fromQuantity(BitSize / getCharWidth());
1695}
1696
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001697/// toBits - Convert a size in characters to a size in characters.
1698int64_t ASTContext::toBits(CharUnits CharSize) const {
1699 return CharSize.getQuantity() * getCharWidth();
1700}
1701
Ken Dyckbdc601b2009-12-22 14:23:30 +00001702/// getTypeSizeInChars - Return the size of the specified type, in characters.
1703/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001704CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001705 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001706}
Jay Foad4ba2a172011-01-12 09:06:06 +00001707CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001708 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001709}
1710
Ken Dyck16e20cc2010-01-26 17:25:18 +00001711/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001712/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001713CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001714 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001715}
Jay Foad4ba2a172011-01-12 09:06:06 +00001716CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001717 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001718}
1719
Chris Lattner34ebde42009-01-27 18:08:34 +00001720/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1721/// type for the current target in bits. This can be different than the ABI
1722/// alignment in cases where it is beneficial for performance to overalign
1723/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001724unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001725 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001726
1727 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001728 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001729 T = CT->getElementType().getTypePtr();
1730 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosiercde7a1d2012-03-21 20:20:47 +00001731 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1732 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman1eed6022009-05-25 21:27:19 +00001733 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1734
Chris Lattner34ebde42009-01-27 18:08:34 +00001735 return ABIAlign;
1736}
1737
Ulrich Weigand6b203512013-05-06 16:23:57 +00001738/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1739/// to a global variable of the specified type.
1740unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1741 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1742}
1743
1744/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1745/// should be given to a global variable of the specified type.
1746CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1747 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1748}
1749
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001750/// DeepCollectObjCIvars -
1751/// This routine first collects all declared, but not synthesized, ivars in
1752/// super class and then collects all ivars, including those synthesized for
1753/// current class. This routine is used for implementation of current class
1754/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001755///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001756void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1757 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001758 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001759 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1760 DeepCollectObjCIvars(SuperClass, false, Ivars);
1761 if (!leafClass) {
1762 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1763 E = OI->ivar_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001764 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001765 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001766 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001767 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001768 Iv= Iv->getNextIvar())
1769 Ivars.push_back(Iv);
1770 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001771}
1772
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001773/// CollectInheritedProtocols - Collect all protocols in current class and
1774/// those inherited by it.
1775void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001776 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001777 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001778 // We can use protocol_iterator here instead of
1779 // all_referenced_protocol_iterator since we are walking all categories.
1780 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1781 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001782 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001783 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001784 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001785 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001786 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001787 CollectInheritedProtocols(*P, Protocols);
1788 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001789 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001790
1791 // Categories of this Interface.
Douglas Gregord3297242013-01-16 23:00:23 +00001792 for (ObjCInterfaceDecl::visible_categories_iterator
1793 Cat = OI->visible_categories_begin(),
1794 CatEnd = OI->visible_categories_end();
1795 Cat != CatEnd; ++Cat) {
1796 CollectInheritedProtocols(*Cat, Protocols);
1797 }
1798
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001799 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1800 while (SD) {
1801 CollectInheritedProtocols(SD, Protocols);
1802 SD = SD->getSuperClass();
1803 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001804 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001805 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001806 PE = OC->protocol_end(); P != PE; ++P) {
1807 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001808 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001809 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1810 PE = Proto->protocol_end(); P != PE; ++P)
1811 CollectInheritedProtocols(*P, Protocols);
1812 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001813 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001814 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1815 PE = OP->protocol_end(); P != PE; ++P) {
1816 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001817 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001818 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1819 PE = Proto->protocol_end(); P != PE; ++P)
1820 CollectInheritedProtocols(*P, Protocols);
1821 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001822 }
1823}
1824
Jay Foad4ba2a172011-01-12 09:06:06 +00001825unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001826 unsigned count = 0;
1827 // Count ivars declared in class extension.
Douglas Gregord3297242013-01-16 23:00:23 +00001828 for (ObjCInterfaceDecl::known_extensions_iterator
1829 Ext = OI->known_extensions_begin(),
1830 ExtEnd = OI->known_extensions_end();
1831 Ext != ExtEnd; ++Ext) {
1832 count += Ext->ivar_size();
1833 }
1834
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001835 // Count ivar defined in this class's implementation. This
1836 // includes synthesized ivars.
1837 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001838 count += ImplDecl->ivar_size();
1839
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001840 return count;
1841}
1842
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +00001843bool ASTContext::isSentinelNullExpr(const Expr *E) {
1844 if (!E)
1845 return false;
1846
1847 // nullptr_t is always treated as null.
1848 if (E->getType()->isNullPtrType()) return true;
1849
1850 if (E->getType()->isAnyPointerType() &&
1851 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1852 Expr::NPC_ValueDependentIsNull))
1853 return true;
1854
1855 // Unfortunately, __null has type 'int'.
1856 if (isa<GNUNullExpr>(E)) return true;
1857
1858 return false;
1859}
1860
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001861/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1862ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1863 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1864 I = ObjCImpls.find(D);
1865 if (I != ObjCImpls.end())
1866 return cast<ObjCImplementationDecl>(I->second);
1867 return 0;
1868}
1869/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1870ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1871 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1872 I = ObjCImpls.find(D);
1873 if (I != ObjCImpls.end())
1874 return cast<ObjCCategoryImplDecl>(I->second);
1875 return 0;
1876}
1877
1878/// \brief Set the implementation of ObjCInterfaceDecl.
1879void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1880 ObjCImplementationDecl *ImplD) {
1881 assert(IFaceD && ImplD && "Passed null params");
1882 ObjCImpls[IFaceD] = ImplD;
1883}
1884/// \brief Set the implementation of ObjCCategoryDecl.
1885void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1886 ObjCCategoryImplDecl *ImplD) {
1887 assert(CatD && ImplD && "Passed null params");
1888 ObjCImpls[CatD] = ImplD;
1889}
1890
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001891const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1892 const NamedDecl *ND) const {
1893 if (const ObjCInterfaceDecl *ID =
1894 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001895 return ID;
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001896 if (const ObjCCategoryDecl *CD =
1897 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001898 return CD->getClassInterface();
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001899 if (const ObjCImplDecl *IMD =
1900 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001901 return IMD->getClassInterface();
1902
1903 return 0;
1904}
1905
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001906/// \brief Get the copy initialization expression of VarDecl,or NULL if
1907/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001908Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001909 assert(VD && "Passed null params");
1910 assert(VD->hasAttr<BlocksAttr>() &&
1911 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001912 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001913 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001914 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1915}
1916
1917/// \brief Set the copy inialization expression of a block var decl.
1918void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1919 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001920 assert(VD->hasAttr<BlocksAttr>() &&
1921 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001922 BlockVarCopyInits[VD] = Init;
1923}
1924
John McCalla93c9342009-12-07 02:54:59 +00001925TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001926 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001927 if (!DataSize)
1928 DataSize = TypeLoc::getFullDataSizeForType(T);
1929 else
1930 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001931 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001932
John McCalla93c9342009-12-07 02:54:59 +00001933 TypeSourceInfo *TInfo =
1934 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1935 new (TInfo) TypeSourceInfo(T);
1936 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001937}
1938
John McCalla93c9342009-12-07 02:54:59 +00001939TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001940 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001941 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001942 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001943 return DI;
1944}
1945
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001946const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001947ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001948 return getObjCLayout(D, 0);
1949}
1950
1951const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001952ASTContext::getASTObjCImplementationLayout(
1953 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001954 return getObjCLayout(D->getClassInterface(), D);
1955}
1956
Chris Lattnera7674d82007-07-13 22:13:22 +00001957//===----------------------------------------------------------------------===//
1958// Type creation/memoization methods
1959//===----------------------------------------------------------------------===//
1960
Jay Foad4ba2a172011-01-12 09:06:06 +00001961QualType
John McCall3b657512011-01-19 10:06:00 +00001962ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1963 unsigned fastQuals = quals.getFastQualifiers();
1964 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001965
1966 // Check if we've already instantiated this type.
1967 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001968 ExtQuals::Profile(ID, baseType, quals);
1969 void *insertPos = 0;
1970 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1971 assert(eq->getQualifiers() == quals);
1972 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001973 }
1974
John McCall3b657512011-01-19 10:06:00 +00001975 // If the base type is not canonical, make the appropriate canonical type.
1976 QualType canon;
1977 if (!baseType->isCanonicalUnqualified()) {
1978 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall200fa532012-02-08 00:46:36 +00001979 canonSplit.Quals.addConsistentQualifiers(quals);
1980 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00001981
1982 // Re-find the insert position.
1983 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1984 }
1985
1986 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1987 ExtQualNodes.InsertNode(eq, insertPos);
1988 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001989}
1990
Jay Foad4ba2a172011-01-12 09:06:06 +00001991QualType
1992ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001993 QualType CanT = getCanonicalType(T);
1994 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001995 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001996
John McCall0953e762009-09-24 19:53:00 +00001997 // If we are composing extended qualifiers together, merge together
1998 // into one ExtQuals node.
1999 QualifierCollector Quals;
2000 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002001
John McCall0953e762009-09-24 19:53:00 +00002002 // If this type already has an address space specified, it cannot get
2003 // another one.
2004 assert(!Quals.hasAddressSpace() &&
2005 "Type cannot be in multiple addr spaces!");
2006 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002007
John McCall0953e762009-09-24 19:53:00 +00002008 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00002009}
2010
Chris Lattnerb7d25532009-02-18 22:53:11 +00002011QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00002012 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002013 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00002014 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002015 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00002016
John McCall7f040a92010-12-24 02:08:15 +00002017 if (const PointerType *ptr = T->getAs<PointerType>()) {
2018 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00002019 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00002020 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2021 return getPointerType(ResultType);
2022 }
2023 }
Mike Stump1eb44332009-09-09 15:08:12 +00002024
John McCall0953e762009-09-24 19:53:00 +00002025 // If we are composing extended qualifiers together, merge together
2026 // into one ExtQuals node.
2027 QualifierCollector Quals;
2028 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002029
John McCall0953e762009-09-24 19:53:00 +00002030 // If this type already has an ObjCGC specified, it cannot get
2031 // another one.
2032 assert(!Quals.hasObjCGCAttr() &&
2033 "Type cannot have multiple ObjCGCs!");
2034 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00002035
John McCall0953e762009-09-24 19:53:00 +00002036 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002037}
Chris Lattnera7674d82007-07-13 22:13:22 +00002038
John McCalle6a365d2010-12-19 02:44:49 +00002039const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2040 FunctionType::ExtInfo Info) {
2041 if (T->getExtInfo() == Info)
2042 return T;
2043
2044 QualType Result;
2045 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2046 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
2047 } else {
2048 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2049 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2050 EPI.ExtInfo = Info;
Jordan Rosebea522f2013-03-08 21:51:21 +00002051 Result = getFunctionType(FPT->getResultType(),
2052 ArrayRef<QualType>(FPT->arg_type_begin(),
2053 FPT->getNumArgs()),
2054 EPI);
John McCalle6a365d2010-12-19 02:44:49 +00002055 }
2056
2057 return cast<FunctionType>(Result.getTypePtr());
2058}
2059
Richard Smith60e141e2013-05-04 07:00:32 +00002060void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2061 QualType ResultType) {
Richard Smith9dadfab2013-05-11 05:45:24 +00002062 FD = FD->getMostRecentDecl();
2063 while (true) {
Richard Smith60e141e2013-05-04 07:00:32 +00002064 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2065 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2066 FD->setType(getFunctionType(ResultType, FPT->getArgTypes(), EPI));
Richard Smith9dadfab2013-05-11 05:45:24 +00002067 if (FunctionDecl *Next = FD->getPreviousDecl())
2068 FD = Next;
2069 else
2070 break;
Richard Smith60e141e2013-05-04 07:00:32 +00002071 }
Richard Smith9dadfab2013-05-11 05:45:24 +00002072 if (ASTMutationListener *L = getASTMutationListener())
2073 L->DeducedReturnType(FD, ResultType);
Richard Smith60e141e2013-05-04 07:00:32 +00002074}
2075
Reid Spencer5f016e22007-07-11 17:01:13 +00002076/// getComplexType - Return the uniqued reference to the type for a complex
2077/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002078QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002079 // Unique pointers, to guarantee there is only one pointer of a particular
2080 // structure.
2081 llvm::FoldingSetNodeID ID;
2082 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002083
Reid Spencer5f016e22007-07-11 17:01:13 +00002084 void *InsertPos = 0;
2085 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2086 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002087
Reid Spencer5f016e22007-07-11 17:01:13 +00002088 // If the pointee type isn't canonical, this won't be a canonical type either,
2089 // so fill in the canonical type field.
2090 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002091 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002092 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002093
Reid Spencer5f016e22007-07-11 17:01:13 +00002094 // Get the new insert position for the node we care about.
2095 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002096 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002097 }
John McCall6b304a02009-09-24 23:30:46 +00002098 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002099 Types.push_back(New);
2100 ComplexTypes.InsertNode(New, InsertPos);
2101 return QualType(New, 0);
2102}
2103
Reid Spencer5f016e22007-07-11 17:01:13 +00002104/// getPointerType - Return the uniqued reference to the type for a pointer to
2105/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002106QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002107 // Unique pointers, to guarantee there is only one pointer of a particular
2108 // structure.
2109 llvm::FoldingSetNodeID ID;
2110 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002111
Reid Spencer5f016e22007-07-11 17:01:13 +00002112 void *InsertPos = 0;
2113 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2114 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002115
Reid Spencer5f016e22007-07-11 17:01:13 +00002116 // If the pointee type isn't canonical, this won't be a canonical type either,
2117 // so fill in the canonical type field.
2118 QualType Canonical;
Bob Wilsonc90cc932013-03-15 17:12:43 +00002119 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002120 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002121
Bob Wilsonc90cc932013-03-15 17:12:43 +00002122 // Get the new insert position for the node we care about.
2123 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2124 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2125 }
John McCall6b304a02009-09-24 23:30:46 +00002126 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002127 Types.push_back(New);
2128 PointerTypes.InsertNode(New, InsertPos);
2129 return QualType(New, 0);
2130}
2131
Mike Stump1eb44332009-09-09 15:08:12 +00002132/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00002133/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00002134QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00002135 assert(T->isFunctionType() && "block of function types only");
2136 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00002137 // structure.
2138 llvm::FoldingSetNodeID ID;
2139 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002140
Steve Naroff5618bd42008-08-27 16:04:49 +00002141 void *InsertPos = 0;
2142 if (BlockPointerType *PT =
2143 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2144 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002145
2146 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00002147 // type either so fill in the canonical type field.
2148 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002149 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00002150 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002151
Steve Naroff5618bd42008-08-27 16:04:49 +00002152 // Get the new insert position for the node we care about.
2153 BlockPointerType *NewIP =
2154 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002155 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00002156 }
John McCall6b304a02009-09-24 23:30:46 +00002157 BlockPointerType *New
2158 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00002159 Types.push_back(New);
2160 BlockPointerTypes.InsertNode(New, InsertPos);
2161 return QualType(New, 0);
2162}
2163
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002164/// getLValueReferenceType - Return the uniqued reference to the type for an
2165/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002166QualType
2167ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00002168 assert(getCanonicalType(T) != OverloadTy &&
2169 "Unresolved overloaded function type");
2170
Reid Spencer5f016e22007-07-11 17:01:13 +00002171 // Unique pointers, to guarantee there is only one pointer of a particular
2172 // structure.
2173 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002174 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002175
2176 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002177 if (LValueReferenceType *RT =
2178 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002179 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002180
John McCall54e14c42009-10-22 22:37:11 +00002181 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2182
Reid Spencer5f016e22007-07-11 17:01:13 +00002183 // If the referencee type isn't canonical, this won't be a canonical type
2184 // either, so fill in the canonical type field.
2185 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002186 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2187 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2188 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002189
Reid Spencer5f016e22007-07-11 17:01:13 +00002190 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002191 LValueReferenceType *NewIP =
2192 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002193 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002194 }
2195
John McCall6b304a02009-09-24 23:30:46 +00002196 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00002197 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2198 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002199 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002200 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00002201
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002202 return QualType(New, 0);
2203}
2204
2205/// getRValueReferenceType - Return the uniqued reference to the type for an
2206/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002207QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002208 // Unique pointers, to guarantee there is only one pointer of a particular
2209 // structure.
2210 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002211 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002212
2213 void *InsertPos = 0;
2214 if (RValueReferenceType *RT =
2215 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2216 return QualType(RT, 0);
2217
John McCall54e14c42009-10-22 22:37:11 +00002218 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2219
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002220 // If the referencee type isn't canonical, this won't be a canonical type
2221 // either, so fill in the canonical type field.
2222 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002223 if (InnerRef || !T.isCanonical()) {
2224 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2225 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002226
2227 // Get the new insert position for the node we care about.
2228 RValueReferenceType *NewIP =
2229 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002230 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002231 }
2232
John McCall6b304a02009-09-24 23:30:46 +00002233 RValueReferenceType *New
2234 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002235 Types.push_back(New);
2236 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002237 return QualType(New, 0);
2238}
2239
Sebastian Redlf30208a2009-01-24 21:16:55 +00002240/// getMemberPointerType - Return the uniqued reference to the type for a
2241/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00002242QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002243 // Unique pointers, to guarantee there is only one pointer of a particular
2244 // structure.
2245 llvm::FoldingSetNodeID ID;
2246 MemberPointerType::Profile(ID, T, Cls);
2247
2248 void *InsertPos = 0;
2249 if (MemberPointerType *PT =
2250 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2251 return QualType(PT, 0);
2252
2253 // If the pointee or class type isn't canonical, this won't be a canonical
2254 // type either, so fill in the canonical type field.
2255 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00002256 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002257 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2258
2259 // Get the new insert position for the node we care about.
2260 MemberPointerType *NewIP =
2261 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002262 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00002263 }
John McCall6b304a02009-09-24 23:30:46 +00002264 MemberPointerType *New
2265 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002266 Types.push_back(New);
2267 MemberPointerTypes.InsertNode(New, InsertPos);
2268 return QualType(New, 0);
2269}
2270
Mike Stump1eb44332009-09-09 15:08:12 +00002271/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00002272/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002273QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00002274 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00002275 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002276 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00002277 assert((EltTy->isDependentType() ||
2278 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00002279 "Constant array of VLAs is illegal!");
2280
Chris Lattner38aeec72009-05-13 04:12:56 +00002281 // Convert the array size into a canonical width matching the pointer size for
2282 // the target.
2283 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002284 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002285 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00002286
Reid Spencer5f016e22007-07-11 17:01:13 +00002287 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002288 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00002289
Reid Spencer5f016e22007-07-11 17:01:13 +00002290 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002291 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002292 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002293 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002294
John McCall3b657512011-01-19 10:06:00 +00002295 // If the element type isn't canonical or has qualifiers, this won't
2296 // be a canonical type either, so fill in the canonical type field.
2297 QualType Canon;
2298 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2299 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002300 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002301 ASM, IndexTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002302 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00002303
Reid Spencer5f016e22007-07-11 17:01:13 +00002304 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00002305 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002306 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002307 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002308 }
Mike Stump1eb44332009-09-09 15:08:12 +00002309
John McCall6b304a02009-09-24 23:30:46 +00002310 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002311 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002312 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002313 Types.push_back(New);
2314 return QualType(New, 0);
2315}
2316
John McCallce889032011-01-18 08:40:38 +00002317/// getVariableArrayDecayedType - Turns the given type, which may be
2318/// variably-modified, into the corresponding type with all the known
2319/// sizes replaced with [*].
2320QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2321 // Vastly most common case.
2322 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002323
John McCallce889032011-01-18 08:40:38 +00002324 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002325
John McCallce889032011-01-18 08:40:38 +00002326 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00002327 const Type *ty = split.Ty;
John McCallce889032011-01-18 08:40:38 +00002328 switch (ty->getTypeClass()) {
2329#define TYPE(Class, Base)
2330#define ABSTRACT_TYPE(Class, Base)
2331#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2332#include "clang/AST/TypeNodes.def"
2333 llvm_unreachable("didn't desugar past all non-canonical types?");
2334
2335 // These types should never be variably-modified.
2336 case Type::Builtin:
2337 case Type::Complex:
2338 case Type::Vector:
2339 case Type::ExtVector:
2340 case Type::DependentSizedExtVector:
2341 case Type::ObjCObject:
2342 case Type::ObjCInterface:
2343 case Type::ObjCObjectPointer:
2344 case Type::Record:
2345 case Type::Enum:
2346 case Type::UnresolvedUsing:
2347 case Type::TypeOfExpr:
2348 case Type::TypeOf:
2349 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00002350 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00002351 case Type::DependentName:
2352 case Type::InjectedClassName:
2353 case Type::TemplateSpecialization:
2354 case Type::DependentTemplateSpecialization:
2355 case Type::TemplateTypeParm:
2356 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00002357 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00002358 case Type::PackExpansion:
2359 llvm_unreachable("type should never be variably-modified");
2360
2361 // These types can be variably-modified but should never need to
2362 // further decay.
2363 case Type::FunctionNoProto:
2364 case Type::FunctionProto:
2365 case Type::BlockPointer:
2366 case Type::MemberPointer:
2367 return type;
2368
2369 // These types can be variably-modified. All these modifications
2370 // preserve structure except as noted by comments.
2371 // TODO: if we ever care about optimizing VLAs, there are no-op
2372 // optimizations available here.
2373 case Type::Pointer:
2374 result = getPointerType(getVariableArrayDecayedType(
2375 cast<PointerType>(ty)->getPointeeType()));
2376 break;
2377
2378 case Type::LValueReference: {
2379 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2380 result = getLValueReferenceType(
2381 getVariableArrayDecayedType(lv->getPointeeType()),
2382 lv->isSpelledAsLValue());
2383 break;
2384 }
2385
2386 case Type::RValueReference: {
2387 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2388 result = getRValueReferenceType(
2389 getVariableArrayDecayedType(lv->getPointeeType()));
2390 break;
2391 }
2392
Eli Friedmanb001de72011-10-06 23:00:33 +00002393 case Type::Atomic: {
2394 const AtomicType *at = cast<AtomicType>(ty);
2395 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2396 break;
2397 }
2398
John McCallce889032011-01-18 08:40:38 +00002399 case Type::ConstantArray: {
2400 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2401 result = getConstantArrayType(
2402 getVariableArrayDecayedType(cat->getElementType()),
2403 cat->getSize(),
2404 cat->getSizeModifier(),
2405 cat->getIndexTypeCVRQualifiers());
2406 break;
2407 }
2408
2409 case Type::DependentSizedArray: {
2410 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2411 result = getDependentSizedArrayType(
2412 getVariableArrayDecayedType(dat->getElementType()),
2413 dat->getSizeExpr(),
2414 dat->getSizeModifier(),
2415 dat->getIndexTypeCVRQualifiers(),
2416 dat->getBracketsRange());
2417 break;
2418 }
2419
2420 // Turn incomplete types into [*] types.
2421 case Type::IncompleteArray: {
2422 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2423 result = getVariableArrayType(
2424 getVariableArrayDecayedType(iat->getElementType()),
2425 /*size*/ 0,
2426 ArrayType::Normal,
2427 iat->getIndexTypeCVRQualifiers(),
2428 SourceRange());
2429 break;
2430 }
2431
2432 // Turn VLA types into [*] types.
2433 case Type::VariableArray: {
2434 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2435 result = getVariableArrayType(
2436 getVariableArrayDecayedType(vat->getElementType()),
2437 /*size*/ 0,
2438 ArrayType::Star,
2439 vat->getIndexTypeCVRQualifiers(),
2440 vat->getBracketsRange());
2441 break;
2442 }
2443 }
2444
2445 // Apply the top-level qualifiers from the original.
John McCall200fa532012-02-08 00:46:36 +00002446 return getQualifiedType(result, split.Quals);
John McCallce889032011-01-18 08:40:38 +00002447}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002448
Steve Naroffbdbf7b02007-08-30 18:14:25 +00002449/// getVariableArrayType - Returns a non-unique reference to the type for a
2450/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002451QualType ASTContext::getVariableArrayType(QualType EltTy,
2452 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00002453 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002454 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00002455 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002456 // Since we don't unique expressions, it isn't possible to unique VLA's
2457 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00002458 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00002459
John McCall3b657512011-01-19 10:06:00 +00002460 // Be sure to pull qualifiers off the element type.
2461 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2462 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002463 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002464 IndexTypeQuals, Brackets);
John McCall200fa532012-02-08 00:46:36 +00002465 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor715e9c82010-05-23 16:10:32 +00002466 }
2467
John McCall6b304a02009-09-24 23:30:46 +00002468 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002469 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002470
2471 VariableArrayTypes.push_back(New);
2472 Types.push_back(New);
2473 return QualType(New, 0);
2474}
2475
Douglas Gregor898574e2008-12-05 23:32:09 +00002476/// getDependentSizedArrayType - Returns a non-unique reference to
2477/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00002478/// type.
John McCall3b657512011-01-19 10:06:00 +00002479QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2480 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00002481 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002482 unsigned elementTypeQuals,
2483 SourceRange brackets) const {
2484 assert((!numElements || numElements->isTypeDependent() ||
2485 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00002486 "Size must be type- or value-dependent!");
2487
John McCall3b657512011-01-19 10:06:00 +00002488 // Dependently-sized array types that do not have a specified number
2489 // of elements will have their sizes deduced from a dependent
2490 // initializer. We do no canonicalization here at all, which is okay
2491 // because they can't be used in most locations.
2492 if (!numElements) {
2493 DependentSizedArrayType *newType
2494 = new (*this, TypeAlignment)
2495 DependentSizedArrayType(*this, elementType, QualType(),
2496 numElements, ASM, elementTypeQuals,
2497 brackets);
2498 Types.push_back(newType);
2499 return QualType(newType, 0);
2500 }
2501
2502 // Otherwise, we actually build a new type every time, but we
2503 // also build a canonical type.
2504
2505 SplitQualType canonElementType = getCanonicalType(elementType).split();
2506
2507 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00002508 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002509 DependentSizedArrayType::Profile(ID, *this,
John McCall200fa532012-02-08 00:46:36 +00002510 QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002511 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002512
John McCall3b657512011-01-19 10:06:00 +00002513 // Look for an existing type with these properties.
2514 DependentSizedArrayType *canonTy =
2515 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002516
John McCall3b657512011-01-19 10:06:00 +00002517 // If we don't have one, build one.
2518 if (!canonTy) {
2519 canonTy = new (*this, TypeAlignment)
John McCall200fa532012-02-08 00:46:36 +00002520 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002521 QualType(), numElements, ASM, elementTypeQuals,
2522 brackets);
2523 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2524 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002525 }
2526
John McCall3b657512011-01-19 10:06:00 +00002527 // Apply qualifiers from the element type to the array.
2528 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall200fa532012-02-08 00:46:36 +00002529 canonElementType.Quals);
Mike Stump1eb44332009-09-09 15:08:12 +00002530
John McCall3b657512011-01-19 10:06:00 +00002531 // If we didn't need extra canonicalization for the element type,
2532 // then just use that as our result.
John McCall200fa532012-02-08 00:46:36 +00002533 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall3b657512011-01-19 10:06:00 +00002534 return canon;
2535
2536 // Otherwise, we need to build a type which follows the spelling
2537 // of the element type.
2538 DependentSizedArrayType *sugaredType
2539 = new (*this, TypeAlignment)
2540 DependentSizedArrayType(*this, elementType, canon, numElements,
2541 ASM, elementTypeQuals, brackets);
2542 Types.push_back(sugaredType);
2543 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00002544}
2545
John McCall3b657512011-01-19 10:06:00 +00002546QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00002547 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002548 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002549 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002550 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002551
John McCall3b657512011-01-19 10:06:00 +00002552 void *insertPos = 0;
2553 if (IncompleteArrayType *iat =
2554 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2555 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002556
2557 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00002558 // either, so fill in the canonical type field. We also have to pull
2559 // qualifiers off the element type.
2560 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00002561
John McCall3b657512011-01-19 10:06:00 +00002562 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2563 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall200fa532012-02-08 00:46:36 +00002564 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002565 ASM, elementTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002566 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002567
2568 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00002569 IncompleteArrayType *existing =
2570 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2571 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00002572 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00002573
John McCall3b657512011-01-19 10:06:00 +00002574 IncompleteArrayType *newType = new (*this, TypeAlignment)
2575 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002576
John McCall3b657512011-01-19 10:06:00 +00002577 IncompleteArrayTypes.InsertNode(newType, insertPos);
2578 Types.push_back(newType);
2579 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00002580}
2581
Steve Naroff73322922007-07-18 18:00:27 +00002582/// getVectorType - Return the unique reference to a vector type of
2583/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00002584QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00002585 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00002586 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00002587
Reid Spencer5f016e22007-07-11 17:01:13 +00002588 // Check if we've already instantiated a vector of this type.
2589 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00002590 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00002591
Reid Spencer5f016e22007-07-11 17:01:13 +00002592 void *InsertPos = 0;
2593 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2594 return QualType(VTP, 0);
2595
2596 // If the element type isn't canonical, this won't be a canonical type either,
2597 // so fill in the canonical type field.
2598 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00002599 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00002600 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002601
Reid Spencer5f016e22007-07-11 17:01:13 +00002602 // Get the new insert position for the node we care about.
2603 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002604 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002605 }
John McCall6b304a02009-09-24 23:30:46 +00002606 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00002607 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002608 VectorTypes.InsertNode(New, InsertPos);
2609 Types.push_back(New);
2610 return QualType(New, 0);
2611}
2612
Nate Begeman213541a2008-04-18 23:10:10 +00002613/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00002614/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002615QualType
2616ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00002617 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00002618
Steve Naroff73322922007-07-18 18:00:27 +00002619 // Check if we've already instantiated a vector of this type.
2620 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00002621 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002622 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00002623 void *InsertPos = 0;
2624 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2625 return QualType(VTP, 0);
2626
2627 // If the element type isn't canonical, this won't be a canonical type either,
2628 // so fill in the canonical type field.
2629 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002630 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002631 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00002632
Steve Naroff73322922007-07-18 18:00:27 +00002633 // Get the new insert position for the node we care about.
2634 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002635 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00002636 }
John McCall6b304a02009-09-24 23:30:46 +00002637 ExtVectorType *New = new (*this, TypeAlignment)
2638 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00002639 VectorTypes.InsertNode(New, InsertPos);
2640 Types.push_back(New);
2641 return QualType(New, 0);
2642}
2643
Jay Foad4ba2a172011-01-12 09:06:06 +00002644QualType
2645ASTContext::getDependentSizedExtVectorType(QualType vecType,
2646 Expr *SizeExpr,
2647 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002648 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002649 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002650 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002651
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002652 void *InsertPos = 0;
2653 DependentSizedExtVectorType *Canon
2654 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2655 DependentSizedExtVectorType *New;
2656 if (Canon) {
2657 // We already have a canonical version of this array type; use it as
2658 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002659 New = new (*this, TypeAlignment)
2660 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2661 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002662 } else {
2663 QualType CanonVecTy = getCanonicalType(vecType);
2664 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002665 New = new (*this, TypeAlignment)
2666 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2667 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002668
2669 DependentSizedExtVectorType *CanonCheck
2670 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2671 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2672 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002673 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2674 } else {
2675 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2676 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002677 New = new (*this, TypeAlignment)
2678 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002679 }
2680 }
Mike Stump1eb44332009-09-09 15:08:12 +00002681
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002682 Types.push_back(New);
2683 return QualType(New, 0);
2684}
2685
Douglas Gregor72564e72009-02-26 23:50:07 +00002686/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002687///
Jay Foad4ba2a172011-01-12 09:06:06 +00002688QualType
2689ASTContext::getFunctionNoProtoType(QualType ResultTy,
2690 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00002691 const CallingConv DefaultCC = Info.getCC();
2692 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2693 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00002694 // Unique functions, to guarantee there is only one function of a particular
2695 // structure.
2696 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002697 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002698
Reid Spencer5f016e22007-07-11 17:01:13 +00002699 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002700 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002701 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002702 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002703
Reid Spencer5f016e22007-07-11 17:01:13 +00002704 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00002705 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00002706 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00002707 Canonical =
2708 getFunctionNoProtoType(getCanonicalType(ResultTy),
2709 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00002710
Reid Spencer5f016e22007-07-11 17:01:13 +00002711 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002712 FunctionNoProtoType *NewIP =
2713 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002714 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002715 }
Mike Stump1eb44332009-09-09 15:08:12 +00002716
Roman Divackycfe9af22011-03-01 17:40:53 +00002717 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002718 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002719 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002720 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002721 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002722 return QualType(New, 0);
2723}
2724
Douglas Gregor02dd7982013-01-17 23:36:45 +00002725/// \brief Determine whether \p T is canonical as the result type of a function.
2726static bool isCanonicalResultType(QualType T) {
2727 return T.isCanonical() &&
2728 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2729 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2730}
2731
Reid Spencer5f016e22007-07-11 17:01:13 +00002732/// getFunctionType - Return a normal function type with a typed argument
2733/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002734QualType
Jordan Rosebea522f2013-03-08 21:51:21 +00002735ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad4ba2a172011-01-12 09:06:06 +00002736 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rosebea522f2013-03-08 21:51:21 +00002737 size_t NumArgs = ArgArray.size();
2738
Reid Spencer5f016e22007-07-11 17:01:13 +00002739 // Unique functions, to guarantee there is only one function of a particular
2740 // structure.
2741 llvm::FoldingSetNodeID ID;
Jordan Rosebea522f2013-03-08 21:51:21 +00002742 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2743 *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002744
2745 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002746 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002747 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002748 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002749
2750 // Determine whether the type being created is already canonical or not.
Richard Smitheefb3d52012-02-10 09:58:53 +00002751 bool isCanonical =
Douglas Gregor02dd7982013-01-17 23:36:45 +00002752 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smitheefb3d52012-02-10 09:58:53 +00002753 !EPI.HasTrailingReturn;
Reid Spencer5f016e22007-07-11 17:01:13 +00002754 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002755 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002756 isCanonical = false;
2757
Roman Divackycfe9af22011-03-01 17:40:53 +00002758 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2759 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2760 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002761
Reid Spencer5f016e22007-07-11 17:01:13 +00002762 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002763 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002764 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002765 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002766 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002767 CanonicalArgs.reserve(NumArgs);
2768 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002769 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002770
John McCalle23cf432010-12-14 08:05:40 +00002771 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +00002772 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002773 CanonicalEPI.ExceptionSpecType = EST_None;
2774 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002775 CanonicalEPI.ExtInfo
2776 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2777
Douglas Gregor02dd7982013-01-17 23:36:45 +00002778 // Result types do not have ARC lifetime qualifiers.
2779 QualType CanResultTy = getCanonicalType(ResultTy);
2780 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2781 Qualifiers Qs = CanResultTy.getQualifiers();
2782 Qs.removeObjCLifetime();
2783 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2784 }
2785
Jordan Rosebea522f2013-03-08 21:51:21 +00002786 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002787
Reid Spencer5f016e22007-07-11 17:01:13 +00002788 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002789 FunctionProtoType *NewIP =
2790 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002791 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002792 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002793
John McCallf85e1932011-06-15 23:02:42 +00002794 // FunctionProtoType objects are allocated with extra bytes after
2795 // them for three variable size arrays at the end:
2796 // - parameter types
2797 // - exception types
2798 // - consumed-arguments flags
2799 // Instead of the exception types, there could be a noexcept
Richard Smithb9d0b762012-07-27 04:22:15 +00002800 // expression, or information used to resolve the exception
2801 // specification.
John McCalle23cf432010-12-14 08:05:40 +00002802 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002803 NumArgs * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002804 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00002805 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002806 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002807 Size += sizeof(Expr*);
Richard Smithe6975e92012-04-17 00:58:00 +00002808 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smith13bffc52012-04-19 00:08:28 +00002809 Size += 2 * sizeof(FunctionDecl*);
Richard Smithb9d0b762012-07-27 04:22:15 +00002810 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2811 Size += sizeof(FunctionDecl*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002812 }
John McCallf85e1932011-06-15 23:02:42 +00002813 if (EPI.ConsumedArguments)
2814 Size += NumArgs * sizeof(bool);
2815
John McCalle23cf432010-12-14 08:05:40 +00002816 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002817 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2818 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Jordan Rosebea522f2013-03-08 21:51:21 +00002819 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002820 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002821 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002822 return QualType(FTP, 0);
2823}
2824
John McCall3cb0ebd2010-03-10 03:28:59 +00002825#ifndef NDEBUG
2826static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2827 if (!isa<CXXRecordDecl>(D)) return false;
2828 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2829 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2830 return true;
2831 if (RD->getDescribedClassTemplate() &&
2832 !isa<ClassTemplateSpecializationDecl>(RD))
2833 return true;
2834 return false;
2835}
2836#endif
2837
2838/// getInjectedClassNameType - Return the unique reference to the
2839/// injected class name type for the specified templated declaration.
2840QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002841 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002842 assert(NeedsInjectedClassNameType(Decl));
2843 if (Decl->TypeForDecl) {
2844 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregoref96ee02012-01-14 16:38:05 +00002845 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002846 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2847 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2848 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2849 } else {
John McCallf4c73712011-01-19 06:33:43 +00002850 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002851 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002852 Decl->TypeForDecl = newType;
2853 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002854 }
2855 return QualType(Decl->TypeForDecl, 0);
2856}
2857
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002858/// getTypeDeclType - Return the unique reference to the type for the
2859/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002860QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002861 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002862 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002863
Richard Smith162e1c12011-04-15 14:24:37 +00002864 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002865 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002866
John McCallbecb8d52010-03-10 06:48:02 +00002867 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2868 "Template type parameter types are always available.");
2869
John McCall19c85762010-02-16 03:57:14 +00002870 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002871 assert(!Record->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002872 "struct/union has previous declaration");
2873 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002874 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002875 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002876 assert(!Enum->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002877 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002878 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002879 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002880 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002881 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2882 Decl->TypeForDecl = newType;
2883 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002884 } else
John McCallbecb8d52010-03-10 06:48:02 +00002885 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002886
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002887 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002888}
2889
Reid Spencer5f016e22007-07-11 17:01:13 +00002890/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002891/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002892QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002893ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2894 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002895 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002896
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002897 if (Canonical.isNull())
2898 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002899 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002900 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002901 Decl->TypeForDecl = newType;
2902 Types.push_back(newType);
2903 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002904}
2905
Jay Foad4ba2a172011-01-12 09:06:06 +00002906QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002907 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2908
Douglas Gregoref96ee02012-01-14 16:38:05 +00002909 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002910 if (PrevDecl->TypeForDecl)
2911 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2912
John McCallf4c73712011-01-19 06:33:43 +00002913 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2914 Decl->TypeForDecl = newType;
2915 Types.push_back(newType);
2916 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002917}
2918
Jay Foad4ba2a172011-01-12 09:06:06 +00002919QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002920 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2921
Douglas Gregoref96ee02012-01-14 16:38:05 +00002922 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002923 if (PrevDecl->TypeForDecl)
2924 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2925
John McCallf4c73712011-01-19 06:33:43 +00002926 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2927 Decl->TypeForDecl = newType;
2928 Types.push_back(newType);
2929 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002930}
2931
John McCall9d156a72011-01-06 01:58:22 +00002932QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2933 QualType modifiedType,
2934 QualType equivalentType) {
2935 llvm::FoldingSetNodeID id;
2936 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2937
2938 void *insertPos = 0;
2939 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2940 if (type) return QualType(type, 0);
2941
2942 QualType canon = getCanonicalType(equivalentType);
2943 type = new (*this, TypeAlignment)
2944 AttributedType(canon, attrKind, modifiedType, equivalentType);
2945
2946 Types.push_back(type);
2947 AttributedTypes.InsertNode(type, insertPos);
2948
2949 return QualType(type, 0);
2950}
2951
2952
John McCall49a832b2009-10-18 09:09:24 +00002953/// \brief Retrieve a substitution-result type.
2954QualType
2955ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002956 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002957 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002958 && "replacement types must always be canonical");
2959
2960 llvm::FoldingSetNodeID ID;
2961 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2962 void *InsertPos = 0;
2963 SubstTemplateTypeParmType *SubstParm
2964 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2965
2966 if (!SubstParm) {
2967 SubstParm = new (*this, TypeAlignment)
2968 SubstTemplateTypeParmType(Parm, Replacement);
2969 Types.push_back(SubstParm);
2970 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2971 }
2972
2973 return QualType(SubstParm, 0);
2974}
2975
Douglas Gregorc3069d62011-01-14 02:55:32 +00002976/// \brief Retrieve a
2977QualType ASTContext::getSubstTemplateTypeParmPackType(
2978 const TemplateTypeParmType *Parm,
2979 const TemplateArgument &ArgPack) {
2980#ifndef NDEBUG
2981 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2982 PEnd = ArgPack.pack_end();
2983 P != PEnd; ++P) {
2984 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2985 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2986 }
2987#endif
2988
2989 llvm::FoldingSetNodeID ID;
2990 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2991 void *InsertPos = 0;
2992 if (SubstTemplateTypeParmPackType *SubstParm
2993 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2994 return QualType(SubstParm, 0);
2995
2996 QualType Canon;
2997 if (!Parm->isCanonicalUnqualified()) {
2998 Canon = getCanonicalType(QualType(Parm, 0));
2999 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3000 ArgPack);
3001 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3002 }
3003
3004 SubstTemplateTypeParmPackType *SubstParm
3005 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3006 ArgPack);
3007 Types.push_back(SubstParm);
3008 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3009 return QualType(SubstParm, 0);
3010}
3011
Douglas Gregorfab9d672009-02-05 23:33:38 +00003012/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00003013/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003014/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00003015QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003016 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003017 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00003018 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003019 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00003020 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003021 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00003022 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3023
3024 if (TypeParm)
3025 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003026
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003027 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003028 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003029 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003030
3031 TemplateTypeParmType *TypeCheck
3032 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3033 assert(!TypeCheck && "Template type parameter canonical type broken");
3034 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003035 } else
John McCall6b304a02009-09-24 23:30:46 +00003036 TypeParm = new (*this, TypeAlignment)
3037 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00003038
3039 Types.push_back(TypeParm);
3040 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3041
3042 return QualType(TypeParm, 0);
3043}
3044
John McCall3cb0ebd2010-03-10 03:28:59 +00003045TypeSourceInfo *
3046ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3047 SourceLocation NameLoc,
3048 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003049 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003050 assert(!Name.getAsDependentTemplateName() &&
3051 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00003052 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00003053
3054 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie39e6ab42013-02-18 22:06:02 +00003055 TemplateSpecializationTypeLoc TL =
3056 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara55d23c92012-02-06 14:41:24 +00003057 TL.setTemplateKeywordLoc(SourceLocation());
John McCall3cb0ebd2010-03-10 03:28:59 +00003058 TL.setTemplateNameLoc(NameLoc);
3059 TL.setLAngleLoc(Args.getLAngleLoc());
3060 TL.setRAngleLoc(Args.getRAngleLoc());
3061 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3062 TL.setArgLocInfo(i, Args[i].getLocInfo());
3063 return DI;
3064}
3065
Mike Stump1eb44332009-09-09 15:08:12 +00003066QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00003067ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00003068 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003069 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003070 assert(!Template.getAsDependentTemplateName() &&
3071 "No dependent template names here!");
3072
John McCalld5532b62009-11-23 01:53:49 +00003073 unsigned NumArgs = Args.size();
3074
Chris Lattner5f9e2722011-07-23 10:55:15 +00003075 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00003076 ArgVec.reserve(NumArgs);
3077 for (unsigned i = 0; i != NumArgs; ++i)
3078 ArgVec.push_back(Args[i].getArgument());
3079
John McCall31f17ec2010-04-27 00:57:59 +00003080 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003081 Underlying);
John McCall833ca992009-10-29 08:12:44 +00003082}
3083
Douglas Gregorb70126a2012-02-03 17:16:23 +00003084#ifndef NDEBUG
3085static bool hasAnyPackExpansions(const TemplateArgument *Args,
3086 unsigned NumArgs) {
3087 for (unsigned I = 0; I != NumArgs; ++I)
3088 if (Args[I].isPackExpansion())
3089 return true;
3090
3091 return true;
3092}
3093#endif
3094
John McCall833ca992009-10-29 08:12:44 +00003095QualType
3096ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003097 const TemplateArgument *Args,
3098 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003099 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003100 assert(!Template.getAsDependentTemplateName() &&
3101 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003102 // Look through qualified template names.
3103 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3104 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003105
Douglas Gregorb70126a2012-02-03 17:16:23 +00003106 bool IsTypeAlias =
Richard Smith3e4c6c42011-05-05 21:57:07 +00003107 Template.getAsTemplateDecl() &&
3108 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00003109 QualType CanonType;
3110 if (!Underlying.isNull())
3111 CanonType = getCanonicalType(Underlying);
3112 else {
Douglas Gregorb70126a2012-02-03 17:16:23 +00003113 // We can get here with an alias template when the specialization contains
3114 // a pack expansion that does not match up with a parameter pack.
3115 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3116 "Caller must compute aliased type");
3117 IsTypeAlias = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00003118 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3119 NumArgs);
3120 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00003121
Douglas Gregor1275ae02009-07-28 23:00:59 +00003122 // Allocate the (non-canonical) template specialization type, but don't
3123 // try to unique it: these types typically have location information that
3124 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00003125 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3126 sizeof(TemplateArgument) * NumArgs +
Douglas Gregorb70126a2012-02-03 17:16:23 +00003127 (IsTypeAlias? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00003128 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00003129 TemplateSpecializationType *Spec
Douglas Gregorb70126a2012-02-03 17:16:23 +00003130 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3131 IsTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00003132
Douglas Gregor55f6b142009-02-09 18:46:07 +00003133 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00003134 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00003135}
3136
Mike Stump1eb44332009-09-09 15:08:12 +00003137QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003138ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3139 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00003140 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003141 assert(!Template.getAsDependentTemplateName() &&
3142 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00003143
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003144 // Look through qualified template names.
3145 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3146 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003147
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003148 // Build the canonical template specialization type.
3149 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003150 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003151 CanonArgs.reserve(NumArgs);
3152 for (unsigned I = 0; I != NumArgs; ++I)
3153 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3154
3155 // Determine whether this canonical template specialization type already
3156 // exists.
3157 llvm::FoldingSetNodeID ID;
3158 TemplateSpecializationType::Profile(ID, CanonTemplate,
3159 CanonArgs.data(), NumArgs, *this);
3160
3161 void *InsertPos = 0;
3162 TemplateSpecializationType *Spec
3163 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3164
3165 if (!Spec) {
3166 // Allocate a new canonical template specialization type.
3167 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3168 sizeof(TemplateArgument) * NumArgs),
3169 TypeAlignment);
3170 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3171 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003172 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003173 Types.push_back(Spec);
3174 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3175 }
3176
3177 assert(Spec->isDependentType() &&
3178 "Non-dependent template-id type must have a canonical type");
3179 return QualType(Spec, 0);
3180}
3181
3182QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003183ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3184 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00003185 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00003186 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003187 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003188
3189 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003190 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003191 if (T)
3192 return QualType(T, 0);
3193
Douglas Gregor789b1f62010-02-04 18:10:26 +00003194 QualType Canon = NamedType;
3195 if (!Canon.isCanonical()) {
3196 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003197 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3198 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00003199 (void)CheckT;
3200 }
3201
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003202 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003203 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003204 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003205 return QualType(T, 0);
3206}
3207
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003208QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00003209ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003210 llvm::FoldingSetNodeID ID;
3211 ParenType::Profile(ID, InnerType);
3212
3213 void *InsertPos = 0;
3214 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3215 if (T)
3216 return QualType(T, 0);
3217
3218 QualType Canon = InnerType;
3219 if (!Canon.isCanonical()) {
3220 Canon = getCanonicalType(InnerType);
3221 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3222 assert(!CheckT && "Paren canonical type broken");
3223 (void)CheckT;
3224 }
3225
3226 T = new (*this) ParenType(InnerType, Canon);
3227 Types.push_back(T);
3228 ParenTypes.InsertNode(T, InsertPos);
3229 return QualType(T, 0);
3230}
3231
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003232QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3233 NestedNameSpecifier *NNS,
3234 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003235 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00003236 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3237
3238 if (Canon.isNull()) {
3239 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003240 ElaboratedTypeKeyword CanonKeyword = Keyword;
3241 if (Keyword == ETK_None)
3242 CanonKeyword = ETK_Typename;
3243
3244 if (CanonNNS != NNS || CanonKeyword != Keyword)
3245 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003246 }
3247
3248 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003249 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003250
3251 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00003252 DependentNameType *T
3253 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00003254 if (T)
3255 return QualType(T, 0);
3256
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003257 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00003258 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00003259 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003260 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00003261}
3262
Mike Stump1eb44332009-09-09 15:08:12 +00003263QualType
John McCall33500952010-06-11 00:33:02 +00003264ASTContext::getDependentTemplateSpecializationType(
3265 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003266 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00003267 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003268 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00003269 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00003270 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00003271 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3272 ArgCopy.push_back(Args[I].getArgument());
3273 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3274 ArgCopy.size(),
3275 ArgCopy.data());
3276}
3277
3278QualType
3279ASTContext::getDependentTemplateSpecializationType(
3280 ElaboratedTypeKeyword Keyword,
3281 NestedNameSpecifier *NNS,
3282 const IdentifierInfo *Name,
3283 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00003284 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003285 assert((!NNS || NNS->isDependent()) &&
3286 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00003287
Douglas Gregor789b1f62010-02-04 18:10:26 +00003288 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00003289 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3290 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003291
3292 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00003293 DependentTemplateSpecializationType *T
3294 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003295 if (T)
3296 return QualType(T, 0);
3297
John McCall33500952010-06-11 00:33:02 +00003298 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003299
John McCall33500952010-06-11 00:33:02 +00003300 ElaboratedTypeKeyword CanonKeyword = Keyword;
3301 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3302
3303 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003304 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00003305 for (unsigned I = 0; I != NumArgs; ++I) {
3306 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3307 if (!CanonArgs[I].structurallyEquals(Args[I]))
3308 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00003309 }
3310
John McCall33500952010-06-11 00:33:02 +00003311 QualType Canon;
3312 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3313 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3314 Name, NumArgs,
3315 CanonArgs.data());
3316
3317 // Find the insert position again.
3318 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3319 }
3320
3321 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3322 sizeof(TemplateArgument) * NumArgs),
3323 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00003324 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00003325 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00003326 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00003327 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003328 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00003329}
3330
Douglas Gregorcded4f62011-01-14 17:04:44 +00003331QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikiedc84cd52013-02-20 22:23:23 +00003332 Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00003333 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00003334 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003335
3336 assert(Pattern->containsUnexpandedParameterPack() &&
3337 "Pack expansions must expand one or more parameter packs");
3338 void *InsertPos = 0;
3339 PackExpansionType *T
3340 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3341 if (T)
3342 return QualType(T, 0);
3343
3344 QualType Canon;
3345 if (!Pattern.isCanonical()) {
Richard Smithd8672ef2012-07-16 00:20:35 +00003346 Canon = getCanonicalType(Pattern);
3347 // The canonical type might not contain an unexpanded parameter pack, if it
3348 // contains an alias template specialization which ignores one of its
3349 // parameters.
3350 if (Canon->containsUnexpandedParameterPack()) {
3351 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003352
Richard Smithd8672ef2012-07-16 00:20:35 +00003353 // Find the insert position again, in case we inserted an element into
3354 // PackExpansionTypes and invalidated our insert position.
3355 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3356 }
Douglas Gregor7536dd52010-12-20 02:24:11 +00003357 }
3358
Douglas Gregorcded4f62011-01-14 17:04:44 +00003359 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003360 Types.push_back(T);
3361 PackExpansionTypes.InsertNode(T, InsertPos);
3362 return QualType(T, 0);
3363}
3364
Chris Lattner88cb27a2008-04-07 04:56:42 +00003365/// CmpProtocolNames - Comparison predicate for sorting protocols
3366/// alphabetically.
3367static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3368 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003369 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00003370}
3371
John McCallc12c5bb2010-05-15 11:32:37 +00003372static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00003373 unsigned NumProtocols) {
3374 if (NumProtocols == 0) return true;
3375
Douglas Gregor61cc2962012-01-02 02:00:30 +00003376 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3377 return false;
3378
John McCall54e14c42009-10-22 22:37:11 +00003379 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregor61cc2962012-01-02 02:00:30 +00003380 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3381 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCall54e14c42009-10-22 22:37:11 +00003382 return false;
3383 return true;
3384}
3385
3386static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00003387 unsigned &NumProtocols) {
3388 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00003389
Chris Lattner88cb27a2008-04-07 04:56:42 +00003390 // Sort protocols, keyed by name.
3391 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3392
Douglas Gregor61cc2962012-01-02 02:00:30 +00003393 // Canonicalize.
3394 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3395 Protocols[I] = Protocols[I]->getCanonicalDecl();
3396
Chris Lattner88cb27a2008-04-07 04:56:42 +00003397 // Remove duplicates.
3398 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3399 NumProtocols = ProtocolsEnd-Protocols;
3400}
3401
John McCallc12c5bb2010-05-15 11:32:37 +00003402QualType ASTContext::getObjCObjectType(QualType BaseType,
3403 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00003404 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003405 // If the base type is an interface and there aren't any protocols
3406 // to add, then the interface type will do just fine.
3407 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3408 return BaseType;
3409
3410 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003411 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00003412 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003413 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00003414 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3415 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003416
John McCallc12c5bb2010-05-15 11:32:37 +00003417 // Build the canonical type, which has the canonical base type and
3418 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00003419 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00003420 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3421 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3422 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003423 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00003424 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003425 unsigned UniqueCount = NumProtocols;
3426
John McCall54e14c42009-10-22 22:37:11 +00003427 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00003428 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3429 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00003430 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00003431 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3432 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003433 }
3434
3435 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00003436 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3437 }
3438
3439 unsigned Size = sizeof(ObjCObjectTypeImpl);
3440 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3441 void *Mem = Allocate(Size, TypeAlignment);
3442 ObjCObjectTypeImpl *T =
3443 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3444
3445 Types.push_back(T);
3446 ObjCObjectTypes.InsertNode(T, InsertPos);
3447 return QualType(T, 0);
3448}
3449
3450/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3451/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003452QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003453 llvm::FoldingSetNodeID ID;
3454 ObjCObjectPointerType::Profile(ID, ObjectT);
3455
3456 void *InsertPos = 0;
3457 if (ObjCObjectPointerType *QT =
3458 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3459 return QualType(QT, 0);
3460
3461 // Find the canonical object type.
3462 QualType Canonical;
3463 if (!ObjectT.isCanonical()) {
3464 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3465
3466 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00003467 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3468 }
3469
Douglas Gregorfd6a0882010-02-08 22:59:26 +00003470 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00003471 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3472 ObjCObjectPointerType *QType =
3473 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00003474
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003475 Types.push_back(QType);
3476 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00003477 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003478}
Chris Lattner88cb27a2008-04-07 04:56:42 +00003479
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003480/// getObjCInterfaceType - Return the unique reference to the type for the
3481/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00003482QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3483 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003484 if (Decl->TypeForDecl)
3485 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003486
Douglas Gregor0af55012011-12-16 03:12:41 +00003487 if (PrevDecl) {
3488 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3489 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3490 return QualType(PrevDecl->TypeForDecl, 0);
3491 }
3492
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00003493 // Prefer the definition, if there is one.
3494 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3495 Decl = Def;
3496
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003497 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3498 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3499 Decl->TypeForDecl = T;
3500 Types.push_back(T);
3501 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00003502}
3503
Douglas Gregor72564e72009-02-26 23:50:07 +00003504/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3505/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00003506/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00003507/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003508/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003509QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003510 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00003511 if (tofExpr->isTypeDependent()) {
3512 llvm::FoldingSetNodeID ID;
3513 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00003514
Douglas Gregorb1975722009-07-30 23:18:24 +00003515 void *InsertPos = 0;
3516 DependentTypeOfExprType *Canon
3517 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3518 if (Canon) {
3519 // We already have a "canonical" version of an identical, dependent
3520 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00003521 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00003522 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003523 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00003524 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003525 Canon
3526 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00003527 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3528 toe = Canon;
3529 }
3530 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003531 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00003532 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00003533 }
Steve Naroff9752f252007-08-01 18:02:17 +00003534 Types.push_back(toe);
3535 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003536}
3537
Steve Naroff9752f252007-08-01 18:02:17 +00003538/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3539/// TypeOfType AST's. The only motivation to unique these nodes would be
3540/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003541/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003542/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003543QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00003544 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00003545 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00003546 Types.push_back(tot);
3547 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003548}
3549
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00003550
Anders Carlsson395b4752009-06-24 19:06:50 +00003551/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3552/// DecltypeType AST's. The only motivation to unique these nodes would be
3553/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003554/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00003555/// on canonical types (which are always unique).
Douglas Gregorf8af9822012-02-12 18:42:33 +00003556QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003557 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00003558
3559 // C++0x [temp.type]p2:
3560 // If an expression e involves a template parameter, decltype(e) denotes a
3561 // unique dependent type. Two such decltype-specifiers refer to the same
3562 // type only if their expressions are equivalent (14.5.6.1).
3563 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003564 llvm::FoldingSetNodeID ID;
3565 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00003566
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003567 void *InsertPos = 0;
3568 DependentDecltypeType *Canon
3569 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3570 if (Canon) {
3571 // We already have a "canonical" version of an equivalent, dependent
3572 // decltype type. Use that as our canonical type.
Richard Smith0d729102012-08-13 20:08:14 +00003573 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003574 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003575 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003576 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003577 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003578 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3579 dt = Canon;
3580 }
3581 } else {
Douglas Gregorf8af9822012-02-12 18:42:33 +00003582 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3583 getCanonicalType(UnderlyingType));
Douglas Gregordd0257c2009-07-08 00:03:05 +00003584 }
Anders Carlsson395b4752009-06-24 19:06:50 +00003585 Types.push_back(dt);
3586 return QualType(dt, 0);
3587}
3588
Sean Huntca63c202011-05-24 22:41:36 +00003589/// getUnaryTransformationType - We don't unique these, since the memory
3590/// savings are minimal and these are rare.
3591QualType ASTContext::getUnaryTransformType(QualType BaseType,
3592 QualType UnderlyingType,
3593 UnaryTransformType::UTTKind Kind)
3594 const {
3595 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00003596 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3597 Kind,
3598 UnderlyingType->isDependentType() ?
Peter Collingbourne12fc4b02012-03-05 16:02:06 +00003599 QualType() : getCanonicalType(UnderlyingType));
Sean Huntca63c202011-05-24 22:41:36 +00003600 Types.push_back(Ty);
3601 return QualType(Ty, 0);
3602}
3603
Richard Smith60e141e2013-05-04 07:00:32 +00003604/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3605/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3606/// canonical deduced-but-dependent 'auto' type.
3607QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Richard Smithdc7a4f52013-04-30 13:56:41 +00003608 bool IsDependent) const {
Richard Smith60e141e2013-05-04 07:00:32 +00003609 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
3610 return getAutoDeductType();
3611
3612 // Look in the folding set for an existing type.
Richard Smith483b9f32011-02-21 20:05:19 +00003613 void *InsertPos = 0;
Richard Smith60e141e2013-05-04 07:00:32 +00003614 llvm::FoldingSetNodeID ID;
3615 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
3616 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3617 return QualType(AT, 0);
Richard Smith483b9f32011-02-21 20:05:19 +00003618
Richard Smitha2c36462013-04-26 16:15:35 +00003619 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithdc7a4f52013-04-30 13:56:41 +00003620 IsDecltypeAuto,
3621 IsDependent);
Richard Smith483b9f32011-02-21 20:05:19 +00003622 Types.push_back(AT);
3623 if (InsertPos)
3624 AutoTypes.InsertNode(AT, InsertPos);
3625 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00003626}
3627
Eli Friedmanb001de72011-10-06 23:00:33 +00003628/// getAtomicType - Return the uniqued reference to the atomic type for
3629/// the given value type.
3630QualType ASTContext::getAtomicType(QualType T) const {
3631 // Unique pointers, to guarantee there is only one pointer of a particular
3632 // structure.
3633 llvm::FoldingSetNodeID ID;
3634 AtomicType::Profile(ID, T);
3635
3636 void *InsertPos = 0;
3637 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3638 return QualType(AT, 0);
3639
3640 // If the atomic value type isn't canonical, this won't be a canonical type
3641 // either, so fill in the canonical type field.
3642 QualType Canonical;
3643 if (!T.isCanonical()) {
3644 Canonical = getAtomicType(getCanonicalType(T));
3645
3646 // Get the new insert position for the node we care about.
3647 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3648 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3649 }
3650 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3651 Types.push_back(New);
3652 AtomicTypes.InsertNode(New, InsertPos);
3653 return QualType(New, 0);
3654}
3655
Richard Smithad762fc2011-04-14 22:09:26 +00003656/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3657QualType ASTContext::getAutoDeductType() const {
3658 if (AutoDeductTy.isNull())
Richard Smith60e141e2013-05-04 07:00:32 +00003659 AutoDeductTy = QualType(
3660 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
3661 /*dependent*/false),
3662 0);
Richard Smithad762fc2011-04-14 22:09:26 +00003663 return AutoDeductTy;
3664}
3665
3666/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3667QualType ASTContext::getAutoRRefDeductType() const {
3668 if (AutoRRefDeductTy.isNull())
3669 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3670 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3671 return AutoRRefDeductTy;
3672}
3673
Reid Spencer5f016e22007-07-11 17:01:13 +00003674/// getTagDeclType - Return the unique reference to the type for the
3675/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003676QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003677 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003678 // FIXME: What is the design on getTagDeclType when it requires casting
3679 // away const? mutable?
3680 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003681}
3682
Mike Stump1eb44332009-09-09 15:08:12 +00003683/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3684/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3685/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003686CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003687 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003688}
3689
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003690/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3691CanQualType ASTContext::getIntMaxType() const {
3692 return getFromTargetType(Target->getIntMaxType());
3693}
3694
3695/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3696CanQualType ASTContext::getUIntMaxType() const {
3697 return getFromTargetType(Target->getUIntMaxType());
3698}
3699
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003700/// getSignedWCharType - Return the type of "signed wchar_t".
3701/// Used when in C++, as a GCC extension.
3702QualType ASTContext::getSignedWCharType() const {
3703 // FIXME: derive from "Target" ?
3704 return WCharTy;
3705}
3706
3707/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3708/// Used when in C++, as a GCC extension.
3709QualType ASTContext::getUnsignedWCharType() const {
3710 // FIXME: derive from "Target" ?
3711 return UnsignedIntTy;
3712}
3713
Enea Zaffanella9677eb82013-01-26 17:08:37 +00003714QualType ASTContext::getIntPtrType() const {
3715 return getFromTargetType(Target->getIntPtrType());
3716}
3717
3718QualType ASTContext::getUIntPtrType() const {
3719 return getCorrespondingUnsignedType(getIntPtrType());
3720}
3721
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003722/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003723/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3724QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003725 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003726}
3727
Eli Friedman6902e412012-11-27 02:58:24 +00003728/// \brief Return the unique type for "pid_t" defined in
3729/// <sys/types.h>. We need this to compute the correct type for vfork().
3730QualType ASTContext::getProcessIDType() const {
3731 return getFromTargetType(Target->getProcessIDType());
3732}
3733
Chris Lattnere6327742008-04-02 05:18:44 +00003734//===----------------------------------------------------------------------===//
3735// Type Operators
3736//===----------------------------------------------------------------------===//
3737
Jay Foad4ba2a172011-01-12 09:06:06 +00003738CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003739 // Push qualifiers into arrays, and then discard any remaining
3740 // qualifiers.
3741 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003742 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003743 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003744 QualType Result;
3745 if (isa<ArrayType>(Ty)) {
3746 Result = getArrayDecayedType(QualType(Ty,0));
3747 } else if (isa<FunctionType>(Ty)) {
3748 Result = getPointerType(QualType(Ty, 0));
3749 } else {
3750 Result = QualType(Ty, 0);
3751 }
3752
3753 return CanQualType::CreateUnsafe(Result);
3754}
3755
John McCall62c28c82011-01-18 07:41:22 +00003756QualType ASTContext::getUnqualifiedArrayType(QualType type,
3757 Qualifiers &quals) {
3758 SplitQualType splitType = type.getSplitUnqualifiedType();
3759
3760 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3761 // the unqualified desugared type and then drops it on the floor.
3762 // We then have to strip that sugar back off with
3763 // getUnqualifiedDesugaredType(), which is silly.
3764 const ArrayType *AT =
John McCall200fa532012-02-08 00:46:36 +00003765 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall62c28c82011-01-18 07:41:22 +00003766
3767 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003768 if (!AT) {
John McCall200fa532012-02-08 00:46:36 +00003769 quals = splitType.Quals;
3770 return QualType(splitType.Ty, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003771 }
3772
John McCall62c28c82011-01-18 07:41:22 +00003773 // Otherwise, recurse on the array's element type.
3774 QualType elementType = AT->getElementType();
3775 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3776
3777 // If that didn't change the element type, AT has no qualifiers, so we
3778 // can just use the results in splitType.
3779 if (elementType == unqualElementType) {
3780 assert(quals.empty()); // from the recursive call
John McCall200fa532012-02-08 00:46:36 +00003781 quals = splitType.Quals;
3782 return QualType(splitType.Ty, 0);
John McCall62c28c82011-01-18 07:41:22 +00003783 }
3784
3785 // Otherwise, add in the qualifiers from the outermost type, then
3786 // build the type back up.
John McCall200fa532012-02-08 00:46:36 +00003787 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003788
Douglas Gregor9dadd942010-05-17 18:45:21 +00003789 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003790 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003791 CAT->getSizeModifier(), 0);
3792 }
3793
Douglas Gregor9dadd942010-05-17 18:45:21 +00003794 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003795 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003796 }
3797
Douglas Gregor9dadd942010-05-17 18:45:21 +00003798 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003799 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003800 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003801 VAT->getSizeModifier(),
3802 VAT->getIndexTypeCVRQualifiers(),
3803 VAT->getBracketsRange());
3804 }
3805
3806 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003807 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003808 DSAT->getSizeModifier(), 0,
3809 SourceRange());
3810}
3811
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003812/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3813/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3814/// they point to and return true. If T1 and T2 aren't pointer types
3815/// or pointer-to-member types, or if they are not similar at this
3816/// level, returns false and leaves T1 and T2 unchanged. Top-level
3817/// qualifiers on T1 and T2 are ignored. This function will typically
3818/// be called in a loop that successively "unwraps" pointer and
3819/// pointer-to-member types to compare them at each level.
3820bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3821 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3822 *T2PtrType = T2->getAs<PointerType>();
3823 if (T1PtrType && T2PtrType) {
3824 T1 = T1PtrType->getPointeeType();
3825 T2 = T2PtrType->getPointeeType();
3826 return true;
3827 }
3828
3829 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3830 *T2MPType = T2->getAs<MemberPointerType>();
3831 if (T1MPType && T2MPType &&
3832 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3833 QualType(T2MPType->getClass(), 0))) {
3834 T1 = T1MPType->getPointeeType();
3835 T2 = T2MPType->getPointeeType();
3836 return true;
3837 }
3838
David Blaikie4e4d0842012-03-11 07:00:24 +00003839 if (getLangOpts().ObjC1) {
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003840 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3841 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3842 if (T1OPType && T2OPType) {
3843 T1 = T1OPType->getPointeeType();
3844 T2 = T2OPType->getPointeeType();
3845 return true;
3846 }
3847 }
3848
3849 // FIXME: Block pointers, too?
3850
3851 return false;
3852}
3853
Jay Foad4ba2a172011-01-12 09:06:06 +00003854DeclarationNameInfo
3855ASTContext::getNameForTemplate(TemplateName Name,
3856 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003857 switch (Name.getKind()) {
3858 case TemplateName::QualifiedTemplate:
3859 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003860 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003861 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3862 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003863
John McCall14606042011-06-30 08:33:18 +00003864 case TemplateName::OverloadedTemplate: {
3865 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3866 // DNInfo work in progress: CHECKME: what about DNLoc?
3867 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3868 }
3869
3870 case TemplateName::DependentTemplate: {
3871 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003872 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003873 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003874 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3875 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003876 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003877 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3878 // DNInfo work in progress: FIXME: source locations?
3879 DeclarationNameLoc DNLoc;
3880 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3881 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3882 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003883 }
3884 }
3885
John McCall14606042011-06-30 08:33:18 +00003886 case TemplateName::SubstTemplateTemplateParm: {
3887 SubstTemplateTemplateParmStorage *subst
3888 = Name.getAsSubstTemplateTemplateParm();
3889 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3890 NameLoc);
3891 }
3892
3893 case TemplateName::SubstTemplateTemplateParmPack: {
3894 SubstTemplateTemplateParmPackStorage *subst
3895 = Name.getAsSubstTemplateTemplateParmPack();
3896 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3897 NameLoc);
3898 }
3899 }
3900
3901 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003902}
3903
Jay Foad4ba2a172011-01-12 09:06:06 +00003904TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003905 switch (Name.getKind()) {
3906 case TemplateName::QualifiedTemplate:
3907 case TemplateName::Template: {
3908 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003909 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003910 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003911 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3912
3913 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003914 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003915 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003916
John McCall14606042011-06-30 08:33:18 +00003917 case TemplateName::OverloadedTemplate:
3918 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003919
John McCall14606042011-06-30 08:33:18 +00003920 case TemplateName::DependentTemplate: {
3921 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3922 assert(DTN && "Non-dependent template names must refer to template decls.");
3923 return DTN->CanonicalTemplateName;
3924 }
3925
3926 case TemplateName::SubstTemplateTemplateParm: {
3927 SubstTemplateTemplateParmStorage *subst
3928 = Name.getAsSubstTemplateTemplateParm();
3929 return getCanonicalTemplateName(subst->getReplacement());
3930 }
3931
3932 case TemplateName::SubstTemplateTemplateParmPack: {
3933 SubstTemplateTemplateParmPackStorage *subst
3934 = Name.getAsSubstTemplateTemplateParmPack();
3935 TemplateTemplateParmDecl *canonParameter
3936 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3937 TemplateArgument canonArgPack
3938 = getCanonicalTemplateArgument(subst->getArgumentPack());
3939 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3940 }
3941 }
3942
3943 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003944}
3945
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003946bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3947 X = getCanonicalTemplateName(X);
3948 Y = getCanonicalTemplateName(Y);
3949 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3950}
3951
Mike Stump1eb44332009-09-09 15:08:12 +00003952TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003953ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003954 switch (Arg.getKind()) {
3955 case TemplateArgument::Null:
3956 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003957
Douglas Gregor1275ae02009-07-28 23:00:59 +00003958 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003959 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003960
Douglas Gregord2008e22012-04-06 22:40:38 +00003961 case TemplateArgument::Declaration: {
Eli Friedmand7a6b162012-09-26 02:36:12 +00003962 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
3963 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregord2008e22012-04-06 22:40:38 +00003964 }
Mike Stump1eb44332009-09-09 15:08:12 +00003965
Eli Friedmand7a6b162012-09-26 02:36:12 +00003966 case TemplateArgument::NullPtr:
3967 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
3968 /*isNullPtr*/true);
3969
Douglas Gregor788cd062009-11-11 01:00:40 +00003970 case TemplateArgument::Template:
3971 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003972
3973 case TemplateArgument::TemplateExpansion:
3974 return TemplateArgument(getCanonicalTemplateName(
3975 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00003976 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00003977
Douglas Gregor1275ae02009-07-28 23:00:59 +00003978 case TemplateArgument::Integral:
Benjamin Kramer85524372012-06-07 15:09:51 +00003979 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003980
Douglas Gregor1275ae02009-07-28 23:00:59 +00003981 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00003982 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003983
Douglas Gregor1275ae02009-07-28 23:00:59 +00003984 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00003985 if (Arg.pack_size() == 0)
3986 return Arg;
3987
Douglas Gregor910f8002010-11-07 23:05:16 +00003988 TemplateArgument *CanonArgs
3989 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00003990 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003991 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003992 AEnd = Arg.pack_end();
3993 A != AEnd; (void)++A, ++Idx)
3994 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00003995
Douglas Gregor910f8002010-11-07 23:05:16 +00003996 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00003997 }
3998 }
3999
4000 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00004001 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00004002}
4003
Douglas Gregord57959a2009-03-27 23:10:48 +00004004NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00004005ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004006 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00004007 return 0;
4008
4009 switch (NNS->getKind()) {
4010 case NestedNameSpecifier::Identifier:
4011 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00004012 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00004013 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4014 NNS->getAsIdentifier());
4015
4016 case NestedNameSpecifier::Namespace:
4017 // A namespace is canonical; build a nested-name-specifier with
4018 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00004019 return NestedNameSpecifier::Create(*this, 0,
4020 NNS->getAsNamespace()->getOriginalNamespace());
4021
4022 case NestedNameSpecifier::NamespaceAlias:
4023 // A namespace is canonical; build a nested-name-specifier with
4024 // this namespace and no prefix.
4025 return NestedNameSpecifier::Create(*this, 0,
4026 NNS->getAsNamespaceAlias()->getNamespace()
4027 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00004028
4029 case NestedNameSpecifier::TypeSpec:
4030 case NestedNameSpecifier::TypeSpecWithTemplate: {
4031 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00004032
4033 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4034 // break it apart into its prefix and identifier, then reconsititute those
4035 // as the canonical nested-name-specifier. This is required to canonicalize
4036 // a dependent nested-name-specifier involving typedefs of dependent-name
4037 // types, e.g.,
4038 // typedef typename T::type T1;
4039 // typedef typename T1::type T2;
Eli Friedman16412ef2012-03-03 04:09:56 +00004040 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4041 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor264bf662010-11-04 00:09:33 +00004042 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor264bf662010-11-04 00:09:33 +00004043
Eli Friedman16412ef2012-03-03 04:09:56 +00004044 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4045 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4046 // first place?
John McCall3b657512011-01-19 10:06:00 +00004047 return NestedNameSpecifier::Create(*this, 0, false,
4048 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00004049 }
4050
4051 case NestedNameSpecifier::Global:
4052 // The global specifier is canonical and unique.
4053 return NNS;
4054 }
4055
David Blaikie7530c032012-01-17 06:56:22 +00004056 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregord57959a2009-03-27 23:10:48 +00004057}
4058
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004059
Jay Foad4ba2a172011-01-12 09:06:06 +00004060const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004061 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004062 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004063 // Handle the common positive case fast.
4064 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4065 return AT;
4066 }
Mike Stump1eb44332009-09-09 15:08:12 +00004067
John McCall0953e762009-09-24 19:53:00 +00004068 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00004069 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004070 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004071
John McCall0953e762009-09-24 19:53:00 +00004072 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004073 // implements C99 6.7.3p8: "If the specification of an array type includes
4074 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00004075
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004076 // If we get here, we either have type qualifiers on the type, or we have
4077 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00004078 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00004079
John McCall3b657512011-01-19 10:06:00 +00004080 SplitQualType split = T.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004081 Qualifiers qs = split.Quals;
Mike Stump1eb44332009-09-09 15:08:12 +00004082
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004083 // If we have a simple case, just return now.
John McCall200fa532012-02-08 00:46:36 +00004084 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall3b657512011-01-19 10:06:00 +00004085 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004086 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00004087
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004088 // Otherwise, we have an array and we have qualifiers on it. Push the
4089 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00004090 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00004091
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004092 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4093 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4094 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004095 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004096 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4097 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4098 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004099 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00004100
Mike Stump1eb44332009-09-09 15:08:12 +00004101 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00004102 = dyn_cast<DependentSizedArrayType>(ATy))
4103 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00004104 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00004105 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00004106 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004107 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004108 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00004109
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004110 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004111 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00004112 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004113 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004114 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004115 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00004116}
4117
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004118QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004119 // C99 6.7.5.3p7:
4120 // A declaration of a parameter as "array of type" shall be
4121 // adjusted to "qualified pointer to type", where the type
4122 // qualifiers (if any) are those specified within the [ and ] of
4123 // the array type derivation.
4124 if (T->isArrayType())
4125 return getArrayDecayedType(T);
4126
4127 // C99 6.7.5.3p8:
4128 // A declaration of a parameter as "function returning type"
4129 // shall be adjusted to "pointer to function returning type", as
4130 // in 6.3.2.1.
4131 if (T->isFunctionType())
4132 return getPointerType(T);
4133
4134 return T;
4135}
4136
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004137QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004138 T = getVariableArrayDecayedType(T);
4139 T = getAdjustedParameterType(T);
4140 return T.getUnqualifiedType();
4141}
4142
Chris Lattnere6327742008-04-02 05:18:44 +00004143/// getArrayDecayedType - Return the properly qualified result of decaying the
4144/// specified array type to a pointer. This operation is non-trivial when
4145/// handling typedefs etc. The canonical type of "T" must be an array type,
4146/// this returns a pointer to a properly qualified element of the array.
4147///
4148/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00004149QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004150 // Get the element type with 'getAsArrayType' so that we don't lose any
4151 // typedefs in the element type of the array. This also handles propagation
4152 // of type qualifiers from the array type into the element type if present
4153 // (C99 6.7.3p8).
4154 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4155 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00004156
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004157 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00004158
4159 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00004160 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00004161}
4162
John McCall3b657512011-01-19 10:06:00 +00004163QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4164 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00004165}
4166
John McCall3b657512011-01-19 10:06:00 +00004167QualType ASTContext::getBaseElementType(QualType type) const {
4168 Qualifiers qs;
4169 while (true) {
4170 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004171 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall3b657512011-01-19 10:06:00 +00004172 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00004173
John McCall3b657512011-01-19 10:06:00 +00004174 type = array->getElementType();
John McCall200fa532012-02-08 00:46:36 +00004175 qs.addConsistentQualifiers(split.Quals);
John McCall3b657512011-01-19 10:06:00 +00004176 }
Mike Stump1eb44332009-09-09 15:08:12 +00004177
John McCall3b657512011-01-19 10:06:00 +00004178 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00004179}
4180
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004181/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00004182uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004183ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4184 uint64_t ElementCount = 1;
4185 do {
4186 ElementCount *= CA->getSize().getZExtValue();
Richard Smithd5e83942012-12-06 03:04:50 +00004187 CA = dyn_cast_or_null<ConstantArrayType>(
4188 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004189 } while (CA);
4190 return ElementCount;
4191}
4192
Reid Spencer5f016e22007-07-11 17:01:13 +00004193/// getFloatingRank - Return a relative rank for floating point types.
4194/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00004195static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00004196 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00004197 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00004198
John McCall183700f2009-09-21 23:43:11 +00004199 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4200 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004201 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00004202 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00004203 case BuiltinType::Float: return FloatRank;
4204 case BuiltinType::Double: return DoubleRank;
4205 case BuiltinType::LongDouble: return LongDoubleRank;
4206 }
4207}
4208
Mike Stump1eb44332009-09-09 15:08:12 +00004209/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4210/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00004211/// 'typeDomain' is a real floating point or complex type.
4212/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00004213QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4214 QualType Domain) const {
4215 FloatingRank EltRank = getFloatingRank(Size);
4216 if (Domain->isComplexType()) {
4217 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00004218 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Narofff1448a02007-08-27 01:27:54 +00004219 case FloatRank: return FloatComplexTy;
4220 case DoubleRank: return DoubleComplexTy;
4221 case LongDoubleRank: return LongDoubleComplexTy;
4222 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004223 }
Chris Lattner1361b112008-04-06 23:58:54 +00004224
4225 assert(Domain->isRealFloatingType() && "Unknown domain!");
4226 switch (EltRank) {
Joey Gouly19dbb202013-01-23 11:56:20 +00004227 case HalfRank: return HalfTy;
Chris Lattner1361b112008-04-06 23:58:54 +00004228 case FloatRank: return FloatTy;
4229 case DoubleRank: return DoubleTy;
4230 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00004231 }
David Blaikie561d3ab2012-01-17 02:30:50 +00004232 llvm_unreachable("getFloatingRank(): illegal value for rank");
Reid Spencer5f016e22007-07-11 17:01:13 +00004233}
4234
Chris Lattner7cfeb082008-04-06 23:55:33 +00004235/// getFloatingTypeOrder - Compare the rank of the two specified floating
4236/// point types, ignoring the domain of the type (i.e. 'double' ==
4237/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004238/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004239int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00004240 FloatingRank LHSR = getFloatingRank(LHS);
4241 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004242
Chris Lattnera75cea32008-04-06 23:38:49 +00004243 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004244 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00004245 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004246 return 1;
4247 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004248}
4249
Chris Lattnerf52ab252008-04-06 22:59:24 +00004250/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4251/// routine will assert if passed a built-in type that isn't an integer or enum,
4252/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00004253unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00004254 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00004255
Chris Lattnerf52ab252008-04-06 22:59:24 +00004256 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004257 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00004258 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004259 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004260 case BuiltinType::Char_S:
4261 case BuiltinType::Char_U:
4262 case BuiltinType::SChar:
4263 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004264 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004265 case BuiltinType::Short:
4266 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004267 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004268 case BuiltinType::Int:
4269 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004270 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004271 case BuiltinType::Long:
4272 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004273 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004274 case BuiltinType::LongLong:
4275 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004276 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00004277 case BuiltinType::Int128:
4278 case BuiltinType::UInt128:
4279 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00004280 }
4281}
4282
Eli Friedman04e83572009-08-20 04:21:42 +00004283/// \brief Whether this is a promotable bitfield reference according
4284/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4285///
4286/// \returns the type this bit-field will promote to, or NULL if no
4287/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00004288QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00004289 if (E->isTypeDependent() || E->isValueDependent())
4290 return QualType();
4291
John McCall993f43f2013-05-06 21:39:12 +00004292 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman04e83572009-08-20 04:21:42 +00004293 if (!Field)
4294 return QualType();
4295
4296 QualType FT = Field->getType();
4297
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004298 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00004299 uint64_t IntSize = getTypeSize(IntTy);
4300 // GCC extension compatibility: if the bit-field size is less than or equal
4301 // to the size of int, it gets promoted no matter what its type is.
4302 // For instance, unsigned long bf : 4 gets promoted to signed int.
4303 if (BitWidth < IntSize)
4304 return IntTy;
4305
4306 if (BitWidth == IntSize)
4307 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4308
4309 // Types bigger than int are not subject to promotions, and therefore act
4310 // like the base type.
4311 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4312 // is ridiculous.
4313 return QualType();
4314}
4315
Eli Friedmana95d7572009-08-19 07:44:53 +00004316/// getPromotedIntegerType - Returns the type that Promotable will
4317/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4318/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00004319QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00004320 assert(!Promotable.isNull());
4321 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00004322 if (const EnumType *ET = Promotable->getAs<EnumType>())
4323 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00004324
4325 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4326 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4327 // (3.9.1) can be converted to a prvalue of the first of the following
4328 // types that can represent all the values of its underlying type:
4329 // int, unsigned int, long int, unsigned long int, long long int, or
4330 // unsigned long long int [...]
4331 // FIXME: Is there some better way to compute this?
4332 if (BT->getKind() == BuiltinType::WChar_S ||
4333 BT->getKind() == BuiltinType::WChar_U ||
4334 BT->getKind() == BuiltinType::Char16 ||
4335 BT->getKind() == BuiltinType::Char32) {
4336 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4337 uint64_t FromSize = getTypeSize(BT);
4338 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4339 LongLongTy, UnsignedLongLongTy };
4340 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4341 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4342 if (FromSize < ToSize ||
4343 (FromSize == ToSize &&
4344 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4345 return PromoteTypes[Idx];
4346 }
4347 llvm_unreachable("char type should fit into long long");
4348 }
4349 }
4350
4351 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00004352 if (Promotable->isSignedIntegerType())
4353 return IntTy;
Eli Friedman5b64e772012-11-15 01:21:59 +00004354 uint64_t PromotableSize = getIntWidth(Promotable);
4355 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedmana95d7572009-08-19 07:44:53 +00004356 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4357 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4358}
4359
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004360/// \brief Recurses in pointer/array types until it finds an objc retainable
4361/// type and returns its ownership.
4362Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4363 while (!T.isNull()) {
4364 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4365 return T.getObjCLifetime();
4366 if (T->isArrayType())
4367 T = getBaseElementType(T);
4368 else if (const PointerType *PT = T->getAs<PointerType>())
4369 T = PT->getPointeeType();
4370 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00004371 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004372 else
4373 break;
4374 }
4375
4376 return Qualifiers::OCL_None;
4377}
4378
Mike Stump1eb44332009-09-09 15:08:12 +00004379/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00004380/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004381/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004382int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00004383 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4384 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00004385 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004386
Chris Lattnerf52ab252008-04-06 22:59:24 +00004387 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4388 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00004389
Chris Lattner7cfeb082008-04-06 23:55:33 +00004390 unsigned LHSRank = getIntegerRank(LHSC);
4391 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00004392
Chris Lattner7cfeb082008-04-06 23:55:33 +00004393 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4394 if (LHSRank == RHSRank) return 0;
4395 return LHSRank > RHSRank ? 1 : -1;
4396 }
Mike Stump1eb44332009-09-09 15:08:12 +00004397
Chris Lattner7cfeb082008-04-06 23:55:33 +00004398 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4399 if (LHSUnsigned) {
4400 // If the unsigned [LHS] type is larger, return it.
4401 if (LHSRank >= RHSRank)
4402 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004403
Chris Lattner7cfeb082008-04-06 23:55:33 +00004404 // If the signed type can represent all values of the unsigned type, it
4405 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004406 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004407 return -1;
4408 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00004409
Chris Lattner7cfeb082008-04-06 23:55:33 +00004410 // If the unsigned [RHS] type is larger, return it.
4411 if (RHSRank >= LHSRank)
4412 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00004413
Chris Lattner7cfeb082008-04-06 23:55:33 +00004414 // If the signed type can represent all values of the unsigned type, it
4415 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004416 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004417 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004418}
Anders Carlsson71993dd2007-08-17 05:31:46 +00004419
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004420static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004421CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4422 DeclContext *DC, IdentifierInfo *Id) {
4423 SourceLocation Loc;
David Blaikie4e4d0842012-03-11 07:00:24 +00004424 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004425 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004426 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004427 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004428}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004429
Mike Stump1eb44332009-09-09 15:08:12 +00004430// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00004431QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00004432 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004433 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004434 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004435 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00004436 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004437
Anders Carlssonf06273f2007-11-19 00:25:30 +00004438 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00004439
Anders Carlsson71993dd2007-08-17 05:31:46 +00004440 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00004441 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00004442 // int flags;
4443 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00004444 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00004445 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00004446 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00004447 FieldTypes[3] = LongTy;
4448
Anders Carlsson71993dd2007-08-17 05:31:46 +00004449 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00004450 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00004451 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004452 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00004453 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00004454 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00004455 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004456 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004457 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004458 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004459 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00004460 }
4461
Douglas Gregor838db382010-02-11 01:19:42 +00004462 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00004463 }
Mike Stump1eb44332009-09-09 15:08:12 +00004464
Anders Carlsson71993dd2007-08-17 05:31:46 +00004465 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00004466}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004467
Fariborz Jahanianf7992132013-01-04 18:45:40 +00004468QualType ASTContext::getObjCSuperType() const {
4469 if (ObjCSuperType.isNull()) {
4470 RecordDecl *ObjCSuperTypeDecl =
4471 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4472 TUDecl->addDecl(ObjCSuperTypeDecl);
4473 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4474 }
4475 return ObjCSuperType;
4476}
4477
Douglas Gregor319ac892009-04-23 22:29:11 +00004478void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004479 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00004480 assert(Rec && "Invalid CFConstantStringType");
4481 CFConstantStringTypeDecl = Rec->getDecl();
4482}
4483
Jay Foad4ba2a172011-01-12 09:06:06 +00004484QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00004485 if (BlockDescriptorType)
4486 return getTagDeclType(BlockDescriptorType);
4487
4488 RecordDecl *T;
4489 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004490 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004491 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00004492 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004493
4494 QualType FieldTypes[] = {
4495 UnsignedLongTy,
4496 UnsignedLongTy,
4497 };
4498
4499 const char *FieldNames[] = {
4500 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00004501 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00004502 };
4503
4504 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004505 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00004506 SourceLocation(),
4507 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004508 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00004509 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004510 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004511 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004512 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00004513 T->addDecl(Field);
4514 }
4515
Douglas Gregor838db382010-02-11 01:19:42 +00004516 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004517
4518 BlockDescriptorType = T;
4519
4520 return getTagDeclType(BlockDescriptorType);
4521}
4522
Jay Foad4ba2a172011-01-12 09:06:06 +00004523QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00004524 if (BlockDescriptorExtendedType)
4525 return getTagDeclType(BlockDescriptorExtendedType);
4526
4527 RecordDecl *T;
4528 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004529 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004530 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00004531 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004532
4533 QualType FieldTypes[] = {
4534 UnsignedLongTy,
4535 UnsignedLongTy,
4536 getPointerType(VoidPtrTy),
4537 getPointerType(VoidPtrTy)
4538 };
4539
4540 const char *FieldNames[] = {
4541 "reserved",
4542 "Size",
4543 "CopyFuncPtr",
4544 "DestroyFuncPtr"
4545 };
4546
4547 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004548 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00004549 SourceLocation(),
4550 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004551 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00004552 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004553 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004554 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004555 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00004556 T->addDecl(Field);
4557 }
4558
Douglas Gregor838db382010-02-11 01:19:42 +00004559 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004560
4561 BlockDescriptorExtendedType = T;
4562
4563 return getTagDeclType(BlockDescriptorExtendedType);
4564}
4565
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004566/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4567/// requires copy/dispose. Note that this must match the logic
4568/// in buildByrefHelpers.
4569bool ASTContext::BlockRequiresCopying(QualType Ty,
4570 const VarDecl *D) {
4571 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4572 const Expr *copyExpr = getBlockVarCopyInits(D);
4573 if (!copyExpr && record->hasTrivialDestructor()) return false;
4574
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004575 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00004576 }
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004577
4578 if (!Ty->isObjCRetainableType()) return false;
4579
4580 Qualifiers qs = Ty.getQualifiers();
4581
4582 // If we have lifetime, that dominates.
4583 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4584 assert(getLangOpts().ObjCAutoRefCount);
4585
4586 switch (lifetime) {
4587 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4588
4589 // These are just bits as far as the runtime is concerned.
4590 case Qualifiers::OCL_ExplicitNone:
4591 case Qualifiers::OCL_Autoreleasing:
4592 return false;
4593
4594 // Tell the runtime that this is ARC __weak, called by the
4595 // byref routines.
4596 case Qualifiers::OCL_Weak:
4597 // ARC __strong __block variables need to be retained.
4598 case Qualifiers::OCL_Strong:
4599 return true;
4600 }
4601 llvm_unreachable("fell out of lifetime switch!");
4602 }
4603 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4604 Ty->isObjCObjectPointerType());
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004605}
4606
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004607bool ASTContext::getByrefLifetime(QualType Ty,
4608 Qualifiers::ObjCLifetime &LifeTime,
4609 bool &HasByrefExtendedLayout) const {
4610
4611 if (!getLangOpts().ObjC1 ||
4612 getLangOpts().getGC() != LangOptions::NonGC)
4613 return false;
4614
4615 HasByrefExtendedLayout = false;
Fariborz Jahanian34db84f2012-12-11 19:58:01 +00004616 if (Ty->isRecordType()) {
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004617 HasByrefExtendedLayout = true;
4618 LifeTime = Qualifiers::OCL_None;
4619 }
4620 else if (getLangOpts().ObjCAutoRefCount)
4621 LifeTime = Ty.getObjCLifetime();
4622 // MRR.
4623 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4624 LifeTime = Qualifiers::OCL_ExplicitNone;
4625 else
4626 LifeTime = Qualifiers::OCL_None;
4627 return true;
4628}
4629
Douglas Gregore97179c2011-09-08 01:46:34 +00004630TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4631 if (!ObjCInstanceTypeDecl)
4632 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4633 getTranslationUnitDecl(),
4634 SourceLocation(),
4635 SourceLocation(),
4636 &Idents.get("instancetype"),
4637 getTrivialTypeSourceInfo(getObjCIdType()));
4638 return ObjCInstanceTypeDecl;
4639}
4640
Anders Carlssone8c49532007-10-29 06:33:42 +00004641// This returns true if a type has been typedefed to BOOL:
4642// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00004643static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00004644 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00004645 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4646 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00004647
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004648 return false;
4649}
4650
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004651/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004652/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00004653CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00004654 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4655 return CharUnits::Zero();
4656
Ken Dyck199c3d62010-01-11 17:06:35 +00004657 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004658
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004659 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004660 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004661 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004662 // Treat arrays as pointers, since that's how they're passed in.
4663 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004664 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004665 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004666}
4667
4668static inline
4669std::string charUnitsToString(const CharUnits &CU) {
4670 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004671}
4672
John McCall6b5a61b2011-02-07 10:33:21 +00004673/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004674/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004675std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4676 std::string S;
4677
David Chisnall5e530af2009-11-17 19:33:30 +00004678 const BlockDecl *Decl = Expr->getBlockDecl();
4679 QualType BlockTy =
4680 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4681 // Encode result type.
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004682 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004683 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4684 BlockTy->getAs<FunctionType>()->getResultType(),
4685 S, true /*Extended*/);
4686 else
4687 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4688 S);
David Chisnall5e530af2009-11-17 19:33:30 +00004689 // Compute size of all parameters.
4690 // Start with computing size of a pointer in number of bytes.
4691 // FIXME: There might(should) be a better way of doing this computation!
4692 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004693 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4694 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004695 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004696 E = Decl->param_end(); PI != E; ++PI) {
4697 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004698 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahanian075a5432012-06-30 00:48:59 +00004699 if (sz.isZero())
4700 continue;
Ken Dyck199c3d62010-01-11 17:06:35 +00004701 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004702 ParmOffset += sz;
4703 }
4704 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004705 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004706 // Block pointer and offset.
4707 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004708
4709 // Argument types.
4710 ParmOffset = PtrSize;
4711 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4712 Decl->param_end(); PI != E; ++PI) {
4713 ParmVarDecl *PVDecl = *PI;
4714 QualType PType = PVDecl->getOriginalType();
4715 if (const ArrayType *AT =
4716 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4717 // Use array's original type only if it has known number of
4718 // elements.
4719 if (!isa<ConstantArrayType>(AT))
4720 PType = PVDecl->getType();
4721 } else if (PType->isFunctionType())
4722 PType = PVDecl->getType();
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004723 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004724 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4725 S, true /*Extended*/);
4726 else
4727 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004728 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004729 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004730 }
John McCall6b5a61b2011-02-07 10:33:21 +00004731
4732 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004733}
4734
Douglas Gregorf968d832011-05-27 01:19:52 +00004735bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004736 std::string& S) {
4737 // Encode result type.
4738 getObjCEncodingForType(Decl->getResultType(), S);
4739 CharUnits ParmOffset;
4740 // Compute size of all parameters.
4741 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4742 E = Decl->param_end(); PI != E; ++PI) {
4743 QualType PType = (*PI)->getType();
4744 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004745 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004746 continue;
4747
David Chisnall5389f482010-12-30 14:05:53 +00004748 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004749 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004750 ParmOffset += sz;
4751 }
4752 S += charUnitsToString(ParmOffset);
4753 ParmOffset = CharUnits::Zero();
4754
4755 // Argument types.
4756 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4757 E = Decl->param_end(); PI != E; ++PI) {
4758 ParmVarDecl *PVDecl = *PI;
4759 QualType PType = PVDecl->getOriginalType();
4760 if (const ArrayType *AT =
4761 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4762 // Use array's original type only if it has known number of
4763 // elements.
4764 if (!isa<ConstantArrayType>(AT))
4765 PType = PVDecl->getType();
4766 } else if (PType->isFunctionType())
4767 PType = PVDecl->getType();
4768 getObjCEncodingForType(PType, S);
4769 S += charUnitsToString(ParmOffset);
4770 ParmOffset += getObjCEncodingTypeSize(PType);
4771 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004772
4773 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004774}
4775
Bob Wilsondc8dab62011-11-30 01:57:58 +00004776/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4777/// method parameter or return type. If Extended, include class names and
4778/// block object types.
4779void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4780 QualType T, std::string& S,
4781 bool Extended) const {
4782 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4783 getObjCEncodingForTypeQualifier(QT, S);
4784 // Encode parameter type.
4785 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4786 true /*OutermostType*/,
4787 false /*EncodingProperty*/,
4788 false /*StructField*/,
4789 Extended /*EncodeBlockParameters*/,
4790 Extended /*EncodeClassNames*/);
4791}
4792
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004793/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004794/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004795bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004796 std::string& S,
4797 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004798 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004799 // Encode return type.
4800 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4801 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004802 // Compute size of all parameters.
4803 // Start with computing size of a pointer in number of bytes.
4804 // FIXME: There might(should) be a better way of doing this computation!
4805 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004806 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004807 // The first two arguments (self and _cmd) are pointers; account for
4808 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004809 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004810 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004811 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004812 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004813 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004814 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004815 continue;
4816
Ken Dyck199c3d62010-01-11 17:06:35 +00004817 assert (sz.isPositive() &&
4818 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004819 ParmOffset += sz;
4820 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004821 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004822 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004823 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004824
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004825 // Argument types.
4826 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004827 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004828 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004829 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004830 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004831 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004832 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4833 // Use array's original type only if it has known number of
4834 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004835 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004836 PType = PVDecl->getType();
4837 } else if (PType->isFunctionType())
4838 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004839 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4840 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004841 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004842 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004843 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004844
4845 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004846}
4847
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004848/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004849/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004850/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4851/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004852/// Property attributes are stored as a comma-delimited C string. The simple
4853/// attributes readonly and bycopy are encoded as single characters. The
4854/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4855/// encoded as single characters, followed by an identifier. Property types
4856/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004857/// these attributes are defined by the following enumeration:
4858/// @code
4859/// enum PropertyAttributes {
4860/// kPropertyReadOnly = 'R', // property is read-only.
4861/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4862/// kPropertyByref = '&', // property is a reference to the value last assigned
4863/// kPropertyDynamic = 'D', // property is dynamic
4864/// kPropertyGetter = 'G', // followed by getter selector name
4865/// kPropertySetter = 'S', // followed by setter selector name
4866/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson0d4cb852012-03-22 17:48:02 +00004867/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004868/// kPropertyWeak = 'W' // 'weak' property
4869/// kPropertyStrong = 'P' // property GC'able
4870/// kPropertyNonAtomic = 'N' // property non-atomic
4871/// };
4872/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004873void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004874 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004875 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004876 // Collect information from the property implementation decl(s).
4877 bool Dynamic = false;
4878 ObjCPropertyImplDecl *SynthesizePID = 0;
4879
4880 // FIXME: Duplicated code due to poor abstraction.
4881 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004882 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004883 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4884 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004885 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004886 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004887 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004888 if (PID->getPropertyDecl() == PD) {
4889 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4890 Dynamic = true;
4891 } else {
4892 SynthesizePID = PID;
4893 }
4894 }
4895 }
4896 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004897 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004898 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004899 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004900 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004901 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004902 if (PID->getPropertyDecl() == PD) {
4903 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4904 Dynamic = true;
4905 } else {
4906 SynthesizePID = PID;
4907 }
4908 }
Mike Stump1eb44332009-09-09 15:08:12 +00004909 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004910 }
4911 }
4912
4913 // FIXME: This is not very efficient.
4914 S = "T";
4915
4916 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004917 // GCC has some special rules regarding encoding of properties which
4918 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004919 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004920 true /* outermost type */,
4921 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004922
4923 if (PD->isReadOnly()) {
4924 S += ",R";
Nico Weberd7ceab32013-05-08 23:47:40 +00004925 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
4926 S += ",C";
4927 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
4928 S += ",&";
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004929 } else {
4930 switch (PD->getSetterKind()) {
4931 case ObjCPropertyDecl::Assign: break;
4932 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004933 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004934 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004935 }
4936 }
4937
4938 // It really isn't clear at all what this means, since properties
4939 // are "dynamic by default".
4940 if (Dynamic)
4941 S += ",D";
4942
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004943 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4944 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004945
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004946 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4947 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004948 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004949 }
4950
4951 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4952 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004953 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004954 }
4955
4956 if (SynthesizePID) {
4957 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4958 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004959 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004960 }
4961
4962 // FIXME: OBJCGC: weak & strong
4963}
4964
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004965/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004966/// Another legacy compatibility encoding: 32-bit longs are encoded as
4967/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004968/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4969///
4970void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004971 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004972 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004973 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004974 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004975 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004976 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004977 PointeeTy = IntTy;
4978 }
4979 }
4980}
4981
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004982void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00004983 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004984 // We follow the behavior of gcc, expanding structures which are
4985 // directly pointed to, and expanding embedded structures. Note that
4986 // these rules are sufficient to prevent recursive encoding of the
4987 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00004988 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00004989 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004990}
4991
John McCall3624e9e2012-12-20 02:45:14 +00004992static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
4993 BuiltinType::Kind kind) {
4994 switch (kind) {
David Chisnall64fd7e82010-06-04 01:10:52 +00004995 case BuiltinType::Void: return 'v';
4996 case BuiltinType::Bool: return 'B';
4997 case BuiltinType::Char_U:
4998 case BuiltinType::UChar: return 'C';
John McCall3624e9e2012-12-20 02:45:14 +00004999 case BuiltinType::Char16:
David Chisnall64fd7e82010-06-04 01:10:52 +00005000 case BuiltinType::UShort: return 'S';
John McCall3624e9e2012-12-20 02:45:14 +00005001 case BuiltinType::Char32:
David Chisnall64fd7e82010-06-04 01:10:52 +00005002 case BuiltinType::UInt: return 'I';
5003 case BuiltinType::ULong:
John McCall3624e9e2012-12-20 02:45:14 +00005004 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00005005 case BuiltinType::UInt128: return 'T';
5006 case BuiltinType::ULongLong: return 'Q';
5007 case BuiltinType::Char_S:
5008 case BuiltinType::SChar: return 'c';
5009 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00005010 case BuiltinType::WChar_S:
5011 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00005012 case BuiltinType::Int: return 'i';
5013 case BuiltinType::Long:
John McCall3624e9e2012-12-20 02:45:14 +00005014 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00005015 case BuiltinType::LongLong: return 'q';
5016 case BuiltinType::Int128: return 't';
5017 case BuiltinType::Float: return 'f';
5018 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00005019 case BuiltinType::LongDouble: return 'D';
John McCall3624e9e2012-12-20 02:45:14 +00005020 case BuiltinType::NullPtr: return '*'; // like char*
5021
5022 case BuiltinType::Half:
5023 // FIXME: potentially need @encodes for these!
5024 return ' ';
5025
5026 case BuiltinType::ObjCId:
5027 case BuiltinType::ObjCClass:
5028 case BuiltinType::ObjCSel:
5029 llvm_unreachable("@encoding ObjC primitive type");
5030
5031 // OpenCL and placeholder types don't need @encodings.
5032 case BuiltinType::OCLImage1d:
5033 case BuiltinType::OCLImage1dArray:
5034 case BuiltinType::OCLImage1dBuffer:
5035 case BuiltinType::OCLImage2d:
5036 case BuiltinType::OCLImage2dArray:
5037 case BuiltinType::OCLImage3d:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005038 case BuiltinType::OCLEvent:
Guy Benyei21f18c42013-02-07 10:55:47 +00005039 case BuiltinType::OCLSampler:
John McCall3624e9e2012-12-20 02:45:14 +00005040 case BuiltinType::Dependent:
5041#define BUILTIN_TYPE(KIND, ID)
5042#define PLACEHOLDER_TYPE(KIND, ID) \
5043 case BuiltinType::KIND:
5044#include "clang/AST/BuiltinTypes.def"
5045 llvm_unreachable("invalid builtin type for @encode");
David Chisnall64fd7e82010-06-04 01:10:52 +00005046 }
David Blaikie719e53f2013-01-09 17:48:41 +00005047 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnall64fd7e82010-06-04 01:10:52 +00005048}
5049
Douglas Gregor5471bc82011-09-08 17:18:35 +00005050static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5051 EnumDecl *Enum = ET->getDecl();
5052
5053 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5054 if (!Enum->isFixed())
5055 return 'i';
5056
5057 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall3624e9e2012-12-20 02:45:14 +00005058 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5059 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor5471bc82011-09-08 17:18:35 +00005060}
5061
Jay Foad4ba2a172011-01-12 09:06:06 +00005062static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00005063 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005064 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00005065 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00005066 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5067 // The GNU runtime requires more information; bitfields are encoded as b,
5068 // then the offset (in bits) of the first element, then the type of the
5069 // bitfield, then the size in bits. For example, in this structure:
5070 //
5071 // struct
5072 // {
5073 // int integer;
5074 // int flags:2;
5075 // };
5076 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5077 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5078 // information is not especially sensible, but we're stuck with it for
5079 // compatibility with GCC, although providing it breaks anything that
5080 // actually uses runtime introspection and wants to work on both runtimes...
John McCall260611a2012-06-20 06:18:46 +00005081 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnall64fd7e82010-06-04 01:10:52 +00005082 const RecordDecl *RD = FD->getParent();
5083 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00005084 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00005085 if (const EnumType *ET = T->getAs<EnumType>())
5086 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall3624e9e2012-12-20 02:45:14 +00005087 else {
5088 const BuiltinType *BT = T->castAs<BuiltinType>();
5089 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5090 }
David Chisnall64fd7e82010-06-04 01:10:52 +00005091 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005092 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00005093}
5094
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00005095// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005096void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5097 bool ExpandPointedToStructures,
5098 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00005099 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00005100 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005101 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00005102 bool StructField,
5103 bool EncodeBlockParameters,
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005104 bool EncodeClassNames,
5105 bool EncodePointerToObjCTypedef) const {
John McCall3624e9e2012-12-20 02:45:14 +00005106 CanQualType CT = getCanonicalType(T);
5107 switch (CT->getTypeClass()) {
5108 case Type::Builtin:
5109 case Type::Enum:
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005110 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00005111 return EncodeBitField(this, S, T, FD);
John McCall3624e9e2012-12-20 02:45:14 +00005112 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5113 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5114 else
5115 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005116 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005117
John McCall3624e9e2012-12-20 02:45:14 +00005118 case Type::Complex: {
5119 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005120 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00005121 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005122 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005123 return;
5124 }
John McCall3624e9e2012-12-20 02:45:14 +00005125
5126 case Type::Atomic: {
5127 const AtomicType *AT = T->castAs<AtomicType>();
5128 S += 'A';
5129 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5130 false, false);
5131 return;
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00005132 }
John McCall3624e9e2012-12-20 02:45:14 +00005133
5134 // encoding for pointer or reference types.
5135 case Type::Pointer:
5136 case Type::LValueReference:
5137 case Type::RValueReference: {
5138 QualType PointeeTy;
5139 if (isa<PointerType>(CT)) {
5140 const PointerType *PT = T->castAs<PointerType>();
5141 if (PT->isObjCSelType()) {
5142 S += ':';
5143 return;
5144 }
5145 PointeeTy = PT->getPointeeType();
5146 } else {
5147 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5148 }
5149
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005150 bool isReadOnly = false;
5151 // For historical/compatibility reasons, the read-only qualifier of the
5152 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5153 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00005154 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00005155 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005156 if (OutermostType && T.isConstQualified()) {
5157 isReadOnly = true;
5158 S += 'r';
5159 }
Mike Stump9fdbab32009-07-31 02:02:20 +00005160 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005161 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00005162 while (P->getAs<PointerType>())
5163 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005164 if (P.isConstQualified()) {
5165 isReadOnly = true;
5166 S += 'r';
5167 }
5168 }
5169 if (isReadOnly) {
5170 // Another legacy compatibility encoding. Some ObjC qualifier and type
5171 // combinations need to be rearranged.
5172 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00005173 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00005174 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005175 }
Mike Stump1eb44332009-09-09 15:08:12 +00005176
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005177 if (PointeeTy->isCharType()) {
5178 // char pointer types should be encoded as '*' unless it is a
5179 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00005180 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005181 S += '*';
5182 return;
5183 }
Ted Kremenek6217b802009-07-29 21:53:49 +00005184 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00005185 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5186 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5187 S += '#';
5188 return;
5189 }
5190 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5191 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5192 S += '@';
5193 return;
5194 }
5195 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005196 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005197 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005198 getLegacyIntegralTypeEncoding(PointeeTy);
5199
Mike Stump1eb44332009-09-09 15:08:12 +00005200 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005201 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005202 return;
5203 }
John McCall3624e9e2012-12-20 02:45:14 +00005204
5205 case Type::ConstantArray:
5206 case Type::IncompleteArray:
5207 case Type::VariableArray: {
5208 const ArrayType *AT = cast<ArrayType>(CT);
5209
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005210 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00005211 // Incomplete arrays are encoded as a pointer to the array element.
5212 S += '^';
5213
Mike Stump1eb44332009-09-09 15:08:12 +00005214 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005215 false, ExpandStructures, FD);
5216 } else {
5217 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00005218
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005219 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
5220 if (getTypeSize(CAT->getElementType()) == 0)
5221 S += '0';
5222 else
5223 S += llvm::utostr(CAT->getSize().getZExtValue());
5224 } else {
Anders Carlsson559a8332009-02-22 01:38:57 +00005225 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005226 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5227 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00005228 S += '0';
5229 }
Mike Stump1eb44332009-09-09 15:08:12 +00005230
5231 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005232 false, ExpandStructures, FD);
5233 S += ']';
5234 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005235 return;
5236 }
Mike Stump1eb44332009-09-09 15:08:12 +00005237
John McCall3624e9e2012-12-20 02:45:14 +00005238 case Type::FunctionNoProto:
5239 case Type::FunctionProto:
Anders Carlssonc0a87b72007-10-30 00:06:20 +00005240 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005241 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005242
John McCall3624e9e2012-12-20 02:45:14 +00005243 case Type::Record: {
5244 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005245 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005246 // Anonymous structures print as '?'
5247 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5248 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005249 if (ClassTemplateSpecializationDecl *Spec
5250 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5251 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer5eada842013-02-22 15:46:01 +00005252 llvm::raw_string_ostream OS(S);
5253 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor910f8002010-11-07 23:05:16 +00005254 TemplateArgs.data(),
5255 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00005256 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005257 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005258 } else {
5259 S += '?';
5260 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00005261 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005262 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005263 if (!RDecl->isUnion()) {
5264 getObjCEncodingForStructureImpl(RDecl, S, FD);
5265 } else {
5266 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5267 FieldEnd = RDecl->field_end();
5268 Field != FieldEnd; ++Field) {
5269 if (FD) {
5270 S += '"';
5271 S += Field->getNameAsString();
5272 S += '"';
5273 }
Mike Stump1eb44332009-09-09 15:08:12 +00005274
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005275 // Special case bit-fields.
5276 if (Field->isBitField()) {
5277 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie581deb32012-06-06 20:45:41 +00005278 *Field);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005279 } else {
5280 QualType qt = Field->getType();
5281 getLegacyIntegralTypeEncoding(qt);
5282 getObjCEncodingForTypeImpl(qt, S, false, true,
5283 FD, /*OutermostType*/false,
5284 /*EncodingProperty*/false,
5285 /*StructField*/true);
5286 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005287 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005288 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00005289 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005290 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005291 return;
5292 }
Mike Stump1eb44332009-09-09 15:08:12 +00005293
John McCall3624e9e2012-12-20 02:45:14 +00005294 case Type::BlockPointer: {
5295 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff21a98b12009-02-02 18:24:29 +00005296 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00005297 if (EncodeBlockParameters) {
John McCall3624e9e2012-12-20 02:45:14 +00005298 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilsondc8dab62011-11-30 01:57:58 +00005299
5300 S += '<';
5301 // Block return type
5302 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5303 ExpandPointedToStructures, ExpandStructures,
5304 FD,
5305 false /* OutermostType */,
5306 EncodingProperty,
5307 false /* StructField */,
5308 EncodeBlockParameters,
5309 EncodeClassNames);
5310 // Block self
5311 S += "@?";
5312 // Block parameters
5313 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5314 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5315 E = FPT->arg_type_end(); I && (I != E); ++I) {
5316 getObjCEncodingForTypeImpl(*I, S,
5317 ExpandPointedToStructures,
5318 ExpandStructures,
5319 FD,
5320 false /* OutermostType */,
5321 EncodingProperty,
5322 false /* StructField */,
5323 EncodeBlockParameters,
5324 EncodeClassNames);
5325 }
5326 }
5327 S += '>';
5328 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005329 return;
5330 }
Mike Stump1eb44332009-09-09 15:08:12 +00005331
John McCall3624e9e2012-12-20 02:45:14 +00005332 case Type::ObjCObject:
5333 case Type::ObjCInterface: {
5334 // Ignore protocol qualifiers when mangling at this level.
5335 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCallc12c5bb2010-05-15 11:32:37 +00005336
John McCall3624e9e2012-12-20 02:45:14 +00005337 // The assumption seems to be that this assert will succeed
5338 // because nested levels will have filtered out 'id' and 'Class'.
5339 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005340 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00005341 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005342 S += '{';
5343 const IdentifierInfo *II = OI->getIdentifier();
5344 S += II->getName();
5345 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00005346 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005347 DeepCollectObjCIvars(OI, true, Ivars);
5348 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00005349 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005350 if (Field->isBitField())
5351 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005352 else
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005353 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5354 false, false, false, false, false,
5355 EncodePointerToObjCTypedef);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005356 }
5357 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005358 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005359 }
Mike Stump1eb44332009-09-09 15:08:12 +00005360
John McCall3624e9e2012-12-20 02:45:14 +00005361 case Type::ObjCObjectPointer: {
5362 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00005363 if (OPT->isObjCIdType()) {
5364 S += '@';
5365 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005366 }
Mike Stump1eb44332009-09-09 15:08:12 +00005367
Steve Naroff27d20a22009-10-28 22:03:49 +00005368 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5369 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5370 // Since this is a binary compatibility issue, need to consult with runtime
5371 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00005372 S += '#';
5373 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005374 }
Mike Stump1eb44332009-09-09 15:08:12 +00005375
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005376 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005377 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00005378 ExpandPointedToStructures,
5379 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00005380 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00005381 // Note that we do extended encoding of protocol qualifer list
5382 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00005383 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005384 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5385 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00005386 S += '<';
5387 S += (*I)->getNameAsString();
5388 S += '>';
5389 }
5390 S += '"';
5391 }
5392 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005393 }
Mike Stump1eb44332009-09-09 15:08:12 +00005394
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005395 QualType PointeeTy = OPT->getPointeeType();
5396 if (!EncodingProperty &&
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005397 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5398 !EncodePointerToObjCTypedef) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005399 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00005400 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005401 // {...};
5402 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00005403 getObjCEncodingForTypeImpl(PointeeTy, S,
5404 false, ExpandPointedToStructures,
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005405 NULL,
5406 false, false, false, false, false,
5407 /*EncodePointerToObjCTypedef*/true);
Steve Naroff14108da2009-07-10 23:34:53 +00005408 return;
5409 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005410
5411 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00005412 if (OPT->getInterfaceDecl() &&
5413 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005414 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00005415 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005416 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5417 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005418 S += '<';
5419 S += (*I)->getNameAsString();
5420 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00005421 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005422 S += '"';
5423 }
5424 return;
5425 }
Mike Stump1eb44332009-09-09 15:08:12 +00005426
John McCall532ec7b2010-05-17 23:56:34 +00005427 // gcc just blithely ignores member pointers.
John McCall3624e9e2012-12-20 02:45:14 +00005428 // FIXME: we shoul do better than that. 'M' is available.
5429 case Type::MemberPointer:
John McCall532ec7b2010-05-17 23:56:34 +00005430 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005431
John McCall3624e9e2012-12-20 02:45:14 +00005432 case Type::Vector:
5433 case Type::ExtVector:
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005434 // This matches gcc's encoding, even though technically it is
5435 // insufficient.
5436 // FIXME. We should do a better job than gcc.
5437 return;
John McCall3624e9e2012-12-20 02:45:14 +00005438
Richard Smithdc7a4f52013-04-30 13:56:41 +00005439 case Type::Auto:
5440 // We could see an undeduced auto type here during error recovery.
5441 // Just ignore it.
5442 return;
5443
John McCall3624e9e2012-12-20 02:45:14 +00005444#define ABSTRACT_TYPE(KIND, BASE)
5445#define TYPE(KIND, BASE)
5446#define DEPENDENT_TYPE(KIND, BASE) \
5447 case Type::KIND:
5448#define NON_CANONICAL_TYPE(KIND, BASE) \
5449 case Type::KIND:
5450#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5451 case Type::KIND:
5452#include "clang/AST/TypeNodes.def"
5453 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005454 }
John McCall3624e9e2012-12-20 02:45:14 +00005455 llvm_unreachable("bad type kind!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005456}
5457
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005458void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5459 std::string &S,
5460 const FieldDecl *FD,
5461 bool includeVBases) const {
5462 assert(RDecl && "Expected non-null RecordDecl");
5463 assert(!RDecl->isUnion() && "Should not be called for unions");
5464 if (!RDecl->getDefinition())
5465 return;
5466
5467 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5468 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5469 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5470
5471 if (CXXRec) {
5472 for (CXXRecordDecl::base_class_iterator
5473 BI = CXXRec->bases_begin(),
5474 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5475 if (!BI->isVirtual()) {
5476 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005477 if (base->isEmpty())
5478 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005479 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005480 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5481 std::make_pair(offs, base));
5482 }
5483 }
5484 }
5485
5486 unsigned i = 0;
5487 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5488 FieldEnd = RDecl->field_end();
5489 Field != FieldEnd; ++Field, ++i) {
5490 uint64_t offs = layout.getFieldOffset(i);
5491 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie581deb32012-06-06 20:45:41 +00005492 std::make_pair(offs, *Field));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005493 }
5494
5495 if (CXXRec && includeVBases) {
5496 for (CXXRecordDecl::base_class_iterator
5497 BI = CXXRec->vbases_begin(),
5498 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5499 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005500 if (base->isEmpty())
5501 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005502 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00005503 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5504 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5505 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005506 }
5507 }
5508
5509 CharUnits size;
5510 if (CXXRec) {
5511 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5512 } else {
5513 size = layout.getSize();
5514 }
5515
5516 uint64_t CurOffs = 0;
5517 std::multimap<uint64_t, NamedDecl *>::iterator
5518 CurLayObj = FieldOrBaseOffsets.begin();
5519
Douglas Gregor58db7a52012-04-27 22:30:01 +00005520 if (CXXRec && CXXRec->isDynamicClass() &&
5521 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005522 if (FD) {
5523 S += "\"_vptr$";
5524 std::string recname = CXXRec->getNameAsString();
5525 if (recname.empty()) recname = "?";
5526 S += recname;
5527 S += '"';
5528 }
5529 S += "^^?";
5530 CurOffs += getTypeSize(VoidPtrTy);
5531 }
5532
5533 if (!RDecl->hasFlexibleArrayMember()) {
5534 // Mark the end of the structure.
5535 uint64_t offs = toBits(size);
5536 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5537 std::make_pair(offs, (NamedDecl*)0));
5538 }
5539
5540 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5541 assert(CurOffs <= CurLayObj->first);
5542
5543 if (CurOffs < CurLayObj->first) {
5544 uint64_t padding = CurLayObj->first - CurOffs;
5545 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5546 // packing/alignment of members is different that normal, in which case
5547 // the encoding will be out-of-sync with the real layout.
5548 // If the runtime switches to just consider the size of types without
5549 // taking into account alignment, we could make padding explicit in the
5550 // encoding (e.g. using arrays of chars). The encoding strings would be
5551 // longer then though.
5552 CurOffs += padding;
5553 }
5554
5555 NamedDecl *dcl = CurLayObj->second;
5556 if (dcl == 0)
5557 break; // reached end of structure.
5558
5559 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5560 // We expand the bases without their virtual bases since those are going
5561 // in the initial structure. Note that this differs from gcc which
5562 // expands virtual bases each time one is encountered in the hierarchy,
5563 // making the encoding type bigger than it really is.
5564 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005565 assert(!base->isEmpty());
5566 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005567 } else {
5568 FieldDecl *field = cast<FieldDecl>(dcl);
5569 if (FD) {
5570 S += '"';
5571 S += field->getNameAsString();
5572 S += '"';
5573 }
5574
5575 if (field->isBitField()) {
5576 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005577 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005578 } else {
5579 QualType qt = field->getType();
5580 getLegacyIntegralTypeEncoding(qt);
5581 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5582 /*OutermostType*/false,
5583 /*EncodingProperty*/false,
5584 /*StructField*/true);
5585 CurOffs += getTypeSize(field->getType());
5586 }
5587 }
5588 }
5589}
5590
Mike Stump1eb44332009-09-09 15:08:12 +00005591void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00005592 std::string& S) const {
5593 if (QT & Decl::OBJC_TQ_In)
5594 S += 'n';
5595 if (QT & Decl::OBJC_TQ_Inout)
5596 S += 'N';
5597 if (QT & Decl::OBJC_TQ_Out)
5598 S += 'o';
5599 if (QT & Decl::OBJC_TQ_Bycopy)
5600 S += 'O';
5601 if (QT & Decl::OBJC_TQ_Byref)
5602 S += 'R';
5603 if (QT & Decl::OBJC_TQ_Oneway)
5604 S += 'V';
5605}
5606
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00005607TypedefDecl *ASTContext::getObjCIdDecl() const {
5608 if (!ObjCIdDecl) {
5609 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5610 T = getObjCObjectPointerType(T);
5611 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5612 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5613 getTranslationUnitDecl(),
5614 SourceLocation(), SourceLocation(),
5615 &Idents.get("id"), IdInfo);
5616 }
5617
5618 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00005619}
5620
Douglas Gregor7a27ea52011-08-12 06:17:30 +00005621TypedefDecl *ASTContext::getObjCSelDecl() const {
5622 if (!ObjCSelDecl) {
5623 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5624 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5625 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5626 getTranslationUnitDecl(),
5627 SourceLocation(), SourceLocation(),
5628 &Idents.get("SEL"), SelInfo);
5629 }
5630 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00005631}
5632
Douglas Gregor79d67262011-08-12 05:59:41 +00005633TypedefDecl *ASTContext::getObjCClassDecl() const {
5634 if (!ObjCClassDecl) {
5635 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5636 T = getObjCObjectPointerType(T);
5637 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5638 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5639 getTranslationUnitDecl(),
5640 SourceLocation(), SourceLocation(),
5641 &Idents.get("Class"), ClassInfo);
5642 }
5643
5644 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00005645}
5646
Douglas Gregora6ea10e2012-01-17 18:09:05 +00005647ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5648 if (!ObjCProtocolClassDecl) {
5649 ObjCProtocolClassDecl
5650 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5651 SourceLocation(),
5652 &Idents.get("Protocol"),
5653 /*PrevDecl=*/0,
5654 SourceLocation(), true);
5655 }
5656
5657 return ObjCProtocolClassDecl;
5658}
5659
Meador Ingec5613b22012-06-16 03:34:49 +00005660//===----------------------------------------------------------------------===//
5661// __builtin_va_list Construction Functions
5662//===----------------------------------------------------------------------===//
5663
5664static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5665 // typedef char* __builtin_va_list;
5666 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5667 TypeSourceInfo *TInfo
5668 = Context->getTrivialTypeSourceInfo(CharPtrType);
5669
5670 TypedefDecl *VaListTypeDecl
5671 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5672 Context->getTranslationUnitDecl(),
5673 SourceLocation(), SourceLocation(),
5674 &Context->Idents.get("__builtin_va_list"),
5675 TInfo);
5676 return VaListTypeDecl;
5677}
5678
5679static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5680 // typedef void* __builtin_va_list;
5681 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5682 TypeSourceInfo *TInfo
5683 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5684
5685 TypedefDecl *VaListTypeDecl
5686 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5687 Context->getTranslationUnitDecl(),
5688 SourceLocation(), SourceLocation(),
5689 &Context->Idents.get("__builtin_va_list"),
5690 TInfo);
5691 return VaListTypeDecl;
5692}
5693
Tim Northoverc264e162013-01-31 12:13:10 +00005694static TypedefDecl *
5695CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5696 RecordDecl *VaListTagDecl;
5697 if (Context->getLangOpts().CPlusPlus) {
5698 // namespace std { struct __va_list {
5699 NamespaceDecl *NS;
5700 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5701 Context->getTranslationUnitDecl(),
5702 /*Inline*/false, SourceLocation(),
5703 SourceLocation(), &Context->Idents.get("std"),
5704 /*PrevDecl*/0);
5705
5706 VaListTagDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5707 Context->getTranslationUnitDecl(),
5708 SourceLocation(), SourceLocation(),
5709 &Context->Idents.get("__va_list"));
5710 VaListTagDecl->setDeclContext(NS);
5711 } else {
5712 // struct __va_list
5713 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5714 Context->getTranslationUnitDecl(),
5715 &Context->Idents.get("__va_list"));
5716 }
5717
5718 VaListTagDecl->startDefinition();
5719
5720 const size_t NumFields = 5;
5721 QualType FieldTypes[NumFields];
5722 const char *FieldNames[NumFields];
5723
5724 // void *__stack;
5725 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5726 FieldNames[0] = "__stack";
5727
5728 // void *__gr_top;
5729 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5730 FieldNames[1] = "__gr_top";
5731
5732 // void *__vr_top;
5733 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5734 FieldNames[2] = "__vr_top";
5735
5736 // int __gr_offs;
5737 FieldTypes[3] = Context->IntTy;
5738 FieldNames[3] = "__gr_offs";
5739
5740 // int __vr_offs;
5741 FieldTypes[4] = Context->IntTy;
5742 FieldNames[4] = "__vr_offs";
5743
5744 // Create fields
5745 for (unsigned i = 0; i < NumFields; ++i) {
5746 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5747 VaListTagDecl,
5748 SourceLocation(),
5749 SourceLocation(),
5750 &Context->Idents.get(FieldNames[i]),
5751 FieldTypes[i], /*TInfo=*/0,
5752 /*BitWidth=*/0,
5753 /*Mutable=*/false,
5754 ICIS_NoInit);
5755 Field->setAccess(AS_public);
5756 VaListTagDecl->addDecl(Field);
5757 }
5758 VaListTagDecl->completeDefinition();
5759 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5760 Context->VaListTagTy = VaListTagType;
5761
5762 // } __builtin_va_list;
5763 TypedefDecl *VaListTypedefDecl
5764 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5765 Context->getTranslationUnitDecl(),
5766 SourceLocation(), SourceLocation(),
5767 &Context->Idents.get("__builtin_va_list"),
5768 Context->getTrivialTypeSourceInfo(VaListTagType));
5769
5770 return VaListTypedefDecl;
5771}
5772
Meador Ingec5613b22012-06-16 03:34:49 +00005773static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5774 // typedef struct __va_list_tag {
5775 RecordDecl *VaListTagDecl;
5776
5777 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5778 Context->getTranslationUnitDecl(),
5779 &Context->Idents.get("__va_list_tag"));
5780 VaListTagDecl->startDefinition();
5781
5782 const size_t NumFields = 5;
5783 QualType FieldTypes[NumFields];
5784 const char *FieldNames[NumFields];
5785
5786 // unsigned char gpr;
5787 FieldTypes[0] = Context->UnsignedCharTy;
5788 FieldNames[0] = "gpr";
5789
5790 // unsigned char fpr;
5791 FieldTypes[1] = Context->UnsignedCharTy;
5792 FieldNames[1] = "fpr";
5793
5794 // unsigned short reserved;
5795 FieldTypes[2] = Context->UnsignedShortTy;
5796 FieldNames[2] = "reserved";
5797
5798 // void* overflow_arg_area;
5799 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5800 FieldNames[3] = "overflow_arg_area";
5801
5802 // void* reg_save_area;
5803 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5804 FieldNames[4] = "reg_save_area";
5805
5806 // Create fields
5807 for (unsigned i = 0; i < NumFields; ++i) {
5808 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5809 SourceLocation(),
5810 SourceLocation(),
5811 &Context->Idents.get(FieldNames[i]),
5812 FieldTypes[i], /*TInfo=*/0,
5813 /*BitWidth=*/0,
5814 /*Mutable=*/false,
5815 ICIS_NoInit);
5816 Field->setAccess(AS_public);
5817 VaListTagDecl->addDecl(Field);
5818 }
5819 VaListTagDecl->completeDefinition();
5820 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005821 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005822
5823 // } __va_list_tag;
5824 TypedefDecl *VaListTagTypedefDecl
5825 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5826 Context->getTranslationUnitDecl(),
5827 SourceLocation(), SourceLocation(),
5828 &Context->Idents.get("__va_list_tag"),
5829 Context->getTrivialTypeSourceInfo(VaListTagType));
5830 QualType VaListTagTypedefType =
5831 Context->getTypedefType(VaListTagTypedefDecl);
5832
5833 // typedef __va_list_tag __builtin_va_list[1];
5834 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5835 QualType VaListTagArrayType
5836 = Context->getConstantArrayType(VaListTagTypedefType,
5837 Size, ArrayType::Normal, 0);
5838 TypeSourceInfo *TInfo
5839 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5840 TypedefDecl *VaListTypedefDecl
5841 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5842 Context->getTranslationUnitDecl(),
5843 SourceLocation(), SourceLocation(),
5844 &Context->Idents.get("__builtin_va_list"),
5845 TInfo);
5846
5847 return VaListTypedefDecl;
5848}
5849
5850static TypedefDecl *
5851CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5852 // typedef struct __va_list_tag {
5853 RecordDecl *VaListTagDecl;
5854 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5855 Context->getTranslationUnitDecl(),
5856 &Context->Idents.get("__va_list_tag"));
5857 VaListTagDecl->startDefinition();
5858
5859 const size_t NumFields = 4;
5860 QualType FieldTypes[NumFields];
5861 const char *FieldNames[NumFields];
5862
5863 // unsigned gp_offset;
5864 FieldTypes[0] = Context->UnsignedIntTy;
5865 FieldNames[0] = "gp_offset";
5866
5867 // unsigned fp_offset;
5868 FieldTypes[1] = Context->UnsignedIntTy;
5869 FieldNames[1] = "fp_offset";
5870
5871 // void* overflow_arg_area;
5872 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5873 FieldNames[2] = "overflow_arg_area";
5874
5875 // void* reg_save_area;
5876 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5877 FieldNames[3] = "reg_save_area";
5878
5879 // Create fields
5880 for (unsigned i = 0; i < NumFields; ++i) {
5881 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5882 VaListTagDecl,
5883 SourceLocation(),
5884 SourceLocation(),
5885 &Context->Idents.get(FieldNames[i]),
5886 FieldTypes[i], /*TInfo=*/0,
5887 /*BitWidth=*/0,
5888 /*Mutable=*/false,
5889 ICIS_NoInit);
5890 Field->setAccess(AS_public);
5891 VaListTagDecl->addDecl(Field);
5892 }
5893 VaListTagDecl->completeDefinition();
5894 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005895 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005896
5897 // } __va_list_tag;
5898 TypedefDecl *VaListTagTypedefDecl
5899 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5900 Context->getTranslationUnitDecl(),
5901 SourceLocation(), SourceLocation(),
5902 &Context->Idents.get("__va_list_tag"),
5903 Context->getTrivialTypeSourceInfo(VaListTagType));
5904 QualType VaListTagTypedefType =
5905 Context->getTypedefType(VaListTagTypedefDecl);
5906
5907 // typedef __va_list_tag __builtin_va_list[1];
5908 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5909 QualType VaListTagArrayType
5910 = Context->getConstantArrayType(VaListTagTypedefType,
5911 Size, ArrayType::Normal,0);
5912 TypeSourceInfo *TInfo
5913 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5914 TypedefDecl *VaListTypedefDecl
5915 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5916 Context->getTranslationUnitDecl(),
5917 SourceLocation(), SourceLocation(),
5918 &Context->Idents.get("__builtin_va_list"),
5919 TInfo);
5920
5921 return VaListTypedefDecl;
5922}
5923
5924static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5925 // typedef int __builtin_va_list[4];
5926 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5927 QualType IntArrayType
5928 = Context->getConstantArrayType(Context->IntTy,
5929 Size, ArrayType::Normal, 0);
5930 TypedefDecl *VaListTypedefDecl
5931 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5932 Context->getTranslationUnitDecl(),
5933 SourceLocation(), SourceLocation(),
5934 &Context->Idents.get("__builtin_va_list"),
5935 Context->getTrivialTypeSourceInfo(IntArrayType));
5936
5937 return VaListTypedefDecl;
5938}
5939
Logan Chieneae5a8202012-10-10 06:56:20 +00005940static TypedefDecl *
5941CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5942 RecordDecl *VaListDecl;
5943 if (Context->getLangOpts().CPlusPlus) {
5944 // namespace std { struct __va_list {
5945 NamespaceDecl *NS;
5946 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5947 Context->getTranslationUnitDecl(),
5948 /*Inline*/false, SourceLocation(),
5949 SourceLocation(), &Context->Idents.get("std"),
5950 /*PrevDecl*/0);
5951
5952 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5953 Context->getTranslationUnitDecl(),
5954 SourceLocation(), SourceLocation(),
5955 &Context->Idents.get("__va_list"));
5956
5957 VaListDecl->setDeclContext(NS);
5958
5959 } else {
5960 // struct __va_list {
5961 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
5962 Context->getTranslationUnitDecl(),
5963 &Context->Idents.get("__va_list"));
5964 }
5965
5966 VaListDecl->startDefinition();
5967
5968 // void * __ap;
5969 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5970 VaListDecl,
5971 SourceLocation(),
5972 SourceLocation(),
5973 &Context->Idents.get("__ap"),
5974 Context->getPointerType(Context->VoidTy),
5975 /*TInfo=*/0,
5976 /*BitWidth=*/0,
5977 /*Mutable=*/false,
5978 ICIS_NoInit);
5979 Field->setAccess(AS_public);
5980 VaListDecl->addDecl(Field);
5981
5982 // };
5983 VaListDecl->completeDefinition();
5984
5985 // typedef struct __va_list __builtin_va_list;
5986 TypeSourceInfo *TInfo
5987 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
5988
5989 TypedefDecl *VaListTypeDecl
5990 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5991 Context->getTranslationUnitDecl(),
5992 SourceLocation(), SourceLocation(),
5993 &Context->Idents.get("__builtin_va_list"),
5994 TInfo);
5995
5996 return VaListTypeDecl;
5997}
5998
Ulrich Weigandb8409212013-05-06 16:26:41 +00005999static TypedefDecl *
6000CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6001 // typedef struct __va_list_tag {
6002 RecordDecl *VaListTagDecl;
6003 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
6004 Context->getTranslationUnitDecl(),
6005 &Context->Idents.get("__va_list_tag"));
6006 VaListTagDecl->startDefinition();
6007
6008 const size_t NumFields = 4;
6009 QualType FieldTypes[NumFields];
6010 const char *FieldNames[NumFields];
6011
6012 // long __gpr;
6013 FieldTypes[0] = Context->LongTy;
6014 FieldNames[0] = "__gpr";
6015
6016 // long __fpr;
6017 FieldTypes[1] = Context->LongTy;
6018 FieldNames[1] = "__fpr";
6019
6020 // void *__overflow_arg_area;
6021 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6022 FieldNames[2] = "__overflow_arg_area";
6023
6024 // void *__reg_save_area;
6025 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6026 FieldNames[3] = "__reg_save_area";
6027
6028 // Create fields
6029 for (unsigned i = 0; i < NumFields; ++i) {
6030 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6031 VaListTagDecl,
6032 SourceLocation(),
6033 SourceLocation(),
6034 &Context->Idents.get(FieldNames[i]),
6035 FieldTypes[i], /*TInfo=*/0,
6036 /*BitWidth=*/0,
6037 /*Mutable=*/false,
6038 ICIS_NoInit);
6039 Field->setAccess(AS_public);
6040 VaListTagDecl->addDecl(Field);
6041 }
6042 VaListTagDecl->completeDefinition();
6043 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6044 Context->VaListTagTy = VaListTagType;
6045
6046 // } __va_list_tag;
6047 TypedefDecl *VaListTagTypedefDecl
6048 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6049 Context->getTranslationUnitDecl(),
6050 SourceLocation(), SourceLocation(),
6051 &Context->Idents.get("__va_list_tag"),
6052 Context->getTrivialTypeSourceInfo(VaListTagType));
6053 QualType VaListTagTypedefType =
6054 Context->getTypedefType(VaListTagTypedefDecl);
6055
6056 // typedef __va_list_tag __builtin_va_list[1];
6057 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6058 QualType VaListTagArrayType
6059 = Context->getConstantArrayType(VaListTagTypedefType,
6060 Size, ArrayType::Normal,0);
6061 TypeSourceInfo *TInfo
6062 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
6063 TypedefDecl *VaListTypedefDecl
6064 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6065 Context->getTranslationUnitDecl(),
6066 SourceLocation(), SourceLocation(),
6067 &Context->Idents.get("__builtin_va_list"),
6068 TInfo);
6069
6070 return VaListTypedefDecl;
6071}
6072
Meador Ingec5613b22012-06-16 03:34:49 +00006073static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6074 TargetInfo::BuiltinVaListKind Kind) {
6075 switch (Kind) {
6076 case TargetInfo::CharPtrBuiltinVaList:
6077 return CreateCharPtrBuiltinVaListDecl(Context);
6078 case TargetInfo::VoidPtrBuiltinVaList:
6079 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northoverc264e162013-01-31 12:13:10 +00006080 case TargetInfo::AArch64ABIBuiltinVaList:
6081 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00006082 case TargetInfo::PowerABIBuiltinVaList:
6083 return CreatePowerABIBuiltinVaListDecl(Context);
6084 case TargetInfo::X86_64ABIBuiltinVaList:
6085 return CreateX86_64ABIBuiltinVaListDecl(Context);
6086 case TargetInfo::PNaClABIBuiltinVaList:
6087 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chieneae5a8202012-10-10 06:56:20 +00006088 case TargetInfo::AAPCSABIBuiltinVaList:
6089 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigandb8409212013-05-06 16:26:41 +00006090 case TargetInfo::SystemZBuiltinVaList:
6091 return CreateSystemZBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00006092 }
6093
6094 llvm_unreachable("Unhandled __builtin_va_list type kind");
6095}
6096
6097TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6098 if (!BuiltinVaListDecl)
6099 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6100
6101 return BuiltinVaListDecl;
6102}
6103
Meador Ingefb40e3f2012-07-01 15:57:25 +00006104QualType ASTContext::getVaListTagType() const {
6105 // Force the creation of VaListTagTy by building the __builtin_va_list
6106 // declaration.
6107 if (VaListTagTy.isNull())
6108 (void) getBuiltinVaListDecl();
6109
6110 return VaListTagTy;
6111}
6112
Ted Kremeneka526c5c2008-01-07 19:49:32 +00006113void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00006114 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00006115 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00006116
Ted Kremeneka526c5c2008-01-07 19:49:32 +00006117 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00006118}
6119
John McCall0bd6feb2009-12-02 08:04:21 +00006120/// \brief Retrieve the template name that corresponds to a non-empty
6121/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00006122TemplateName
6123ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6124 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00006125 unsigned size = End - Begin;
6126 assert(size > 1 && "set is not overloaded!");
6127
6128 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6129 size * sizeof(FunctionTemplateDecl*));
6130 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6131
6132 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00006133 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00006134 NamedDecl *D = *I;
6135 assert(isa<FunctionTemplateDecl>(D) ||
6136 (isa<UsingShadowDecl>(D) &&
6137 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6138 *Storage++ = D;
6139 }
6140
6141 return TemplateName(OT);
6142}
6143
Douglas Gregor7532dc62009-03-30 22:58:21 +00006144/// \brief Retrieve the template name that represents a qualified
6145/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00006146TemplateName
6147ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6148 bool TemplateKeyword,
6149 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00006150 assert(NNS && "Missing nested-name-specifier in qualified template name");
6151
Douglas Gregor789b1f62010-02-04 18:10:26 +00006152 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00006153 llvm::FoldingSetNodeID ID;
6154 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6155
6156 void *InsertPos = 0;
6157 QualifiedTemplateName *QTN =
6158 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6159 if (!QTN) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006160 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6161 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregor7532dc62009-03-30 22:58:21 +00006162 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6163 }
6164
6165 return TemplateName(QTN);
6166}
6167
6168/// \brief Retrieve the template name that represents a dependent
6169/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00006170TemplateName
6171ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6172 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00006173 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00006174 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00006175
6176 llvm::FoldingSetNodeID ID;
6177 DependentTemplateName::Profile(ID, NNS, Name);
6178
6179 void *InsertPos = 0;
6180 DependentTemplateName *QTN =
6181 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6182
6183 if (QTN)
6184 return TemplateName(QTN);
6185
6186 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6187 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006188 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6189 DependentTemplateName(NNS, Name);
Douglas Gregor7532dc62009-03-30 22:58:21 +00006190 } else {
6191 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smith2f47cab2012-08-16 01:19:31 +00006192 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6193 DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00006194 DependentTemplateName *CheckQTN =
6195 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6196 assert(!CheckQTN && "Dependent type name canonicalization broken");
6197 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00006198 }
6199
6200 DependentTemplateNames.InsertNode(QTN, InsertPos);
6201 return TemplateName(QTN);
6202}
6203
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006204/// \brief Retrieve the template name that represents a dependent
6205/// template name such as \c MetaFun::template operator+.
6206TemplateName
6207ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00006208 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006209 assert((!NNS || NNS->isDependent()) &&
6210 "Nested name specifier must be dependent");
6211
6212 llvm::FoldingSetNodeID ID;
6213 DependentTemplateName::Profile(ID, NNS, Operator);
6214
6215 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00006216 DependentTemplateName *QTN
6217 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006218
6219 if (QTN)
6220 return TemplateName(QTN);
6221
6222 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6223 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006224 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6225 DependentTemplateName(NNS, Operator);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006226 } else {
6227 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smith2f47cab2012-08-16 01:19:31 +00006228 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6229 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00006230
6231 DependentTemplateName *CheckQTN
6232 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6233 assert(!CheckQTN && "Dependent template name canonicalization broken");
6234 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006235 }
6236
6237 DependentTemplateNames.InsertNode(QTN, InsertPos);
6238 return TemplateName(QTN);
6239}
6240
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006241TemplateName
John McCall14606042011-06-30 08:33:18 +00006242ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6243 TemplateName replacement) const {
6244 llvm::FoldingSetNodeID ID;
6245 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6246
6247 void *insertPos = 0;
6248 SubstTemplateTemplateParmStorage *subst
6249 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6250
6251 if (!subst) {
6252 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6253 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6254 }
6255
6256 return TemplateName(subst);
6257}
6258
6259TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006260ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6261 const TemplateArgument &ArgPack) const {
6262 ASTContext &Self = const_cast<ASTContext &>(*this);
6263 llvm::FoldingSetNodeID ID;
6264 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6265
6266 void *InsertPos = 0;
6267 SubstTemplateTemplateParmPackStorage *Subst
6268 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6269
6270 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00006271 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006272 ArgPack.pack_size(),
6273 ArgPack.pack_begin());
6274 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6275 }
6276
6277 return TemplateName(Subst);
6278}
6279
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006280/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00006281/// TargetInfo, produce the corresponding type. The unsigned @p Type
6282/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00006283CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006284 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00006285 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006286 case TargetInfo::SignedShort: return ShortTy;
6287 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6288 case TargetInfo::SignedInt: return IntTy;
6289 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6290 case TargetInfo::SignedLong: return LongTy;
6291 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6292 case TargetInfo::SignedLongLong: return LongLongTy;
6293 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6294 }
6295
David Blaikieb219cfc2011-09-23 05:06:16 +00006296 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006297}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00006298
6299//===----------------------------------------------------------------------===//
6300// Type Predicates.
6301//===----------------------------------------------------------------------===//
6302
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006303/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6304/// garbage collection attribute.
6305///
John McCallae278a32011-01-12 00:34:59 +00006306Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006307 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00006308 return Qualifiers::GCNone;
6309
David Blaikie4e4d0842012-03-11 07:00:24 +00006310 assert(getLangOpts().ObjC1);
John McCallae278a32011-01-12 00:34:59 +00006311 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6312
6313 // Default behaviour under objective-C's gc is for ObjC pointers
6314 // (or pointers to them) be treated as though they were declared
6315 // as __strong.
6316 if (GCAttrs == Qualifiers::GCNone) {
6317 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6318 return Qualifiers::Strong;
6319 else if (Ty->isPointerType())
6320 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6321 } else {
6322 // It's not valid to set GC attributes on anything that isn't a
6323 // pointer.
6324#ifndef NDEBUG
6325 QualType CT = Ty->getCanonicalTypeInternal();
6326 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6327 CT = AT->getElementType();
6328 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6329#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006330 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00006331 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006332}
6333
Chris Lattner6ac46a42008-04-07 06:51:04 +00006334//===----------------------------------------------------------------------===//
6335// Type Compatibility Testing
6336//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00006337
Mike Stump1eb44332009-09-09 15:08:12 +00006338/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006339/// compatible.
6340static bool areCompatVectorTypes(const VectorType *LHS,
6341 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00006342 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00006343 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00006344 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00006345}
6346
Douglas Gregor255210e2010-08-06 10:14:59 +00006347bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6348 QualType SecondVec) {
6349 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6350 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6351
6352 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6353 return true;
6354
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006355 // Treat Neon vector types and most AltiVec vector types as if they are the
6356 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00006357 const VectorType *First = FirstVec->getAs<VectorType>();
6358 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006359 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00006360 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006361 First->getVectorKind() != VectorType::AltiVecPixel &&
6362 First->getVectorKind() != VectorType::AltiVecBool &&
6363 Second->getVectorKind() != VectorType::AltiVecPixel &&
6364 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00006365 return true;
6366
6367 return false;
6368}
6369
Steve Naroff4084c302009-07-23 01:01:38 +00006370//===----------------------------------------------------------------------===//
6371// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6372//===----------------------------------------------------------------------===//
6373
6374/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6375/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00006376bool
6377ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6378 ObjCProtocolDecl *rProto) const {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00006379 if (declaresSameEntity(lProto, rProto))
Steve Naroff4084c302009-07-23 01:01:38 +00006380 return true;
6381 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6382 E = rProto->protocol_end(); PI != E; ++PI)
6383 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6384 return true;
6385 return false;
6386}
6387
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00006388/// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
Steve Naroff4084c302009-07-23 01:01:38 +00006389/// return true if lhs's protocols conform to rhs's protocol; false
6390/// otherwise.
6391bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
6392 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
6393 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
6394 return false;
6395}
6396
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00006397/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6398/// Class<pr1, ...>.
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006399bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6400 QualType rhs) {
6401 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6402 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6403 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6404
6405 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6406 E = lhsQID->qual_end(); I != E; ++I) {
6407 bool match = false;
6408 ObjCProtocolDecl *lhsProto = *I;
6409 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6410 E = rhsOPT->qual_end(); J != E; ++J) {
6411 ObjCProtocolDecl *rhsProto = *J;
6412 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6413 match = true;
6414 break;
6415 }
6416 }
6417 if (!match)
6418 return false;
6419 }
6420 return true;
6421}
6422
Steve Naroff4084c302009-07-23 01:01:38 +00006423/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6424/// ObjCQualifiedIDType.
6425bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6426 bool compare) {
6427 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00006428 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006429 lhs->isObjCIdType() || lhs->isObjCClassType())
6430 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006431 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006432 rhs->isObjCIdType() || rhs->isObjCClassType())
6433 return true;
6434
6435 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00006436 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006437
Steve Naroff4084c302009-07-23 01:01:38 +00006438 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006439
Steve Naroff4084c302009-07-23 01:01:38 +00006440 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006441 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00006442 // make sure we check the class hierarchy.
6443 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6444 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6445 E = lhsQID->qual_end(); I != E; ++I) {
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.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006449 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00006450 return false;
6451 }
6452 }
6453 // If there are no qualifiers and no interface, we have an 'id'.
6454 return true;
6455 }
Mike Stump1eb44332009-09-09 15:08:12 +00006456 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006457 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6458 E = lhsQID->qual_end(); I != E; ++I) {
6459 ObjCProtocolDecl *lhsProto = *I;
6460 bool match = false;
6461
6462 // when comparing an id<P> on lhs with a static type on rhs,
6463 // see if static class implements all of id's protocols, directly or
6464 // through its super class and categories.
6465 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6466 E = rhsOPT->qual_end(); J != E; ++J) {
6467 ObjCProtocolDecl *rhsProto = *J;
6468 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6469 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6470 match = true;
6471 break;
6472 }
6473 }
Mike Stump1eb44332009-09-09 15:08:12 +00006474 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00006475 // make sure we check the class hierarchy.
6476 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6477 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6478 E = lhsQID->qual_end(); I != E; ++I) {
6479 // when comparing an id<P> on lhs with a static type on rhs,
6480 // see if static class implements all of id's protocols, directly or
6481 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006482 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00006483 match = true;
6484 break;
6485 }
6486 }
6487 }
6488 if (!match)
6489 return false;
6490 }
Mike Stump1eb44332009-09-09 15:08:12 +00006491
Steve Naroff4084c302009-07-23 01:01:38 +00006492 return true;
6493 }
Mike Stump1eb44332009-09-09 15:08:12 +00006494
Steve Naroff4084c302009-07-23 01:01:38 +00006495 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6496 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6497
Mike Stump1eb44332009-09-09 15:08:12 +00006498 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00006499 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006500 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006501 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6502 E = lhsOPT->qual_end(); I != E; ++I) {
6503 ObjCProtocolDecl *lhsProto = *I;
6504 bool match = false;
6505
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006506 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00006507 // see if static class implements all of id's protocols, directly or
6508 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006509 // First, lhs protocols in the qualifier list must be found, direct
6510 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00006511 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6512 E = rhsQID->qual_end(); J != E; ++J) {
6513 ObjCProtocolDecl *rhsProto = *J;
6514 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6515 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6516 match = true;
6517 break;
6518 }
6519 }
6520 if (!match)
6521 return false;
6522 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006523
6524 // Static class's protocols, or its super class or category protocols
6525 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6526 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6527 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6528 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6529 // This is rather dubious but matches gcc's behavior. If lhs has
6530 // no type qualifier and its class has no static protocol(s)
6531 // assume that it is mismatch.
6532 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6533 return false;
6534 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6535 LHSInheritedProtocols.begin(),
6536 E = LHSInheritedProtocols.end(); I != E; ++I) {
6537 bool match = false;
6538 ObjCProtocolDecl *lhsProto = (*I);
6539 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6540 E = rhsQID->qual_end(); J != E; ++J) {
6541 ObjCProtocolDecl *rhsProto = *J;
6542 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6543 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6544 match = true;
6545 break;
6546 }
6547 }
6548 if (!match)
6549 return false;
6550 }
6551 }
Steve Naroff4084c302009-07-23 01:01:38 +00006552 return true;
6553 }
6554 return false;
6555}
6556
Eli Friedman3d815e72008-08-22 00:56:42 +00006557/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006558/// compatible for assignment from RHS to LHS. This handles validation of any
6559/// protocol qualifiers on the LHS or RHS.
6560///
Steve Naroff14108da2009-07-10 23:34:53 +00006561bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6562 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00006563 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6564 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6565
Steve Naroffde2e22d2009-07-15 18:40:39 +00006566 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00006567 if (LHS->isObjCUnqualifiedIdOrClass() ||
6568 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00006569 return true;
6570
John McCallc12c5bb2010-05-15 11:32:37 +00006571 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00006572 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6573 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00006574 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006575
6576 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6577 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6578 QualType(RHSOPT,0));
6579
John McCallc12c5bb2010-05-15 11:32:37 +00006580 // If we have 2 user-defined types, fall into that path.
6581 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00006582 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006583
Steve Naroff4084c302009-07-23 01:01:38 +00006584 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006585}
6586
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006587/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00006588/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006589/// arguments in block literals. When passed as arguments, passing 'A*' where
6590/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6591/// not OK. For the return type, the opposite is not OK.
6592bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6593 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006594 const ObjCObjectPointerType *RHSOPT,
6595 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006596 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006597 return true;
6598
6599 if (LHSOPT->isObjCBuiltinType()) {
6600 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6601 }
6602
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006603 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006604 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6605 QualType(RHSOPT,0),
6606 false);
6607
6608 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6609 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6610 if (LHS && RHS) { // We have 2 user-defined types.
6611 if (LHS != RHS) {
6612 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006613 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006614 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006615 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006616 }
6617 else
6618 return true;
6619 }
6620 return false;
6621}
6622
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006623/// getIntersectionOfProtocols - This routine finds the intersection of set
6624/// of protocols inherited from two distinct objective-c pointer objects.
6625/// It is used to build composite qualifier list of the composite type of
6626/// the conditional expression involving two objective-c pointer objects.
6627static
6628void getIntersectionOfProtocols(ASTContext &Context,
6629 const ObjCObjectPointerType *LHSOPT,
6630 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006631 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006632
John McCallc12c5bb2010-05-15 11:32:37 +00006633 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6634 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6635 assert(LHS->getInterface() && "LHS must have an interface base");
6636 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006637
6638 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6639 unsigned LHSNumProtocols = LHS->getNumProtocols();
6640 if (LHSNumProtocols > 0)
6641 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6642 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006643 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006644 Context.CollectInheritedProtocols(LHS->getInterface(),
6645 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006646 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6647 LHSInheritedProtocols.end());
6648 }
6649
6650 unsigned RHSNumProtocols = RHS->getNumProtocols();
6651 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00006652 ObjCProtocolDecl **RHSProtocols =
6653 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006654 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6655 if (InheritedProtocolSet.count(RHSProtocols[i]))
6656 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00006657 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006658 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006659 Context.CollectInheritedProtocols(RHS->getInterface(),
6660 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006661 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6662 RHSInheritedProtocols.begin(),
6663 E = RHSInheritedProtocols.end(); I != E; ++I)
6664 if (InheritedProtocolSet.count((*I)))
6665 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006666 }
6667}
6668
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006669/// areCommonBaseCompatible - Returns common base class of the two classes if
6670/// one found. Note that this is O'2 algorithm. But it will be called as the
6671/// last type comparison in a ?-exp of ObjC pointer types before a
6672/// warning is issued. So, its invokation is extremely rare.
6673QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00006674 const ObjCObjectPointerType *Lptr,
6675 const ObjCObjectPointerType *Rptr) {
6676 const ObjCObjectType *LHS = Lptr->getObjectType();
6677 const ObjCObjectType *RHS = Rptr->getObjectType();
6678 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6679 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor60ef3082011-12-15 00:29:59 +00006680 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006681 return QualType();
6682
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006683 do {
John McCallc12c5bb2010-05-15 11:32:37 +00006684 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006685 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006686 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006687 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6688
6689 QualType Result = QualType(LHS, 0);
6690 if (!Protocols.empty())
6691 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6692 Result = getObjCObjectPointerType(Result);
6693 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006694 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006695 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006696
6697 return QualType();
6698}
6699
John McCallc12c5bb2010-05-15 11:32:37 +00006700bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6701 const ObjCObjectType *RHS) {
6702 assert(LHS->getInterface() && "LHS is not an interface type");
6703 assert(RHS->getInterface() && "RHS is not an interface type");
6704
Chris Lattner6ac46a42008-04-07 06:51:04 +00006705 // Verify that the base decls are compatible: the RHS must be a subclass of
6706 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00006707 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00006708 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006709
Chris Lattner6ac46a42008-04-07 06:51:04 +00006710 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6711 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00006712 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00006713 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006714
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006715 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6716 // more detailed analysis is required.
6717 if (RHS->getNumProtocols() == 0) {
6718 // OK, if LHS is a superclass of RHS *and*
6719 // this superclass is assignment compatible with LHS.
6720 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006721 bool IsSuperClass =
6722 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6723 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006724 // OK if conversion of LHS to SuperClass results in narrowing of types
6725 // ; i.e., SuperClass may implement at least one of the protocols
6726 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6727 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6728 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006729 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006730 // If super class has no protocols, it is not a match.
6731 if (SuperClassInheritedProtocols.empty())
6732 return false;
6733
6734 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6735 LHSPE = LHS->qual_end();
6736 LHSPI != LHSPE; LHSPI++) {
6737 bool SuperImplementsProtocol = false;
6738 ObjCProtocolDecl *LHSProto = (*LHSPI);
6739
6740 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6741 SuperClassInheritedProtocols.begin(),
6742 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6743 ObjCProtocolDecl *SuperClassProto = (*I);
6744 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6745 SuperImplementsProtocol = true;
6746 break;
6747 }
6748 }
6749 if (!SuperImplementsProtocol)
6750 return false;
6751 }
6752 return true;
6753 }
6754 return false;
6755 }
Mike Stump1eb44332009-09-09 15:08:12 +00006756
John McCallc12c5bb2010-05-15 11:32:37 +00006757 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6758 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006759 LHSPI != LHSPE; LHSPI++) {
6760 bool RHSImplementsProtocol = false;
6761
6762 // If the RHS doesn't implement the protocol on the left, the types
6763 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00006764 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6765 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00006766 RHSPI != RHSPE; RHSPI++) {
6767 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006768 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00006769 break;
6770 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006771 }
6772 // FIXME: For better diagnostics, consider passing back the protocol name.
6773 if (!RHSImplementsProtocol)
6774 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006775 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006776 // The RHS implements all protocols listed on the LHS.
6777 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006778}
6779
Steve Naroff389bf462009-02-12 17:52:19 +00006780bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6781 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00006782 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6783 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006784
Steve Naroff14108da2009-07-10 23:34:53 +00006785 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00006786 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006787
6788 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6789 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00006790}
6791
Douglas Gregor569c3162010-08-07 11:51:51 +00006792bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6793 return canAssignObjCInterfaces(
6794 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6795 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6796}
6797
Mike Stump1eb44332009-09-09 15:08:12 +00006798/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00006799/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00006800/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00006801/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00006802bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6803 bool CompareUnqualified) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006804 if (getLangOpts().CPlusPlus)
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006805 return hasSameType(LHS, RHS);
6806
Douglas Gregor447234d2010-07-29 15:18:02 +00006807 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00006808}
6809
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006810bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00006811 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006812}
6813
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006814bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6815 return !mergeTypes(LHS, RHS, true).isNull();
6816}
6817
Peter Collingbourne48466752010-10-24 18:30:18 +00006818/// mergeTransparentUnionType - if T is a transparent union type and a member
6819/// of T is compatible with SubType, return the merged type, else return
6820/// QualType()
6821QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6822 bool OfBlockPointer,
6823 bool Unqualified) {
6824 if (const RecordType *UT = T->getAsUnionType()) {
6825 RecordDecl *UD = UT->getDecl();
6826 if (UD->hasAttr<TransparentUnionAttr>()) {
6827 for (RecordDecl::field_iterator it = UD->field_begin(),
6828 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00006829 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006830 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6831 if (!MT.isNull())
6832 return MT;
6833 }
6834 }
6835 }
6836
6837 return QualType();
6838}
6839
6840/// mergeFunctionArgumentTypes - merge two types which appear as function
6841/// argument types
6842QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6843 bool OfBlockPointer,
6844 bool Unqualified) {
6845 // GNU extension: two types are compatible if they appear as a function
6846 // argument, one of the types is a transparent union type and the other
6847 // type is compatible with a union member
6848 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6849 Unqualified);
6850 if (!lmerge.isNull())
6851 return lmerge;
6852
6853 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6854 Unqualified);
6855 if (!rmerge.isNull())
6856 return rmerge;
6857
6858 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6859}
6860
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006861QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00006862 bool OfBlockPointer,
6863 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00006864 const FunctionType *lbase = lhs->getAs<FunctionType>();
6865 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00006866 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6867 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00006868 bool allLTypes = true;
6869 bool allRTypes = true;
6870
6871 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006872 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006873 if (OfBlockPointer) {
6874 QualType RHS = rbase->getResultType();
6875 QualType LHS = lbase->getResultType();
6876 bool UnqualifiedResult = Unqualified;
6877 if (!UnqualifiedResult)
6878 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006879 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006880 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006881 else
John McCall8cc246c2010-12-15 01:06:38 +00006882 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6883 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006884 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006885
6886 if (Unqualified)
6887 retType = retType.getUnqualifiedType();
6888
6889 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6890 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6891 if (Unqualified) {
6892 LRetType = LRetType.getUnqualifiedType();
6893 RRetType = RRetType.getUnqualifiedType();
6894 }
6895
6896 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006897 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00006898 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006899 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00006900
Daniel Dunbar6a15c852010-04-28 16:20:58 +00006901 // FIXME: double check this
6902 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6903 // rbase->getRegParmAttr() != 0 &&
6904 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00006905 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6906 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00006907
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006908 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00006909 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006910 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006911
John McCall8cc246c2010-12-15 01:06:38 +00006912 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00006913 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6914 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00006915 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6916 return QualType();
6917
John McCallf85e1932011-06-15 23:02:42 +00006918 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6919 return QualType();
6920
John McCall8cc246c2010-12-15 01:06:38 +00006921 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6922 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00006923
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00006924 if (lbaseInfo.getNoReturn() != NoReturn)
6925 allLTypes = false;
6926 if (rbaseInfo.getNoReturn() != NoReturn)
6927 allRTypes = false;
6928
John McCallf85e1932011-06-15 23:02:42 +00006929 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00006930
Eli Friedman3d815e72008-08-22 00:56:42 +00006931 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00006932 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6933 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006934 unsigned lproto_nargs = lproto->getNumArgs();
6935 unsigned rproto_nargs = rproto->getNumArgs();
6936
6937 // Compatible functions must have the same number of arguments
6938 if (lproto_nargs != rproto_nargs)
6939 return QualType();
6940
6941 // Variadic and non-variadic functions aren't compatible
6942 if (lproto->isVariadic() != rproto->isVariadic())
6943 return QualType();
6944
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00006945 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6946 return QualType();
6947
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006948 if (LangOpts.ObjCAutoRefCount &&
6949 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6950 return QualType();
6951
Eli Friedman3d815e72008-08-22 00:56:42 +00006952 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00006953 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00006954 for (unsigned i = 0; i < lproto_nargs; i++) {
6955 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6956 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006957 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6958 OfBlockPointer,
6959 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006960 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006961
6962 if (Unqualified)
6963 argtype = argtype.getUnqualifiedType();
6964
Eli Friedman3d815e72008-08-22 00:56:42 +00006965 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00006966 if (Unqualified) {
6967 largtype = largtype.getUnqualifiedType();
6968 rargtype = rargtype.getUnqualifiedType();
6969 }
6970
Chris Lattner61710852008-10-05 17:34:18 +00006971 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6972 allLTypes = false;
6973 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6974 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00006975 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006976
Eli Friedman3d815e72008-08-22 00:56:42 +00006977 if (allLTypes) return lhs;
6978 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00006979
6980 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6981 EPI.ExtInfo = einfo;
Jordan Rosebea522f2013-03-08 21:51:21 +00006982 return getFunctionType(retType, types, EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00006983 }
6984
6985 if (lproto) allRTypes = false;
6986 if (rproto) allLTypes = false;
6987
Douglas Gregor72564e72009-02-26 23:50:07 +00006988 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00006989 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00006990 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006991 if (proto->isVariadic()) return QualType();
6992 // Check that the types are compatible with the types that
6993 // would result from default argument promotions (C99 6.7.5.3p15).
6994 // The only types actually affected are promotable integer
6995 // types and floats, which would be passed as a different
6996 // type depending on whether the prototype is visible.
6997 unsigned proto_nargs = proto->getNumArgs();
6998 for (unsigned i = 0; i < proto_nargs; ++i) {
6999 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007000
Eli Friedmanc586d5d2012-08-30 00:44:15 +00007001 // Look at the converted type of enum types, since that is the type used
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007002 // to pass enum values.
Eli Friedmanc586d5d2012-08-30 00:44:15 +00007003 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
7004 argTy = Enum->getDecl()->getIntegerType();
7005 if (argTy.isNull())
7006 return QualType();
7007 }
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007008
Eli Friedman3d815e72008-08-22 00:56:42 +00007009 if (argTy->isPromotableIntegerType() ||
7010 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
7011 return QualType();
7012 }
7013
7014 if (allLTypes) return lhs;
7015 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00007016
7017 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7018 EPI.ExtInfo = einfo;
Jordan Rosebea522f2013-03-08 21:51:21 +00007019 return getFunctionType(retType,
7020 ArrayRef<QualType>(proto->arg_type_begin(),
7021 proto->getNumArgs()),
7022 EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00007023 }
7024
7025 if (allLTypes) return lhs;
7026 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00007027 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00007028}
7029
John McCallb9da7132013-03-21 00:10:07 +00007030/// Given that we have an enum type and a non-enum type, try to merge them.
7031static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7032 QualType other, bool isBlockReturnType) {
7033 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7034 // a signed integer type, or an unsigned integer type.
7035 // Compatibility is based on the underlying type, not the promotion
7036 // type.
7037 QualType underlyingType = ET->getDecl()->getIntegerType();
7038 if (underlyingType.isNull()) return QualType();
7039 if (Context.hasSameType(underlyingType, other))
7040 return other;
7041
7042 // In block return types, we're more permissive and accept any
7043 // integral type of the same size.
7044 if (isBlockReturnType && other->isIntegerType() &&
7045 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7046 return other;
7047
7048 return QualType();
7049}
7050
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007051QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00007052 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00007053 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00007054 // C++ [expr]: If an expression initially has the type "reference to T", the
7055 // type is adjusted to "T" prior to any further analysis, the expression
7056 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00007057 // expression is an lvalue unless the reference is an rvalue reference and
7058 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00007059 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7060 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00007061
7062 if (Unqualified) {
7063 LHS = LHS.getUnqualifiedType();
7064 RHS = RHS.getUnqualifiedType();
7065 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00007066
Eli Friedman3d815e72008-08-22 00:56:42 +00007067 QualType LHSCan = getCanonicalType(LHS),
7068 RHSCan = getCanonicalType(RHS);
7069
7070 // If two types are identical, they are compatible.
7071 if (LHSCan == RHSCan)
7072 return LHS;
7073
John McCall0953e762009-09-24 19:53:00 +00007074 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00007075 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7076 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00007077 if (LQuals != RQuals) {
7078 // If any of these qualifiers are different, we have a type
7079 // mismatch.
7080 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00007081 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7082 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00007083 return QualType();
7084
7085 // Exactly one GC qualifier difference is allowed: __strong is
7086 // okay if the other type has no GC qualifier but is an Objective
7087 // C object pointer (i.e. implicitly strong by default). We fix
7088 // this by pretending that the unqualified type was actually
7089 // qualified __strong.
7090 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7091 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7092 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7093
7094 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7095 return QualType();
7096
7097 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7098 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7099 }
7100 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7101 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7102 }
Eli Friedman3d815e72008-08-22 00:56:42 +00007103 return QualType();
John McCall0953e762009-09-24 19:53:00 +00007104 }
7105
7106 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00007107
Eli Friedman852d63b2009-06-01 01:22:52 +00007108 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7109 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00007110
Chris Lattner1adb8832008-01-14 05:45:46 +00007111 // We want to consider the two function types to be the same for these
7112 // comparisons, just force one to the other.
7113 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7114 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00007115
7116 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00007117 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7118 LHSClass = Type::ConstantArray;
7119 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7120 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00007121
John McCallc12c5bb2010-05-15 11:32:37 +00007122 // ObjCInterfaces are just specialized ObjCObjects.
7123 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7124 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7125
Nate Begeman213541a2008-04-18 23:10:10 +00007126 // Canonicalize ExtVector -> Vector.
7127 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7128 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00007129
Chris Lattnera36a61f2008-04-07 05:43:21 +00007130 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00007131 if (LHSClass != RHSClass) {
John McCallb9da7132013-03-21 00:10:07 +00007132 // Note that we only have special rules for turning block enum
7133 // returns into block int returns, not vice-versa.
John McCall183700f2009-09-21 23:43:11 +00007134 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCallb9da7132013-03-21 00:10:07 +00007135 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmanbab96962008-02-12 08:46:17 +00007136 }
John McCall183700f2009-09-21 23:43:11 +00007137 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCallb9da7132013-03-21 00:10:07 +00007138 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmanbab96962008-02-12 08:46:17 +00007139 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00007140 // allow block pointer type to match an 'id' type.
Fariborz Jahanian41963632012-01-26 17:08:50 +00007141 if (OfBlockPointer && !BlockReturnType) {
7142 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7143 return LHS;
7144 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7145 return RHS;
7146 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00007147
Eli Friedman3d815e72008-08-22 00:56:42 +00007148 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00007149 }
Eli Friedman3d815e72008-08-22 00:56:42 +00007150
Steve Naroff4a746782008-01-09 22:43:08 +00007151 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00007152 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00007153#define TYPE(Class, Base)
7154#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00007155#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00007156#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7157#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7158#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00007159 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00007160
Richard Smithdc7a4f52013-04-30 13:56:41 +00007161 case Type::Auto:
Sebastian Redl7c80bd62009-03-16 23:22:08 +00007162 case Type::LValueReference:
7163 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00007164 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00007165 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00007166
John McCallc12c5bb2010-05-15 11:32:37 +00007167 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00007168 case Type::IncompleteArray:
7169 case Type::VariableArray:
7170 case Type::FunctionProto:
7171 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00007172 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00007173
Chris Lattner1adb8832008-01-14 05:45:46 +00007174 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00007175 {
7176 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00007177 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7178 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007179 if (Unqualified) {
7180 LHSPointee = LHSPointee.getUnqualifiedType();
7181 RHSPointee = RHSPointee.getUnqualifiedType();
7182 }
7183 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7184 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00007185 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00007186 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00007187 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00007188 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00007189 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00007190 return getPointerType(ResultType);
7191 }
Steve Naroffc0febd52008-12-10 17:49:55 +00007192 case Type::BlockPointer:
7193 {
7194 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00007195 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7196 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007197 if (Unqualified) {
7198 LHSPointee = LHSPointee.getUnqualifiedType();
7199 RHSPointee = RHSPointee.getUnqualifiedType();
7200 }
7201 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7202 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00007203 if (ResultType.isNull()) return QualType();
7204 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7205 return LHS;
7206 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7207 return RHS;
7208 return getBlockPointerType(ResultType);
7209 }
Eli Friedmanb001de72011-10-06 23:00:33 +00007210 case Type::Atomic:
7211 {
7212 // Merge two pointer types, while trying to preserve typedef info
7213 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7214 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7215 if (Unqualified) {
7216 LHSValue = LHSValue.getUnqualifiedType();
7217 RHSValue = RHSValue.getUnqualifiedType();
7218 }
7219 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7220 Unqualified);
7221 if (ResultType.isNull()) return QualType();
7222 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7223 return LHS;
7224 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7225 return RHS;
7226 return getAtomicType(ResultType);
7227 }
Chris Lattner1adb8832008-01-14 05:45:46 +00007228 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00007229 {
7230 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7231 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7232 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7233 return QualType();
7234
7235 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7236 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007237 if (Unqualified) {
7238 LHSElem = LHSElem.getUnqualifiedType();
7239 RHSElem = RHSElem.getUnqualifiedType();
7240 }
7241
7242 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00007243 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00007244 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7245 return LHS;
7246 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7247 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00007248 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7249 ArrayType::ArraySizeModifier(), 0);
7250 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7251 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00007252 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7253 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00007254 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7255 return LHS;
7256 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7257 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00007258 if (LVAT) {
7259 // FIXME: This isn't correct! But tricky to implement because
7260 // the array's size has to be the size of LHS, but the type
7261 // has to be different.
7262 return LHS;
7263 }
7264 if (RVAT) {
7265 // FIXME: This isn't correct! But tricky to implement because
7266 // the array's size has to be the size of RHS, but the type
7267 // has to be different.
7268 return RHS;
7269 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00007270 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7271 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00007272 return getIncompleteArrayType(ResultType,
7273 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00007274 }
Chris Lattner1adb8832008-01-14 05:45:46 +00007275 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00007276 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00007277 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00007278 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00007279 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00007280 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00007281 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00007282 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00007283 case Type::Complex:
7284 // Distinct complex types are incompatible.
7285 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00007286 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00007287 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00007288 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7289 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00007290 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00007291 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00007292 case Type::ObjCObject: {
7293 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00007294 // FIXME: This should be type compatibility, e.g. whether
7295 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00007296 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7297 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7298 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00007299 return LHS;
7300
Eli Friedman3d815e72008-08-22 00:56:42 +00007301 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00007302 }
Steve Naroff14108da2009-07-10 23:34:53 +00007303 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007304 if (OfBlockPointer) {
7305 if (canAssignObjCInterfacesInBlockPointer(
7306 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00007307 RHS->getAs<ObjCObjectPointerType>(),
7308 BlockReturnType))
David Blaikie7530c032012-01-17 06:56:22 +00007309 return LHS;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007310 return QualType();
7311 }
John McCall183700f2009-09-21 23:43:11 +00007312 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7313 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00007314 return LHS;
7315
Steve Naroffbc76dd02008-12-10 22:14:21 +00007316 return QualType();
David Blaikie7530c032012-01-17 06:56:22 +00007317 }
Steve Naroffec0550f2007-10-15 20:41:53 +00007318 }
Douglas Gregor72564e72009-02-26 23:50:07 +00007319
David Blaikie7530c032012-01-17 06:56:22 +00007320 llvm_unreachable("Invalid Type::Class!");
Steve Naroffec0550f2007-10-15 20:41:53 +00007321}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00007322
Fariborz Jahanian78213e42011-09-28 21:52:05 +00007323bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7324 const FunctionProtoType *FromFunctionType,
7325 const FunctionProtoType *ToFunctionType) {
7326 if (FromFunctionType->hasAnyConsumedArgs() !=
7327 ToFunctionType->hasAnyConsumedArgs())
7328 return false;
7329 FunctionProtoType::ExtProtoInfo FromEPI =
7330 FromFunctionType->getExtProtoInfo();
7331 FunctionProtoType::ExtProtoInfo ToEPI =
7332 ToFunctionType->getExtProtoInfo();
7333 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
7334 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
7335 ArgIdx != NumArgs; ++ArgIdx) {
7336 if (FromEPI.ConsumedArguments[ArgIdx] !=
7337 ToEPI.ConsumedArguments[ArgIdx])
7338 return false;
7339 }
7340 return true;
7341}
7342
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007343/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7344/// 'RHS' attributes and returns the merged version; including for function
7345/// return types.
7346QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7347 QualType LHSCan = getCanonicalType(LHS),
7348 RHSCan = getCanonicalType(RHS);
7349 // If two types are identical, they are compatible.
7350 if (LHSCan == RHSCan)
7351 return LHS;
7352 if (RHSCan->isFunctionType()) {
7353 if (!LHSCan->isFunctionType())
7354 return QualType();
7355 QualType OldReturnType =
7356 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7357 QualType NewReturnType =
7358 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7359 QualType ResReturnType =
7360 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7361 if (ResReturnType.isNull())
7362 return QualType();
7363 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7364 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7365 // In either case, use OldReturnType to build the new function type.
7366 const FunctionType *F = LHS->getAs<FunctionType>();
7367 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00007368 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7369 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007370 QualType ResultType
Jordan Rosebea522f2013-03-08 21:51:21 +00007371 = getFunctionType(OldReturnType,
7372 ArrayRef<QualType>(FPT->arg_type_begin(),
7373 FPT->getNumArgs()),
7374 EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007375 return ResultType;
7376 }
7377 }
7378 return QualType();
7379 }
7380
7381 // If the qualifiers are different, the types can still be merged.
7382 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7383 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7384 if (LQuals != RQuals) {
7385 // If any of these qualifiers are different, we have a type mismatch.
7386 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7387 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7388 return QualType();
7389
7390 // Exactly one GC qualifier difference is allowed: __strong is
7391 // okay if the other type has no GC qualifier but is an Objective
7392 // C object pointer (i.e. implicitly strong by default). We fix
7393 // this by pretending that the unqualified type was actually
7394 // qualified __strong.
7395 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7396 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7397 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7398
7399 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7400 return QualType();
7401
7402 if (GC_L == Qualifiers::Strong)
7403 return LHS;
7404 if (GC_R == Qualifiers::Strong)
7405 return RHS;
7406 return QualType();
7407 }
7408
7409 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7410 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7411 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7412 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7413 if (ResQT == LHSBaseQT)
7414 return LHS;
7415 if (ResQT == RHSBaseQT)
7416 return RHS;
7417 }
7418 return QualType();
7419}
7420
Chris Lattner5426bf62008-04-07 07:01:58 +00007421//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00007422// Integer Predicates
7423//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00007424
Jay Foad4ba2a172011-01-12 09:06:06 +00007425unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00007426 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00007427 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007428 if (T->isBooleanType())
7429 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00007430 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00007431 return (unsigned)getTypeSize(T);
7432}
7433
Abramo Bagnara762f1592012-09-09 10:21:24 +00007434QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregorf6094622010-07-23 15:58:24 +00007435 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00007436
7437 // Turn <4 x signed int> -> <4 x unsigned int>
7438 if (const VectorType *VTy = T->getAs<VectorType>())
7439 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00007440 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00007441
7442 // For enums, we return the unsigned version of the base type.
7443 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00007444 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00007445
7446 const BuiltinType *BTy = T->getAs<BuiltinType>();
7447 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007448 switch (BTy->getKind()) {
7449 case BuiltinType::Char_S:
7450 case BuiltinType::SChar:
7451 return UnsignedCharTy;
7452 case BuiltinType::Short:
7453 return UnsignedShortTy;
7454 case BuiltinType::Int:
7455 return UnsignedIntTy;
7456 case BuiltinType::Long:
7457 return UnsignedLongTy;
7458 case BuiltinType::LongLong:
7459 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00007460 case BuiltinType::Int128:
7461 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00007462 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00007463 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007464 }
7465}
7466
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00007467ASTMutationListener::~ASTMutationListener() { }
7468
Richard Smith9dadfab2013-05-11 05:45:24 +00007469void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7470 QualType ReturnType) {}
Chris Lattner86df27b2009-06-14 00:45:47 +00007471
7472//===----------------------------------------------------------------------===//
7473// Builtin Type Computation
7474//===----------------------------------------------------------------------===//
7475
7476/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00007477/// pointer over the consumed characters. This returns the resultant type. If
7478/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7479/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7480/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00007481///
7482/// RequiresICE is filled in on return to indicate whether the value is required
7483/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00007484static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00007485 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00007486 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00007487 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00007488 // Modifiers.
7489 int HowLong = 0;
7490 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00007491 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007492
Chris Lattner33daae62010-10-01 22:42:38 +00007493 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00007494 bool Done = false;
7495 while (!Done) {
7496 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00007497 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007498 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00007499 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007500 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007501 case 'S':
7502 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7503 assert(!Signed && "Can't use 'S' modifier multiple times!");
7504 Signed = true;
7505 break;
7506 case 'U':
7507 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7508 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7509 Unsigned = true;
7510 break;
7511 case 'L':
7512 assert(HowLong <= 2 && "Can't have LLLL modifier");
7513 ++HowLong;
7514 break;
7515 }
7516 }
7517
7518 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00007519
Chris Lattner86df27b2009-06-14 00:45:47 +00007520 // Read the base type.
7521 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00007522 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00007523 case 'v':
7524 assert(HowLong == 0 && !Signed && !Unsigned &&
7525 "Bad modifiers used with 'v'!");
7526 Type = Context.VoidTy;
7527 break;
7528 case 'f':
7529 assert(HowLong == 0 && !Signed && !Unsigned &&
7530 "Bad modifiers used with 'f'!");
7531 Type = Context.FloatTy;
7532 break;
7533 case 'd':
7534 assert(HowLong < 2 && !Signed && !Unsigned &&
7535 "Bad modifiers used with 'd'!");
7536 if (HowLong)
7537 Type = Context.LongDoubleTy;
7538 else
7539 Type = Context.DoubleTy;
7540 break;
7541 case 's':
7542 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7543 if (Unsigned)
7544 Type = Context.UnsignedShortTy;
7545 else
7546 Type = Context.ShortTy;
7547 break;
7548 case 'i':
7549 if (HowLong == 3)
7550 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7551 else if (HowLong == 2)
7552 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7553 else if (HowLong == 1)
7554 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7555 else
7556 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7557 break;
7558 case 'c':
7559 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7560 if (Signed)
7561 Type = Context.SignedCharTy;
7562 else if (Unsigned)
7563 Type = Context.UnsignedCharTy;
7564 else
7565 Type = Context.CharTy;
7566 break;
7567 case 'b': // boolean
7568 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7569 Type = Context.BoolTy;
7570 break;
7571 case 'z': // size_t.
7572 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7573 Type = Context.getSizeType();
7574 break;
7575 case 'F':
7576 Type = Context.getCFConstantStringType();
7577 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00007578 case 'G':
7579 Type = Context.getObjCIdType();
7580 break;
7581 case 'H':
7582 Type = Context.getObjCSelType();
7583 break;
Fariborz Jahanianf7992132013-01-04 18:45:40 +00007584 case 'M':
7585 Type = Context.getObjCSuperType();
7586 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007587 case 'a':
7588 Type = Context.getBuiltinVaListType();
7589 assert(!Type.isNull() && "builtin va list type not initialized!");
7590 break;
7591 case 'A':
7592 // This is a "reference" to a va_list; however, what exactly
7593 // this means depends on how va_list is defined. There are two
7594 // different kinds of va_list: ones passed by value, and ones
7595 // passed by reference. An example of a by-value va_list is
7596 // x86, where va_list is a char*. An example of by-ref va_list
7597 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7598 // we want this argument to be a char*&; for x86-64, we want
7599 // it to be a __va_list_tag*.
7600 Type = Context.getBuiltinVaListType();
7601 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00007602 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00007603 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00007604 else
Chris Lattner86df27b2009-06-14 00:45:47 +00007605 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00007606 break;
7607 case 'V': {
7608 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00007609 unsigned NumElements = strtoul(Str, &End, 10);
7610 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00007611 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00007612
Chris Lattner14e0e742010-10-01 22:53:11 +00007613 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7614 RequiresICE, false);
7615 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00007616
7617 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00007618 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00007619 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00007620 break;
7621 }
Douglas Gregorb4bc99b2012-06-07 18:08:25 +00007622 case 'E': {
7623 char *End;
7624
7625 unsigned NumElements = strtoul(Str, &End, 10);
7626 assert(End != Str && "Missing vector size");
7627
7628 Str = End;
7629
7630 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7631 false);
7632 Type = Context.getExtVectorType(ElementType, NumElements);
7633 break;
7634 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00007635 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00007636 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7637 false);
7638 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00007639 Type = Context.getComplexType(ElementType);
7640 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00007641 }
7642 case 'Y' : {
7643 Type = Context.getPointerDiffType();
7644 break;
7645 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007646 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00007647 Type = Context.getFILEType();
7648 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007649 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00007650 return QualType();
7651 }
Mike Stumpfd612db2009-07-28 23:47:15 +00007652 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007653 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00007654 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00007655 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00007656 else
7657 Type = Context.getjmp_bufType();
7658
Mike Stumpfd612db2009-07-28 23:47:15 +00007659 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007660 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00007661 return QualType();
7662 }
7663 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00007664 case 'K':
7665 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7666 Type = Context.getucontext_tType();
7667
7668 if (Type.isNull()) {
7669 Error = ASTContext::GE_Missing_ucontext;
7670 return QualType();
7671 }
7672 break;
Eli Friedman6902e412012-11-27 02:58:24 +00007673 case 'p':
7674 Type = Context.getProcessIDType();
7675 break;
Mike Stump782fa302009-07-28 02:25:19 +00007676 }
Mike Stump1eb44332009-09-09 15:08:12 +00007677
Chris Lattner33daae62010-10-01 22:42:38 +00007678 // If there are modifiers and if we're allowed to parse them, go for it.
7679 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00007680 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00007681 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00007682 default: Done = true; --Str; break;
7683 case '*':
7684 case '&': {
7685 // Both pointers and references can have their pointee types
7686 // qualified with an address space.
7687 char *End;
7688 unsigned AddrSpace = strtoul(Str, &End, 10);
7689 if (End != Str && AddrSpace != 0) {
7690 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7691 Str = End;
7692 }
7693 if (c == '*')
7694 Type = Context.getPointerType(Type);
7695 else
7696 Type = Context.getLValueReferenceType(Type);
7697 break;
7698 }
7699 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7700 case 'C':
7701 Type = Type.withConst();
7702 break;
7703 case 'D':
7704 Type = Context.getVolatileType(Type);
7705 break;
Ted Kremenek18932a02012-01-20 21:40:12 +00007706 case 'R':
7707 Type = Type.withRestrict();
7708 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007709 }
7710 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00007711
Chris Lattner14e0e742010-10-01 22:53:11 +00007712 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00007713 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00007714
Chris Lattner86df27b2009-06-14 00:45:47 +00007715 return Type;
7716}
7717
7718/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00007719QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00007720 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00007721 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00007722 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00007723
Chris Lattner5f9e2722011-07-23 10:55:15 +00007724 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00007725
Chris Lattner14e0e742010-10-01 22:53:11 +00007726 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00007727 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00007728 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7729 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007730 if (Error != GE_None)
7731 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00007732
7733 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7734
Chris Lattner86df27b2009-06-14 00:45:47 +00007735 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00007736 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007737 if (Error != GE_None)
7738 return QualType();
7739
Chris Lattner14e0e742010-10-01 22:53:11 +00007740 // If this argument is required to be an IntegerConstantExpression and the
7741 // caller cares, fill in the bitmask we return.
7742 if (RequiresICE && IntegerConstantArgs)
7743 *IntegerConstantArgs |= 1 << ArgTypes.size();
7744
Chris Lattner86df27b2009-06-14 00:45:47 +00007745 // Do array -> pointer decay. The builtin should use the decayed type.
7746 if (Ty->isArrayType())
7747 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00007748
Chris Lattner86df27b2009-06-14 00:45:47 +00007749 ArgTypes.push_back(Ty);
7750 }
7751
7752 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7753 "'.' should only occur at end of builtin type list!");
7754
John McCall00ccbef2010-12-21 00:44:39 +00007755 FunctionType::ExtInfo EI;
7756 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7757
7758 bool Variadic = (TypeStr[0] == '.');
7759
7760 // We really shouldn't be making a no-proto type here, especially in C++.
7761 if (ArgTypes.empty() && Variadic)
7762 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00007763
John McCalle23cf432010-12-14 08:05:40 +00007764 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00007765 EPI.ExtInfo = EI;
7766 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00007767
Jordan Rosebea522f2013-03-08 21:51:21 +00007768 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00007769}
Eli Friedmana95d7572009-08-19 07:44:53 +00007770
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007771GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007772 if (!FD->isExternallyVisible())
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007773 return GVA_Internal;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007774
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007775 GVALinkage External = GVA_StrongExternal;
7776 switch (FD->getTemplateSpecializationKind()) {
7777 case TSK_Undeclared:
7778 case TSK_ExplicitSpecialization:
7779 External = GVA_StrongExternal;
7780 break;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007781
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007782 case TSK_ExplicitInstantiationDefinition:
7783 return GVA_ExplicitTemplateInstantiation;
7784
7785 case TSK_ExplicitInstantiationDeclaration:
7786 case TSK_ImplicitInstantiation:
7787 External = GVA_TemplateInstantiation;
7788 break;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007789 }
7790
7791 if (!FD->isInlined())
7792 return External;
7793
David Blaikie4e4d0842012-03-11 07:00:24 +00007794 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007795 // GNU or C99 inline semantics. Determine whether this symbol should be
7796 // externally visible.
7797 if (FD->isInlineDefinitionExternallyVisible())
7798 return External;
7799
7800 // C99 inline semantics, where the symbol is not externally visible.
7801 return GVA_C99Inline;
7802 }
7803
7804 // C++0x [temp.explicit]p9:
7805 // [ Note: The intent is that an inline function that is the subject of
7806 // an explicit instantiation declaration will still be implicitly
7807 // instantiated when used so that the body can be considered for
7808 // inlining, but that no out-of-line copy of the inline function would be
7809 // generated in the translation unit. -- end note ]
7810 if (FD->getTemplateSpecializationKind()
7811 == TSK_ExplicitInstantiationDeclaration)
7812 return GVA_C99Inline;
7813
7814 return GVA_CXXInline;
7815}
7816
7817GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007818 if (!VD->isExternallyVisible())
7819 return GVA_Internal;
7820
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007821 // If this is a static data member, compute the kind of template
7822 // specialization. Otherwise, this variable is not part of a
7823 // template.
7824 TemplateSpecializationKind TSK = TSK_Undeclared;
7825 if (VD->isStaticDataMember())
7826 TSK = VD->getTemplateSpecializationKind();
7827
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007828 switch (TSK) {
7829 case TSK_Undeclared:
7830 case TSK_ExplicitSpecialization:
7831 return GVA_StrongExternal;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007832
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007833 case TSK_ExplicitInstantiationDeclaration:
7834 llvm_unreachable("Variable should not be instantiated");
7835 // Fall through to treat this like any other instantiation.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007836
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007837 case TSK_ExplicitInstantiationDefinition:
7838 return GVA_ExplicitTemplateInstantiation;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007839
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007840 case TSK_ImplicitInstantiation:
7841 return GVA_TemplateInstantiation;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007842 }
Rafael Espindola77b50252013-05-13 14:05:53 +00007843
7844 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007845}
7846
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00007847bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007848 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7849 if (!VD->isFileVarDecl())
7850 return false;
Richard Smithf396ad92013-04-01 20:22:16 +00007851 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7852 // We never need to emit an uninstantiated function template.
7853 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7854 return false;
7855 } else
7856 return false;
7857
7858 // If this is a member of a class template, we do not need to emit it.
7859 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007860 return false;
7861
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007862 // Weak references don't produce any output by themselves.
7863 if (D->hasAttr<WeakRefAttr>())
7864 return false;
7865
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007866 // Aliases and used decls are required.
7867 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7868 return true;
7869
7870 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7871 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00007872 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00007873 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007874
7875 // Constructors and destructors are required.
7876 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7877 return true;
7878
John McCalld5617ee2013-01-25 22:31:03 +00007879 // The key function for a class is required. This rule only comes
7880 // into play when inline functions can be key functions, though.
7881 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7882 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7883 const CXXRecordDecl *RD = MD->getParent();
7884 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7885 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7886 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7887 return true;
7888 }
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007889 }
7890 }
7891
7892 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7893
7894 // static, static inline, always_inline, and extern inline functions can
7895 // always be deferred. Normal inline functions can be deferred in C99/C++.
7896 // Implicit template instantiations can also be deferred in C++.
7897 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev3a5aca82012-02-02 06:06:34 +00007898 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007899 return false;
7900 return true;
7901 }
Douglas Gregor94da1582011-09-10 00:22:34 +00007902
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007903 const VarDecl *VD = cast<VarDecl>(D);
7904 assert(VD->isFileVarDecl() && "Expected file scoped var");
7905
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007906 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7907 return false;
7908
Richard Smith5f9a7e32012-11-12 21:38:00 +00007909 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007910 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smith5f9a7e32012-11-12 21:38:00 +00007911 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7912 return true;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007913
Richard Smith5f9a7e32012-11-12 21:38:00 +00007914 // Variables that have destruction with side-effects are required.
7915 if (VD->getType().isDestructedType())
7916 return true;
7917
7918 // Variables that have initialization with side-effects are required.
7919 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7920 return true;
7921
7922 return false;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007923}
Charles Davis071cc7d2010-08-16 03:33:14 +00007924
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007925CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davisee743f92010-11-09 18:04:24 +00007926 // Pass through to the C++ ABI object
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007927 return ABI->getDefaultMethodCallConv(isVariadic);
7928}
7929
7930CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
John McCallb8b2c9d2013-01-25 22:30:49 +00007931 if (CC == CC_C && !LangOpts.MRTD &&
7932 getTargetInfo().getCXXABI().isMemberFunctionCCDefault())
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007933 return CC_Default;
7934 return CC;
Charles Davisee743f92010-11-09 18:04:24 +00007935}
7936
Jay Foad4ba2a172011-01-12 09:06:06 +00007937bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00007938 // Pass through to the C++ ABI object
7939 return ABI->isNearlyEmpty(RD);
7940}
7941
Peter Collingbourne14110472011-01-13 18:57:25 +00007942MangleContext *ASTContext::createMangleContext() {
John McCallb8b2c9d2013-01-25 22:30:49 +00007943 switch (Target->getCXXABI().getKind()) {
Tim Northoverc264e162013-01-31 12:13:10 +00007944 case TargetCXXABI::GenericAArch64:
John McCallb8b2c9d2013-01-25 22:30:49 +00007945 case TargetCXXABI::GenericItanium:
7946 case TargetCXXABI::GenericARM:
7947 case TargetCXXABI::iOS:
Peter Collingbourne14110472011-01-13 18:57:25 +00007948 return createItaniumMangleContext(*this, getDiagnostics());
John McCallb8b2c9d2013-01-25 22:30:49 +00007949 case TargetCXXABI::Microsoft:
Peter Collingbourne14110472011-01-13 18:57:25 +00007950 return createMicrosoftMangleContext(*this, getDiagnostics());
7951 }
David Blaikieb219cfc2011-09-23 05:06:16 +00007952 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00007953}
7954
Charles Davis071cc7d2010-08-16 03:33:14 +00007955CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00007956
7957size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00007958 return ASTRecordLayouts.getMemorySize()
7959 + llvm::capacity_in_bytes(ObjCLayouts)
7960 + llvm::capacity_in_bytes(KeyFunctions)
7961 + llvm::capacity_in_bytes(ObjCImpls)
7962 + llvm::capacity_in_bytes(BlockVarCopyInits)
7963 + llvm::capacity_in_bytes(DeclAttrs)
7964 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7965 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7966 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7967 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7968 + llvm::capacity_in_bytes(OverriddenMethods)
7969 + llvm::capacity_in_bytes(Types)
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007970 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet0d95f0d2011-08-14 14:28:49 +00007971 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00007972}
Ted Kremenekd211cb72011-10-06 05:00:56 +00007973
David Blaikie66cff722012-11-14 01:52:05 +00007974void ASTContext::addUnnamedTag(const TagDecl *Tag) {
7975 // FIXME: This mangling should be applied to function local classes too
7976 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl() ||
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007977 !isa<CXXRecordDecl>(Tag->getParent()) ||
7978 !Tag->isExternallyVisible())
David Blaikie66cff722012-11-14 01:52:05 +00007979 return;
7980
7981 std::pair<llvm::DenseMap<const DeclContext *, unsigned>::iterator, bool> P =
7982 UnnamedMangleContexts.insert(std::make_pair(Tag->getParent(), 0));
7983 UnnamedMangleNumbers.insert(std::make_pair(Tag, P.first->second++));
7984}
7985
7986int ASTContext::getUnnamedTagManglingNumber(const TagDecl *Tag) const {
7987 llvm::DenseMap<const TagDecl *, unsigned>::const_iterator I =
7988 UnnamedMangleNumbers.find(Tag);
7989 return I != UnnamedMangleNumbers.end() ? I->second : -1;
7990}
7991
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00007992unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7993 CXXRecordDecl *Lambda = CallOperator->getParent();
7994 return LambdaMangleContexts[Lambda->getDeclContext()]
7995 .getManglingNumber(CallOperator);
7996}
7997
7998
Ted Kremenekd211cb72011-10-06 05:00:56 +00007999void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8000 ParamIndices[D] = index;
8001}
8002
8003unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8004 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8005 assert(I != ParamIndices.end() &&
8006 "ParmIndices lacks entry set by ParmVarDecl");
8007 return I->second;
8008}