blob: f5e4b42d2769ee5e9dea2c06b81beb727fbcf42a [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
Richard Smith0a74a4c2013-05-21 05:24:00 +0000409comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
410 const RawComment *RC = getRawCommentForDeclNoCache(D);
411 return RC ? RC->parse(*this, 0, D) : 0;
412}
413
Dmitri Gribenko19523542012-09-29 11:40:46 +0000414comments::FullComment *ASTContext::getCommentForDecl(
415 const Decl *D,
416 const Preprocessor *PP) const {
Fariborz Jahanianfbff0c42013-05-13 17:27:00 +0000417 if (D->isInvalidDecl())
418 return NULL;
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000419 D = adjustDeclToTemplate(D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000420
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000421 const Decl *Canonical = D->getCanonicalDecl();
422 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
423 ParsedComments.find(Canonical);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000424
425 if (Pos != ParsedComments.end()) {
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000426 if (Canonical != D) {
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000427 comments::FullComment *FC = Pos->second;
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000428 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000429 return CFC;
430 }
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000431 return Pos->second;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000432 }
433
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000434 const Decl *OriginalDecl;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000435
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000436 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000437 if (!RC) {
438 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko1e905da2012-11-03 14:24:57 +0000439 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanianc328d9c2013-01-12 00:28:34 +0000440 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000441 if (OMD && OMD->isPropertyAccessor())
442 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
443 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
444 return cloneFullComment(FC, D);
Fariborz Jahanianc328d9c2013-01-12 00:28:34 +0000445 if (OMD)
Dmitri Gribenko1e905da2012-11-03 14:24:57 +0000446 addRedeclaredMethods(OMD, Overridden);
447 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000448 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
449 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
450 return cloneFullComment(FC, D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000451 }
Fariborz Jahanian4857fdc2013-05-02 15:44:16 +0000452 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +0000453 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000454 // does not have one of its own.
Fariborz Jahanian41170b52013-01-25 22:48:32 +0000455 QualType QT = TD->getUnderlyingType();
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +0000456 if (const TagType *TT = QT->getAs<TagType>())
457 if (const Decl *TD = TT->getDecl())
458 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000459 return cloneFullComment(FC, D);
Fariborz Jahanian41170b52013-01-25 22:48:32 +0000460 }
Fariborz Jahanian622bb4a2013-04-26 20:55:38 +0000461 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
462 while (IC->getSuperClass()) {
463 IC = IC->getSuperClass();
464 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
465 return cloneFullComment(FC, D);
466 }
467 }
468 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
469 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
470 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
471 return cloneFullComment(FC, D);
472 }
473 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
474 if (!(RD = RD->getDefinition()))
475 return NULL;
476 // Check non-virtual bases.
477 for (CXXRecordDecl::base_class_const_iterator I =
478 RD->bases_begin(), E = RD->bases_end(); I != E; ++I) {
Fariborz Jahanian91efca02013-04-26 23:34:36 +0000479 if (I->isVirtual() || (I->getAccessSpecifier() != AS_public))
Fariborz Jahanian622bb4a2013-04-26 20:55:38 +0000480 continue;
481 QualType Ty = I->getType();
482 if (Ty.isNull())
483 continue;
484 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
485 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
486 continue;
487
488 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
489 return cloneFullComment(FC, D);
490 }
491 }
492 // Check virtual bases.
493 for (CXXRecordDecl::base_class_const_iterator I =
494 RD->vbases_begin(), E = RD->vbases_end(); I != E; ++I) {
Fariborz Jahanian91efca02013-04-26 23:34:36 +0000495 if (I->getAccessSpecifier() != AS_public)
496 continue;
Fariborz Jahanian622bb4a2013-04-26 20:55:38 +0000497 QualType Ty = I->getType();
498 if (Ty.isNull())
499 continue;
500 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
501 if (!(VirtualBase= VirtualBase->getDefinition()))
502 continue;
503 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
504 return cloneFullComment(FC, D);
505 }
506 }
507 }
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000508 return NULL;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000509 }
510
Dmitri Gribenko4b41c652012-08-22 18:12:19 +0000511 // If the RawComment was attached to other redeclaration of this Decl, we
512 // should parse the comment in context of that other Decl. This is important
513 // because comments can contain references to parameter names which can be
514 // different across redeclarations.
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000515 if (D != OriginalDecl)
Dmitri Gribenko19523542012-09-29 11:40:46 +0000516 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000517
Dmitri Gribenko19523542012-09-29 11:40:46 +0000518 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000519 ParsedComments[Canonical] = FC;
520 return FC;
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000521}
522
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000523void
524ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
525 TemplateTemplateParmDecl *Parm) {
526 ID.AddInteger(Parm->getDepth());
527 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +0000528 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000529
530 TemplateParameterList *Params = Parm->getTemplateParameters();
531 ID.AddInteger(Params->size());
532 for (TemplateParameterList::const_iterator P = Params->begin(),
533 PEnd = Params->end();
534 P != PEnd; ++P) {
535 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
536 ID.AddInteger(0);
537 ID.AddBoolean(TTP->isParameterPack());
538 continue;
539 }
540
541 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
542 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000543 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000544 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000545 if (NTTP->isExpandedParameterPack()) {
546 ID.AddBoolean(true);
547 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000548 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
549 QualType T = NTTP->getExpansionType(I);
550 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
551 }
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000552 } else
553 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000554 continue;
555 }
556
557 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
558 ID.AddInteger(2);
559 Profile(ID, TTP);
560 }
561}
562
563TemplateTemplateParmDecl *
564ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +0000565 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000566 // Check if we already have a canonical template template parameter.
567 llvm::FoldingSetNodeID ID;
568 CanonicalTemplateTemplateParm::Profile(ID, TTP);
569 void *InsertPos = 0;
570 CanonicalTemplateTemplateParm *Canonical
571 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
572 if (Canonical)
573 return Canonical->getParam();
574
575 // Build a canonical template parameter list.
576 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000577 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000578 CanonParams.reserve(Params->size());
579 for (TemplateParameterList::const_iterator P = Params->begin(),
580 PEnd = Params->end();
581 P != PEnd; ++P) {
582 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
583 CanonParams.push_back(
584 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000585 SourceLocation(),
586 SourceLocation(),
587 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000588 TTP->getIndex(), 0, false,
589 TTP->isParameterPack()));
590 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000591 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
592 QualType T = getCanonicalType(NTTP->getType());
593 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
594 NonTypeTemplateParmDecl *Param;
595 if (NTTP->isExpandedParameterPack()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000596 SmallVector<QualType, 2> ExpandedTypes;
597 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000598 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
599 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
600 ExpandedTInfos.push_back(
601 getTrivialTypeSourceInfo(ExpandedTypes.back()));
602 }
603
604 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000605 SourceLocation(),
606 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000607 NTTP->getDepth(),
608 NTTP->getPosition(), 0,
609 T,
610 TInfo,
611 ExpandedTypes.data(),
612 ExpandedTypes.size(),
613 ExpandedTInfos.data());
614 } else {
615 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000616 SourceLocation(),
617 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000618 NTTP->getDepth(),
619 NTTP->getPosition(), 0,
620 T,
621 NTTP->isParameterPack(),
622 TInfo);
623 }
624 CanonParams.push_back(Param);
625
626 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000627 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
628 cast<TemplateTemplateParmDecl>(*P)));
629 }
630
631 TemplateTemplateParmDecl *CanonTTP
632 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
633 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000634 TTP->getPosition(),
635 TTP->isParameterPack(),
636 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000637 TemplateParameterList::Create(*this, SourceLocation(),
638 SourceLocation(),
639 CanonParams.data(),
640 CanonParams.size(),
641 SourceLocation()));
642
643 // Get the new insert position for the node we care about.
644 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
645 assert(Canonical == 0 && "Shouldn't be in the map!");
646 (void)Canonical;
647
648 // Create the canonical template template parameter entry.
649 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
650 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
651 return CanonTTP;
652}
653
Charles Davis071cc7d2010-08-16 03:33:14 +0000654CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000655 if (!LangOpts.CPlusPlus) return 0;
656
John McCallb8b2c9d2013-01-25 22:30:49 +0000657 switch (T.getCXXABI().getKind()) {
658 case TargetCXXABI::GenericARM:
659 case TargetCXXABI::iOS:
John McCallee79a4c2010-08-21 22:46:04 +0000660 return CreateARMCXXABI(*this);
Tim Northoverc264e162013-01-31 12:13:10 +0000661 case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
John McCallb8b2c9d2013-01-25 22:30:49 +0000662 case TargetCXXABI::GenericItanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000663 return CreateItaniumCXXABI(*this);
John McCallb8b2c9d2013-01-25 22:30:49 +0000664 case TargetCXXABI::Microsoft:
Charles Davis20cf7172010-08-19 02:18:14 +0000665 return CreateMicrosoftCXXABI(*this);
666 }
David Blaikie7530c032012-01-17 06:56:22 +0000667 llvm_unreachable("Invalid CXXABI type!");
Charles Davis071cc7d2010-08-16 03:33:14 +0000668}
669
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000670static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000671 const LangOptions &LOpts) {
672 if (LOpts.FakeAddressSpaceMap) {
673 // The fake address space map must have a distinct entry for each
674 // language-specific address space.
675 static const unsigned FakeAddrSpaceMap[] = {
676 1, // opencl_global
677 2, // opencl_local
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +0000678 3, // opencl_constant
679 4, // cuda_device
680 5, // cuda_constant
681 6 // cuda_shared
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000682 };
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000683 return &FakeAddrSpaceMap;
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000684 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000685 return &T.getAddressSpaceMap();
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000686 }
687}
688
Douglas Gregor3e3cd932011-09-01 20:23:19 +0000689ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000690 const TargetInfo *t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000691 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000692 Builtin::Context &builtins,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000693 unsigned size_reserve,
694 bool DelayInitialization)
695 : FunctionProtoTypes(this_()),
696 TemplateSpecializationTypes(this_()),
697 DependentTemplateSpecializationTypes(this_()),
698 SubstTemplateTemplateParmPacks(this_()),
699 GlobalNestedNameSpecifier(0),
700 Int128Decl(0), UInt128Decl(0),
Meador Ingec5613b22012-06-16 03:34:49 +0000701 BuiltinVaListDecl(0),
Douglas Gregora6ea10e2012-01-17 18:09:05 +0000702 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanian96171302012-08-30 18:49:41 +0000703 BOOLDecl(0),
Douglas Gregore97179c2011-09-08 01:46:34 +0000704 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000705 FILEDecl(0),
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +0000706 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
707 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
708 cudaConfigureCallDecl(0),
Douglas Gregore6649772011-12-03 00:30:27 +0000709 NullTypeSourceInfo(QualType()),
710 FirstLocalImport(), LastLocalImport(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000711 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor30c42402011-09-27 22:38:19 +0000712 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000713 Idents(idents), Selectors(sels),
714 BuiltinInfo(builtins),
715 DeclarationNames(*this),
Douglas Gregor30c42402011-09-27 22:38:19 +0000716 ExternalSource(0), Listener(0),
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000717 Comments(SM), CommentsLoaded(false),
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +0000718 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000719 LastSDM(0, 0),
Fariborz Jahanianf7992132013-01-04 18:45:40 +0000720 UniqueBlockByRefTypeID(0)
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000721{
Mike Stump1eb44332009-09-09 15:08:12 +0000722 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000723 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000724
725 if (!DelayInitialization) {
726 assert(t && "No target supplied for ASTContext initialization");
727 InitBuiltinTypes(*t);
728 }
Daniel Dunbare91593e2008-08-11 04:54:23 +0000729}
730
Reid Spencer5f016e22007-07-11 17:01:13 +0000731ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000732 // Release the DenseMaps associated with DeclContext objects.
733 // FIXME: Is this the ideal solution?
734 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000735
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000736 // Call all of the deallocation functions.
737 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
738 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000739
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000740 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000741 // because they can contain DenseMaps.
742 for (llvm::DenseMap<const ObjCContainerDecl*,
743 const ASTRecordLayout*>::iterator
744 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
745 // Increment in loop to prevent using deallocated memory.
746 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
747 R->Destroy(*this);
748
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000749 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
750 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
751 // Increment in loop to prevent using deallocated memory.
752 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
753 R->Destroy(*this);
754 }
Douglas Gregor63200642010-08-30 16:49:28 +0000755
756 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
757 AEnd = DeclAttrs.end();
758 A != AEnd; ++A)
759 A->second->~AttrVec();
760}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000761
Douglas Gregor00545312010-05-23 18:26:36 +0000762void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
763 Deallocations.push_back(std::make_pair(Callback, Data));
764}
765
Mike Stump1eb44332009-09-09 15:08:12 +0000766void
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000767ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000768 ExternalSource.reset(Source.take());
769}
770
Reid Spencer5f016e22007-07-11 17:01:13 +0000771void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000772 llvm::errs() << "\n*** AST Context Stats:\n";
773 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000774
Douglas Gregordbe833d2009-05-26 14:40:08 +0000775 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000776#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000777#define ABSTRACT_TYPE(Name, Parent)
778#include "clang/AST/TypeNodes.def"
779 0 // Extra
780 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000781
Reid Spencer5f016e22007-07-11 17:01:13 +0000782 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
783 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000784 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000785 }
786
Douglas Gregordbe833d2009-05-26 14:40:08 +0000787 unsigned Idx = 0;
788 unsigned TotalBytes = 0;
789#define TYPE(Name, Parent) \
790 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000791 llvm::errs() << " " << counts[Idx] << " " << #Name \
792 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000793 TotalBytes += counts[Idx] * sizeof(Name##Type); \
794 ++Idx;
795#define ABSTRACT_TYPE(Name, Parent)
796#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000797
Chandler Carruthcd92a652011-07-04 05:32:14 +0000798 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
799
Douglas Gregor4923aa22010-07-02 20:37:36 +0000800 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000801 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
802 << NumImplicitDefaultConstructors
803 << " implicit default constructors created\n";
804 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
805 << NumImplicitCopyConstructors
806 << " implicit copy constructors created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000807 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000808 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
809 << NumImplicitMoveConstructors
810 << " implicit move constructors created\n";
811 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
812 << NumImplicitCopyAssignmentOperators
813 << " implicit copy assignment operators created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000814 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000815 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
816 << NumImplicitMoveAssignmentOperators
817 << " implicit move assignment operators created\n";
818 llvm::errs() << NumImplicitDestructorsDeclared << "/"
819 << NumImplicitDestructors
820 << " implicit destructors created\n";
821
Douglas Gregor2cf26342009-04-09 22:27:44 +0000822 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000823 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000824 ExternalSource->PrintStats();
825 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000826
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000827 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000828}
829
Douglas Gregor772eeae2011-08-12 06:49:56 +0000830TypedefDecl *ASTContext::getInt128Decl() const {
831 if (!Int128Decl) {
832 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
833 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
834 getTranslationUnitDecl(),
835 SourceLocation(),
836 SourceLocation(),
837 &Idents.get("__int128_t"),
838 TInfo);
839 }
840
841 return Int128Decl;
842}
843
844TypedefDecl *ASTContext::getUInt128Decl() const {
845 if (!UInt128Decl) {
846 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
847 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
848 getTranslationUnitDecl(),
849 SourceLocation(),
850 SourceLocation(),
851 &Idents.get("__uint128_t"),
852 TInfo);
853 }
854
855 return UInt128Decl;
856}
Reid Spencer5f016e22007-07-11 17:01:13 +0000857
John McCalle27ec8a2009-10-23 23:03:21 +0000858void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000859 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000860 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000861 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000862}
863
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000864void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
865 assert((!this->Target || this->Target == &Target) &&
866 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000867 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000868
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000869 this->Target = &Target;
870
871 ABI.reset(createCXXABI(Target));
872 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
873
Reid Spencer5f016e22007-07-11 17:01:13 +0000874 // C99 6.2.5p19.
875 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000876
Reid Spencer5f016e22007-07-11 17:01:13 +0000877 // C99 6.2.5p2.
878 InitBuiltinType(BoolTy, BuiltinType::Bool);
879 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000880 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000881 InitBuiltinType(CharTy, BuiltinType::Char_S);
882 else
883 InitBuiltinType(CharTy, BuiltinType::Char_U);
884 // C99 6.2.5p4.
885 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
886 InitBuiltinType(ShortTy, BuiltinType::Short);
887 InitBuiltinType(IntTy, BuiltinType::Int);
888 InitBuiltinType(LongTy, BuiltinType::Long);
889 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000890
Reid Spencer5f016e22007-07-11 17:01:13 +0000891 // C99 6.2.5p6.
892 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
893 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
894 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
895 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
896 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000897
Reid Spencer5f016e22007-07-11 17:01:13 +0000898 // C99 6.2.5p10.
899 InitBuiltinType(FloatTy, BuiltinType::Float);
900 InitBuiltinType(DoubleTy, BuiltinType::Double);
901 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000902
Chris Lattner2df9ced2009-04-30 02:43:43 +0000903 // GNU extension, 128-bit integers.
904 InitBuiltinType(Int128Ty, BuiltinType::Int128);
905 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
906
Hans Wennborg15f92ba2013-05-10 10:08:40 +0000907 // C++ 3.9.1p5
908 if (TargetInfo::isTypeSigned(Target.getWCharType()))
909 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
910 else // -fshort-wchar makes wchar_t be unsigned.
911 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
912 if (LangOpts.CPlusPlus && LangOpts.WChar)
913 WideCharTy = WCharTy;
914 else {
915 // C99 (or C++ using -fno-wchar).
916 WideCharTy = getFromTargetType(Target.getWCharType());
917 }
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000918
James Molloy392da482012-05-04 10:55:22 +0000919 WIntTy = getFromTargetType(Target.getWIntType());
920
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000921 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
922 InitBuiltinType(Char16Ty, BuiltinType::Char16);
923 else // C99
924 Char16Ty = getFromTargetType(Target.getChar16Type());
925
926 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
927 InitBuiltinType(Char32Ty, BuiltinType::Char32);
928 else // C99
929 Char32Ty = getFromTargetType(Target.getChar32Type());
930
Douglas Gregor898574e2008-12-05 23:32:09 +0000931 // Placeholder type for type-dependent expressions whose type is
932 // completely unknown. No code should ever check a type against
933 // DependentTy and users should never see it; however, it is here to
934 // help diagnose failures to properly check for type-dependent
935 // expressions.
936 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000937
John McCall2a984ca2010-10-12 00:20:44 +0000938 // Placeholder type for functions.
939 InitBuiltinType(OverloadTy, BuiltinType::Overload);
940
John McCall864c0412011-04-26 20:42:42 +0000941 // Placeholder type for bound members.
942 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
943
John McCall3c3b7f92011-10-25 17:37:35 +0000944 // Placeholder type for pseudo-objects.
945 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
946
John McCall1de4d4e2011-04-07 08:22:57 +0000947 // "any" type; useful for debugger-like clients.
948 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
949
John McCall0ddaeb92011-10-17 18:09:15 +0000950 // Placeholder type for unbridged ARC casts.
951 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
952
Eli Friedmana6c66ce2012-08-31 00:14:07 +0000953 // Placeholder type for builtin functions.
954 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
955
Reid Spencer5f016e22007-07-11 17:01:13 +0000956 // C99 6.2.5p11.
957 FloatComplexTy = getComplexType(FloatTy);
958 DoubleComplexTy = getComplexType(DoubleTy);
959 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000960
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000961 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000962 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
963 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000964 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeib13621d2012-12-18 14:38:23 +0000965
966 if (LangOpts.OpenCL) {
967 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
968 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
969 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
970 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
971 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
972 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000973
Guy Benyei21f18c42013-02-07 10:55:47 +0000974 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000975 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeib13621d2012-12-18 14:38:23 +0000976 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000977
978 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian93a49942012-04-16 21:03:30 +0000979 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
980 SignedCharTy : BoolTy);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000981
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000982 ObjCConstantStringType = QualType();
Fariborz Jahanianf7992132013-01-04 18:45:40 +0000983
984 ObjCSuperType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000985
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000986 // void * type
987 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000988
989 // nullptr type (C++0x 2.14.7)
990 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000991
992 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
993 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingefb40e3f2012-07-01 15:57:25 +0000994
995 // Builtin type used to help define __builtin_va_list.
996 VaListTagTy = QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000997}
998
David Blaikied6471f72011-09-25 23:23:43 +0000999DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001000 return SourceMgr.getDiagnostics();
1001}
1002
Douglas Gregor63200642010-08-30 16:49:28 +00001003AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1004 AttrVec *&Result = DeclAttrs[D];
1005 if (!Result) {
1006 void *Mem = Allocate(sizeof(AttrVec));
1007 Result = new (Mem) AttrVec;
1008 }
1009
1010 return *Result;
1011}
1012
1013/// \brief Erase the attributes corresponding to the given declaration.
1014void ASTContext::eraseDeclAttrs(const Decl *D) {
1015 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1016 if (Pos != DeclAttrs.end()) {
1017 Pos->second->~AttrVec();
1018 DeclAttrs.erase(Pos);
1019 }
1020}
1021
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001022MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +00001023ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001024 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +00001025 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +00001026 = InstantiatedFromStaticDataMember.find(Var);
1027 if (Pos == InstantiatedFromStaticDataMember.end())
1028 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001029
Douglas Gregor7caa6822009-07-24 20:34:43 +00001030 return Pos->second;
1031}
1032
Mike Stump1eb44332009-09-09 15:08:12 +00001033void
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001034ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +00001035 TemplateSpecializationKind TSK,
1036 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001037 assert(Inst->isStaticDataMember() && "Not a static data member");
1038 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1039 assert(!InstantiatedFromStaticDataMember[Inst] &&
1040 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001041 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +00001042 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +00001043}
1044
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001045FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1046 const FunctionDecl *FD){
1047 assert(FD && "Specialization is 0");
1048 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +00001049 = ClassScopeSpecializationPattern.find(FD);
1050 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001051 return 0;
1052
1053 return Pos->second;
1054}
1055
1056void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1057 FunctionDecl *Pattern) {
1058 assert(FD && "Specialization is 0");
1059 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +00001060 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001061}
1062
John McCall7ba107a2009-11-18 02:36:19 +00001063NamedDecl *
John McCalled976492009-12-04 22:46:56 +00001064ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +00001065 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +00001066 = InstantiatedFromUsingDecl.find(UUD);
1067 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +00001068 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001069
Anders Carlsson0d8df782009-08-29 19:37:28 +00001070 return Pos->second;
1071}
1072
1073void
John McCalled976492009-12-04 22:46:56 +00001074ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1075 assert((isa<UsingDecl>(Pattern) ||
1076 isa<UnresolvedUsingValueDecl>(Pattern) ||
1077 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1078 "pattern decl is not a using decl");
1079 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1080 InstantiatedFromUsingDecl[Inst] = Pattern;
1081}
1082
1083UsingShadowDecl *
1084ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1085 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1086 = InstantiatedFromUsingShadowDecl.find(Inst);
1087 if (Pos == InstantiatedFromUsingShadowDecl.end())
1088 return 0;
1089
1090 return Pos->second;
1091}
1092
1093void
1094ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1095 UsingShadowDecl *Pattern) {
1096 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1097 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00001098}
1099
Anders Carlssond8b285f2009-09-01 04:26:58 +00001100FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1101 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1102 = InstantiatedFromUnnamedFieldDecl.find(Field);
1103 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1104 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001105
Anders Carlssond8b285f2009-09-01 04:26:58 +00001106 return Pos->second;
1107}
1108
1109void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1110 FieldDecl *Tmpl) {
1111 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1112 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1113 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1114 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +00001115
Anders Carlssond8b285f2009-09-01 04:26:58 +00001116 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1117}
1118
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +00001119bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
1120 const FieldDecl *LastFD) const {
1121 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001122 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +00001123}
1124
Fariborz Jahanian340fa242011-05-02 17:20:56 +00001125bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
1126 const FieldDecl *LastFD) const {
1127 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001128 FD->getBitWidthValue(*this) == 0 &&
1129 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +00001130}
1131
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001132bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
1133 const FieldDecl *LastFD) const {
1134 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001135 FD->getBitWidthValue(*this) &&
1136 LastFD->getBitWidthValue(*this));
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001137}
1138
Chad Rosierdd7fddb2011-08-04 23:34:15 +00001139bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001140 const FieldDecl *LastFD) const {
1141 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001142 LastFD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001143}
1144
Chad Rosierdd7fddb2011-08-04 23:34:15 +00001145bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001146 const FieldDecl *LastFD) const {
1147 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001148 FD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001149}
1150
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001151ASTContext::overridden_cxx_method_iterator
1152ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1153 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001154 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001155 if (Pos == OverriddenMethods.end())
1156 return 0;
1157
1158 return Pos->second.begin();
1159}
1160
1161ASTContext::overridden_cxx_method_iterator
1162ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1163 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001164 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001165 if (Pos == OverriddenMethods.end())
1166 return 0;
1167
1168 return Pos->second.end();
1169}
1170
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001171unsigned
1172ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1173 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001174 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001175 if (Pos == OverriddenMethods.end())
1176 return 0;
1177
1178 return Pos->second.size();
1179}
1180
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001181void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1182 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001183 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001184 OverriddenMethods[Method].push_back(Overridden);
1185}
1186
Dmitri Gribenko1e905da2012-11-03 14:24:57 +00001187void ASTContext::getOverriddenMethods(
1188 const NamedDecl *D,
1189 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001190 assert(D);
1191
1192 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis685d1042013-04-17 00:09:03 +00001193 Overridden.append(overridden_methods_begin(CXXMethod),
1194 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001195 return;
1196 }
1197
1198 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1199 if (!Method)
1200 return;
1201
Argyrios Kyrtzidis740ae672012-10-09 18:19:01 +00001202 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1203 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisbc0a2bb2012-10-09 20:08:43 +00001204 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001205}
1206
Douglas Gregore6649772011-12-03 00:30:27 +00001207void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1208 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1209 assert(!Import->isFromASTFile() && "Non-local import declaration");
1210 if (!FirstLocalImport) {
1211 FirstLocalImport = Import;
1212 LastLocalImport = Import;
1213 return;
1214 }
1215
1216 LastLocalImport->NextLocalImport = Import;
1217 LastLocalImport = Import;
1218}
1219
Chris Lattner464175b2007-07-18 17:52:12 +00001220//===----------------------------------------------------------------------===//
1221// Type Sizing and Analysis
1222//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +00001223
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001224/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1225/// scalar floating point type.
1226const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +00001227 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001228 assert(BT && "Not a floating point type!");
1229 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001230 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001231 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001232 case BuiltinType::Float: return Target->getFloatFormat();
1233 case BuiltinType::Double: return Target->getDoubleFormat();
1234 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001235 }
1236}
1237
Ken Dyck8b752f12010-01-27 17:10:57 +00001238/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +00001239/// specified decl. Note that bitfields do not have a valid alignment, so
1240/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +00001241/// If @p RefAsPointee, references are treated like their underlying type
1242/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +00001243CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001244 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +00001245
John McCall4081a5c2010-10-08 18:24:19 +00001246 bool UseAlignAttrOnly = false;
1247 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1248 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +00001249
John McCall4081a5c2010-10-08 18:24:19 +00001250 // __attribute__((aligned)) can increase or decrease alignment
1251 // *except* on a struct or struct member, where it only increases
1252 // alignment unless 'packed' is also specified.
1253 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +00001254 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +00001255 // ignore that possibility; Sema should diagnose it.
1256 if (isa<FieldDecl>(D)) {
1257 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1258 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1259 } else {
1260 UseAlignAttrOnly = true;
1261 }
1262 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +00001263 else if (isa<FieldDecl>(D))
1264 UseAlignAttrOnly =
1265 D->hasAttr<PackedAttr>() ||
1266 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +00001267
John McCallba4f5d52011-01-20 07:57:12 +00001268 // If we're using the align attribute only, just ignore everything
1269 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +00001270 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +00001271 // do nothing
1272
John McCall4081a5c2010-10-08 18:24:19 +00001273 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001274 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001275 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001276 if (RefAsPointee)
1277 T = RT->getPointeeType();
1278 else
1279 T = getPointerType(RT->getPointeeType());
1280 }
1281 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +00001282 // Adjust alignments of declarations with array type by the
1283 // large-array alignment on the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001284 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +00001285 const ArrayType *arrayType;
1286 if (MinWidth && (arrayType = getAsArrayType(T))) {
1287 if (isa<VariableArrayType>(arrayType))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001288 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall3b657512011-01-19 10:06:00 +00001289 else if (isa<ConstantArrayType>(arrayType) &&
1290 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001291 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +00001292
John McCall3b657512011-01-19 10:06:00 +00001293 // Walk through any array types while we're at it.
1294 T = getBaseElementType(arrayType);
1295 }
Chad Rosier9f1210c2011-07-26 07:03:04 +00001296 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigand6b203512013-05-06 16:23:57 +00001297 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1298 if (VD->hasGlobalStorage())
1299 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1300 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001301 }
John McCallba4f5d52011-01-20 07:57:12 +00001302
1303 // Fields can be subject to extra alignment constraints, like if
1304 // the field is packed, the struct is packed, or the struct has a
1305 // a max-field-alignment constraint (#pragma pack). So calculate
1306 // the actual alignment of the field within the struct, and then
1307 // (as we're expected to) constrain that by the alignment of the type.
1308 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1309 // So calculate the alignment of the field.
1310 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1311
1312 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +00001313 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +00001314
1315 // Use the GCD of that and the offset within the record.
1316 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1317 if (offset > 0) {
1318 // Alignment is always a power of 2, so the GCD will be a power of 2,
1319 // which means we get to do this crazy thing instead of Euclid's.
1320 uint64_t lowBitOfOffset = offset & (~offset + 1);
1321 if (lowBitOfOffset < fieldAlign)
1322 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1323 }
1324
1325 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +00001326 }
Chris Lattneraf707ab2009-01-24 21:53:27 +00001327 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001328
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001329 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001330}
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001331
John McCall929bbfb2012-08-21 04:10:00 +00001332// getTypeInfoDataSizeInChars - Return the size of a type, in
1333// chars. If the type is a record, its data size is returned. This is
1334// the size of the memcpy that's performed when assigning this type
1335// using a trivial copy/move assignment operator.
1336std::pair<CharUnits, CharUnits>
1337ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1338 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1339
1340 // In C++, objects can sometimes be allocated into the tail padding
1341 // of a base-class subobject. We decide whether that's possible
1342 // during class layout, so here we can just trust the layout results.
1343 if (getLangOpts().CPlusPlus) {
1344 if (const RecordType *RT = T->getAs<RecordType>()) {
1345 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1346 sizeAndAlign.first = layout.getDataSize();
1347 }
1348 }
1349
1350 return sizeAndAlign;
1351}
1352
Richard Trieu910f17e2013-05-14 21:59:17 +00001353/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1354/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1355std::pair<CharUnits, CharUnits>
1356static getConstantArrayInfoInChars(const ASTContext &Context,
1357 const ConstantArrayType *CAT) {
1358 std::pair<CharUnits, CharUnits> EltInfo =
1359 Context.getTypeInfoInChars(CAT->getElementType());
1360 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieu1069b732013-05-14 23:41:50 +00001361 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1362 (uint64_t)(-1)/Size) &&
Richard Trieu910f17e2013-05-14 21:59:17 +00001363 "Overflow in array type char size evaluation");
1364 uint64_t Width = EltInfo.first.getQuantity() * Size;
1365 unsigned Align = EltInfo.second.getQuantity();
1366 Width = llvm::RoundUpToAlignment(Width, Align);
1367 return std::make_pair(CharUnits::fromQuantity(Width),
1368 CharUnits::fromQuantity(Align));
1369}
1370
John McCallea1471e2010-05-20 01:18:31 +00001371std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001372ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001373 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1374 return getConstantArrayInfoInChars(*this, CAT);
John McCallea1471e2010-05-20 01:18:31 +00001375 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001376 return std::make_pair(toCharUnitsFromBits(Info.first),
1377 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +00001378}
1379
1380std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001381ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +00001382 return getTypeInfoInChars(T.getTypePtr());
1383}
1384
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001385std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1386 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1387 if (it != MemoizedTypeInfo.end())
1388 return it->second;
1389
1390 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1391 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1392 return Info;
1393}
1394
1395/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1396/// method does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +00001397///
1398/// FIXME: Pointers into different addr spaces could have different sizes and
1399/// alignment requirements: getPointerInfo should take an AddrSpace, this
1400/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001401std::pair<uint64_t, unsigned>
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001402ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +00001403 uint64_t Width=0;
1404 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +00001405 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001406#define TYPE(Class, Base)
1407#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +00001408#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +00001409#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1410#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +00001411 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +00001412
Chris Lattner692233e2007-07-13 22:27:08 +00001413 case Type::FunctionNoProto:
1414 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +00001415 // GCC extension: alignof(function) = 32 bits
1416 Width = 0;
1417 Align = 32;
1418 break;
1419
Douglas Gregor72564e72009-02-26 23:50:07 +00001420 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +00001421 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +00001422 Width = 0;
1423 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1424 break;
1425
Steve Narofffb22d962007-08-30 01:06:46 +00001426 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001427 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001428
Chris Lattner98be4942008-03-05 18:54:05 +00001429 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001430 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001431 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1432 "Overflow in array type bit size evaluation");
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001433 Width = EltInfo.first*Size;
Chris Lattner030d8842007-07-19 22:06:24 +00001434 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +00001435 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +00001436 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +00001437 }
Nate Begeman213541a2008-04-18 23:10:10 +00001438 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +00001439 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001440 const VectorType *VT = cast<VectorType>(T);
1441 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1442 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +00001443 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001444 // If the alignment is not a power of 2, round up to the next power of 2.
1445 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +00001446 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001447 Align = llvm::NextPowerOf2(Align);
1448 Width = llvm::RoundUpToAlignment(Width, Align);
1449 }
Chad Rosierf9e9af72012-07-13 23:57:43 +00001450 // Adjust the alignment based on the target max.
1451 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1452 if (TargetVectorAlign && TargetVectorAlign < Align)
1453 Align = TargetVectorAlign;
Chris Lattner030d8842007-07-19 22:06:24 +00001454 break;
1455 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001456
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001457 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +00001458 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001459 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001460 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +00001461 // GCC extension: alignof(void) = 8 bits.
1462 Width = 0;
1463 Align = 8;
1464 break;
1465
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001466 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001467 Width = Target->getBoolWidth();
1468 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001469 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001470 case BuiltinType::Char_S:
1471 case BuiltinType::Char_U:
1472 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001473 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001474 Width = Target->getCharWidth();
1475 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001476 break;
Chris Lattner3f59c972010-12-25 23:25:43 +00001477 case BuiltinType::WChar_S:
1478 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001479 Width = Target->getWCharWidth();
1480 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001481 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001482 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001483 Width = Target->getChar16Width();
1484 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001485 break;
1486 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001487 Width = Target->getChar32Width();
1488 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001489 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001490 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001491 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001492 Width = Target->getShortWidth();
1493 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001494 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001495 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001496 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001497 Width = Target->getIntWidth();
1498 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001499 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001500 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001501 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001502 Width = Target->getLongWidth();
1503 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001504 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001505 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001506 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001507 Width = Target->getLongLongWidth();
1508 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001509 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +00001510 case BuiltinType::Int128:
1511 case BuiltinType::UInt128:
1512 Width = 128;
1513 Align = 128; // int128_t is 128-bit aligned on all targets.
1514 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001515 case BuiltinType::Half:
1516 Width = Target->getHalfWidth();
1517 Align = Target->getHalfAlign();
1518 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001519 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001520 Width = Target->getFloatWidth();
1521 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001522 break;
1523 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001524 Width = Target->getDoubleWidth();
1525 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001526 break;
1527 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001528 Width = Target->getLongDoubleWidth();
1529 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001530 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001531 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001532 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1533 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +00001534 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001535 case BuiltinType::ObjCId:
1536 case BuiltinType::ObjCClass:
1537 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001538 Width = Target->getPointerWidth(0);
1539 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001540 break;
Guy Benyei21f18c42013-02-07 10:55:47 +00001541 case BuiltinType::OCLSampler:
1542 // Samplers are modeled as integers.
1543 Width = Target->getIntWidth();
1544 Align = Target->getIntAlign();
1545 break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00001546 case BuiltinType::OCLEvent:
Guy Benyeib13621d2012-12-18 14:38:23 +00001547 case BuiltinType::OCLImage1d:
1548 case BuiltinType::OCLImage1dArray:
1549 case BuiltinType::OCLImage1dBuffer:
1550 case BuiltinType::OCLImage2d:
1551 case BuiltinType::OCLImage2dArray:
1552 case BuiltinType::OCLImage3d:
1553 // Currently these types are pointers to opaque types.
1554 Width = Target->getPointerWidth(0);
1555 Align = Target->getPointerAlign(0);
1556 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001557 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +00001558 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001559 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001560 Width = Target->getPointerWidth(0);
1561 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001562 break;
Steve Naroff485eeff2008-09-24 15:05:44 +00001563 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001564 unsigned AS = getTargetAddressSpace(
1565 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001566 Width = Target->getPointerWidth(AS);
1567 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +00001568 break;
1569 }
Sebastian Redl5d484e82009-11-23 17:18:46 +00001570 case Type::LValueReference:
1571 case Type::RValueReference: {
1572 // alignof and sizeof should never enter this code path here, so we go
1573 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001574 unsigned AS = getTargetAddressSpace(
1575 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001576 Width = Target->getPointerWidth(AS);
1577 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +00001578 break;
1579 }
Chris Lattnerf72a4432008-03-08 08:34:58 +00001580 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001581 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001582 Width = Target->getPointerWidth(AS);
1583 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +00001584 break;
1585 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00001586 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +00001587 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Reid Kleckner84e9ab42013-03-28 20:02:56 +00001588 llvm::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001589 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001590 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001591 case Type::Complex: {
1592 // Complex types have the same alignment as their elements, but twice the
1593 // size.
Mike Stump1eb44332009-09-09 15:08:12 +00001594 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +00001595 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001596 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +00001597 Align = EltInfo.second;
1598 break;
1599 }
John McCallc12c5bb2010-05-15 11:32:37 +00001600 case Type::ObjCObject:
1601 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +00001602 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001603 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +00001604 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001605 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001606 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +00001607 break;
1608 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001609 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001610 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001611 const TagType *TT = cast<TagType>(T);
1612
1613 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001614 Width = 8;
1615 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001616 break;
1617 }
Mike Stump1eb44332009-09-09 15:08:12 +00001618
Daniel Dunbar1d751182008-11-08 05:48:37 +00001619 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001620 return getTypeInfo(ET->getDecl()->getIntegerType());
1621
Daniel Dunbar1d751182008-11-08 05:48:37 +00001622 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001623 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001624 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001625 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001626 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001627 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001628
Chris Lattner9fcfe922009-10-22 05:17:15 +00001629 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001630 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1631 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001632
Richard Smith34b41d92011-02-20 03:19:35 +00001633 case Type::Auto: {
1634 const AutoType *A = cast<AutoType>(T);
Richard Smithdc7a4f52013-04-30 13:56:41 +00001635 assert(!A->getDeducedType().isNull() &&
1636 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001637 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001638 }
1639
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001640 case Type::Paren:
1641 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1642
Douglas Gregor18857642009-04-30 17:32:17 +00001643 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001644 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001645 std::pair<uint64_t, unsigned> Info
1646 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001647 // If the typedef has an aligned attribute on it, it overrides any computed
1648 // alignment we have. This violates the GCC documentation (which says that
1649 // attribute(aligned) can only round up) but matches its implementation.
1650 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1651 Align = AttrAlign;
1652 else
1653 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001654 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001655 break;
Chris Lattner71763312008-04-06 22:05:18 +00001656 }
Douglas Gregor18857642009-04-30 17:32:17 +00001657
1658 case Type::TypeOfExpr:
1659 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1660 .getTypePtr());
1661
1662 case Type::TypeOf:
1663 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1664
Anders Carlsson395b4752009-06-24 19:06:50 +00001665 case Type::Decltype:
1666 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1667 .getTypePtr());
1668
Sean Huntca63c202011-05-24 22:41:36 +00001669 case Type::UnaryTransform:
1670 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1671
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001672 case Type::Elaborated:
1673 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001674
John McCall9d156a72011-01-06 01:58:22 +00001675 case Type::Attributed:
1676 return getTypeInfo(
1677 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1678
Richard Smith3e4c6c42011-05-05 21:57:07 +00001679 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00001680 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +00001681 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +00001682 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1683 // A type alias template specialization may refer to a typedef with the
1684 // aligned attribute on it.
1685 if (TST->isTypeAlias())
1686 return getTypeInfo(TST->getAliasedType().getTypePtr());
1687 else
1688 return getTypeInfo(getCanonicalType(T));
1689 }
1690
Eli Friedmanb001de72011-10-06 23:00:33 +00001691 case Type::Atomic: {
John McCall9eda3ab2013-03-07 21:37:17 +00001692 // Start with the base type information.
Eli Friedman2be46072011-10-14 20:59:01 +00001693 std::pair<uint64_t, unsigned> Info
1694 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1695 Width = Info.first;
1696 Align = Info.second;
John McCall9eda3ab2013-03-07 21:37:17 +00001697
1698 // If the size of the type doesn't exceed the platform's max
1699 // atomic promotion width, make the size and alignment more
1700 // favorable to atomic operations:
1701 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1702 // Round the size up to a power of 2.
1703 if (!llvm::isPowerOf2_64(Width))
1704 Width = llvm::NextPowerOf2(Width);
1705
1706 // Set the alignment equal to the size.
Eli Friedman2be46072011-10-14 20:59:01 +00001707 Align = static_cast<unsigned>(Width);
1708 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001709 }
1710
Douglas Gregor18857642009-04-30 17:32:17 +00001711 }
Mike Stump1eb44332009-09-09 15:08:12 +00001712
Eli Friedman2be46072011-10-14 20:59:01 +00001713 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001714 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001715}
1716
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001717/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1718CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1719 return CharUnits::fromQuantity(BitSize / getCharWidth());
1720}
1721
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001722/// toBits - Convert a size in characters to a size in characters.
1723int64_t ASTContext::toBits(CharUnits CharSize) const {
1724 return CharSize.getQuantity() * getCharWidth();
1725}
1726
Ken Dyckbdc601b2009-12-22 14:23:30 +00001727/// getTypeSizeInChars - Return the size of the specified type, in characters.
1728/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001729CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001730 return getTypeInfoInChars(T).first;
Ken Dyckbdc601b2009-12-22 14:23:30 +00001731}
Jay Foad4ba2a172011-01-12 09:06:06 +00001732CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001733 return getTypeInfoInChars(T).first;
Ken Dyckbdc601b2009-12-22 14:23:30 +00001734}
1735
Ken Dyck16e20cc2010-01-26 17:25:18 +00001736/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001737/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001738CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001739 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001740}
Jay Foad4ba2a172011-01-12 09:06:06 +00001741CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001742 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001743}
1744
Chris Lattner34ebde42009-01-27 18:08:34 +00001745/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1746/// type for the current target in bits. This can be different than the ABI
1747/// alignment in cases where it is beneficial for performance to overalign
1748/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001749unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001750 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001751
1752 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001753 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001754 T = CT->getElementType().getTypePtr();
1755 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosiercde7a1d2012-03-21 20:20:47 +00001756 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1757 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman1eed6022009-05-25 21:27:19 +00001758 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1759
Chris Lattner34ebde42009-01-27 18:08:34 +00001760 return ABIAlign;
1761}
1762
Ulrich Weigand6b203512013-05-06 16:23:57 +00001763/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1764/// to a global variable of the specified type.
1765unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1766 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1767}
1768
1769/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1770/// should be given to a global variable of the specified type.
1771CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1772 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1773}
1774
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001775/// DeepCollectObjCIvars -
1776/// This routine first collects all declared, but not synthesized, ivars in
1777/// super class and then collects all ivars, including those synthesized for
1778/// current class. This routine is used for implementation of current class
1779/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001780///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001781void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1782 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001783 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001784 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1785 DeepCollectObjCIvars(SuperClass, false, Ivars);
1786 if (!leafClass) {
1787 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1788 E = OI->ivar_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001789 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001790 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001791 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001792 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001793 Iv= Iv->getNextIvar())
1794 Ivars.push_back(Iv);
1795 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001796}
1797
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001798/// CollectInheritedProtocols - Collect all protocols in current class and
1799/// those inherited by it.
1800void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001801 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001802 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001803 // We can use protocol_iterator here instead of
1804 // all_referenced_protocol_iterator since we are walking all categories.
1805 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1806 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001807 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(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001810 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001811 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001812 CollectInheritedProtocols(*P, Protocols);
1813 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001814 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001815
1816 // Categories of this Interface.
Douglas Gregord3297242013-01-16 23:00:23 +00001817 for (ObjCInterfaceDecl::visible_categories_iterator
1818 Cat = OI->visible_categories_begin(),
1819 CatEnd = OI->visible_categories_end();
1820 Cat != CatEnd; ++Cat) {
1821 CollectInheritedProtocols(*Cat, Protocols);
1822 }
1823
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001824 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1825 while (SD) {
1826 CollectInheritedProtocols(SD, Protocols);
1827 SD = SD->getSuperClass();
1828 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001829 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001830 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001831 PE = OC->protocol_end(); P != PE; ++P) {
1832 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001833 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001834 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1835 PE = Proto->protocol_end(); P != PE; ++P)
1836 CollectInheritedProtocols(*P, Protocols);
1837 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001838 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001839 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1840 PE = OP->protocol_end(); P != PE; ++P) {
1841 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001842 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001843 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1844 PE = Proto->protocol_end(); P != PE; ++P)
1845 CollectInheritedProtocols(*P, Protocols);
1846 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001847 }
1848}
1849
Jay Foad4ba2a172011-01-12 09:06:06 +00001850unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001851 unsigned count = 0;
1852 // Count ivars declared in class extension.
Douglas Gregord3297242013-01-16 23:00:23 +00001853 for (ObjCInterfaceDecl::known_extensions_iterator
1854 Ext = OI->known_extensions_begin(),
1855 ExtEnd = OI->known_extensions_end();
1856 Ext != ExtEnd; ++Ext) {
1857 count += Ext->ivar_size();
1858 }
1859
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001860 // Count ivar defined in this class's implementation. This
1861 // includes synthesized ivars.
1862 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001863 count += ImplDecl->ivar_size();
1864
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001865 return count;
1866}
1867
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +00001868bool ASTContext::isSentinelNullExpr(const Expr *E) {
1869 if (!E)
1870 return false;
1871
1872 // nullptr_t is always treated as null.
1873 if (E->getType()->isNullPtrType()) return true;
1874
1875 if (E->getType()->isAnyPointerType() &&
1876 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1877 Expr::NPC_ValueDependentIsNull))
1878 return true;
1879
1880 // Unfortunately, __null has type 'int'.
1881 if (isa<GNUNullExpr>(E)) return true;
1882
1883 return false;
1884}
1885
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001886/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1887ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1888 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1889 I = ObjCImpls.find(D);
1890 if (I != ObjCImpls.end())
1891 return cast<ObjCImplementationDecl>(I->second);
1892 return 0;
1893}
1894/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1895ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1896 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1897 I = ObjCImpls.find(D);
1898 if (I != ObjCImpls.end())
1899 return cast<ObjCCategoryImplDecl>(I->second);
1900 return 0;
1901}
1902
1903/// \brief Set the implementation of ObjCInterfaceDecl.
1904void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1905 ObjCImplementationDecl *ImplD) {
1906 assert(IFaceD && ImplD && "Passed null params");
1907 ObjCImpls[IFaceD] = ImplD;
1908}
1909/// \brief Set the implementation of ObjCCategoryDecl.
1910void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1911 ObjCCategoryImplDecl *ImplD) {
1912 assert(CatD && ImplD && "Passed null params");
1913 ObjCImpls[CatD] = ImplD;
1914}
1915
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001916const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1917 const NamedDecl *ND) const {
1918 if (const ObjCInterfaceDecl *ID =
1919 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001920 return ID;
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001921 if (const ObjCCategoryDecl *CD =
1922 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001923 return CD->getClassInterface();
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001924 if (const ObjCImplDecl *IMD =
1925 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001926 return IMD->getClassInterface();
1927
1928 return 0;
1929}
1930
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001931/// \brief Get the copy initialization expression of VarDecl,or NULL if
1932/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001933Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001934 assert(VD && "Passed null params");
1935 assert(VD->hasAttr<BlocksAttr>() &&
1936 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001937 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001938 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001939 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1940}
1941
1942/// \brief Set the copy inialization expression of a block var decl.
1943void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1944 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001945 assert(VD->hasAttr<BlocksAttr>() &&
1946 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001947 BlockVarCopyInits[VD] = Init;
1948}
1949
John McCalla93c9342009-12-07 02:54:59 +00001950TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001951 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001952 if (!DataSize)
1953 DataSize = TypeLoc::getFullDataSizeForType(T);
1954 else
1955 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001956 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001957
John McCalla93c9342009-12-07 02:54:59 +00001958 TypeSourceInfo *TInfo =
1959 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1960 new (TInfo) TypeSourceInfo(T);
1961 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001962}
1963
John McCalla93c9342009-12-07 02:54:59 +00001964TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001965 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001966 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001967 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001968 return DI;
1969}
1970
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001971const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001972ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001973 return getObjCLayout(D, 0);
1974}
1975
1976const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001977ASTContext::getASTObjCImplementationLayout(
1978 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001979 return getObjCLayout(D->getClassInterface(), D);
1980}
1981
Chris Lattnera7674d82007-07-13 22:13:22 +00001982//===----------------------------------------------------------------------===//
1983// Type creation/memoization methods
1984//===----------------------------------------------------------------------===//
1985
Jay Foad4ba2a172011-01-12 09:06:06 +00001986QualType
John McCall3b657512011-01-19 10:06:00 +00001987ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1988 unsigned fastQuals = quals.getFastQualifiers();
1989 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001990
1991 // Check if we've already instantiated this type.
1992 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001993 ExtQuals::Profile(ID, baseType, quals);
1994 void *insertPos = 0;
1995 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1996 assert(eq->getQualifiers() == quals);
1997 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001998 }
1999
John McCall3b657512011-01-19 10:06:00 +00002000 // If the base type is not canonical, make the appropriate canonical type.
2001 QualType canon;
2002 if (!baseType->isCanonicalUnqualified()) {
2003 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall200fa532012-02-08 00:46:36 +00002004 canonSplit.Quals.addConsistentQualifiers(quals);
2005 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00002006
2007 // Re-find the insert position.
2008 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2009 }
2010
2011 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2012 ExtQualNodes.InsertNode(eq, insertPos);
2013 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00002014}
2015
Jay Foad4ba2a172011-01-12 09:06:06 +00002016QualType
2017ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002018 QualType CanT = getCanonicalType(T);
2019 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00002020 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00002021
John McCall0953e762009-09-24 19:53:00 +00002022 // If we are composing extended qualifiers together, merge together
2023 // into one ExtQuals node.
2024 QualifierCollector Quals;
2025 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002026
John McCall0953e762009-09-24 19:53:00 +00002027 // If this type already has an address space specified, it cannot get
2028 // another one.
2029 assert(!Quals.hasAddressSpace() &&
2030 "Type cannot be in multiple addr spaces!");
2031 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002032
John McCall0953e762009-09-24 19:53:00 +00002033 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00002034}
2035
Chris Lattnerb7d25532009-02-18 22:53:11 +00002036QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00002037 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002038 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00002039 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002040 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00002041
John McCall7f040a92010-12-24 02:08:15 +00002042 if (const PointerType *ptr = T->getAs<PointerType>()) {
2043 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00002044 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00002045 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2046 return getPointerType(ResultType);
2047 }
2048 }
Mike Stump1eb44332009-09-09 15:08:12 +00002049
John McCall0953e762009-09-24 19:53:00 +00002050 // If we are composing extended qualifiers together, merge together
2051 // into one ExtQuals node.
2052 QualifierCollector Quals;
2053 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002054
John McCall0953e762009-09-24 19:53:00 +00002055 // If this type already has an ObjCGC specified, it cannot get
2056 // another one.
2057 assert(!Quals.hasObjCGCAttr() &&
2058 "Type cannot have multiple ObjCGCs!");
2059 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00002060
John McCall0953e762009-09-24 19:53:00 +00002061 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002062}
Chris Lattnera7674d82007-07-13 22:13:22 +00002063
John McCalle6a365d2010-12-19 02:44:49 +00002064const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2065 FunctionType::ExtInfo Info) {
2066 if (T->getExtInfo() == Info)
2067 return T;
2068
2069 QualType Result;
2070 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2071 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
2072 } else {
2073 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2074 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2075 EPI.ExtInfo = Info;
Jordan Rosebea522f2013-03-08 21:51:21 +00002076 Result = getFunctionType(FPT->getResultType(),
2077 ArrayRef<QualType>(FPT->arg_type_begin(),
2078 FPT->getNumArgs()),
2079 EPI);
John McCalle6a365d2010-12-19 02:44:49 +00002080 }
2081
2082 return cast<FunctionType>(Result.getTypePtr());
2083}
2084
Richard Smith60e141e2013-05-04 07:00:32 +00002085void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2086 QualType ResultType) {
Richard Smith9dadfab2013-05-11 05:45:24 +00002087 FD = FD->getMostRecentDecl();
2088 while (true) {
Richard Smith60e141e2013-05-04 07:00:32 +00002089 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2090 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2091 FD->setType(getFunctionType(ResultType, FPT->getArgTypes(), EPI));
Richard Smith9dadfab2013-05-11 05:45:24 +00002092 if (FunctionDecl *Next = FD->getPreviousDecl())
2093 FD = Next;
2094 else
2095 break;
Richard Smith60e141e2013-05-04 07:00:32 +00002096 }
Richard Smith9dadfab2013-05-11 05:45:24 +00002097 if (ASTMutationListener *L = getASTMutationListener())
2098 L->DeducedReturnType(FD, ResultType);
Richard Smith60e141e2013-05-04 07:00:32 +00002099}
2100
Reid Spencer5f016e22007-07-11 17:01:13 +00002101/// getComplexType - Return the uniqued reference to the type for a complex
2102/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002103QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002104 // Unique pointers, to guarantee there is only one pointer of a particular
2105 // structure.
2106 llvm::FoldingSetNodeID ID;
2107 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002108
Reid Spencer5f016e22007-07-11 17:01:13 +00002109 void *InsertPos = 0;
2110 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2111 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002112
Reid Spencer5f016e22007-07-11 17:01:13 +00002113 // If the pointee type isn't canonical, this won't be a canonical type either,
2114 // so fill in the canonical type field.
2115 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002116 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002117 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002118
Reid Spencer5f016e22007-07-11 17:01:13 +00002119 // Get the new insert position for the node we care about.
2120 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002121 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002122 }
John McCall6b304a02009-09-24 23:30:46 +00002123 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002124 Types.push_back(New);
2125 ComplexTypes.InsertNode(New, InsertPos);
2126 return QualType(New, 0);
2127}
2128
Reid Spencer5f016e22007-07-11 17:01:13 +00002129/// getPointerType - Return the uniqued reference to the type for a pointer to
2130/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002131QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002132 // Unique pointers, to guarantee there is only one pointer of a particular
2133 // structure.
2134 llvm::FoldingSetNodeID ID;
2135 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002136
Reid Spencer5f016e22007-07-11 17:01:13 +00002137 void *InsertPos = 0;
2138 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2139 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002140
Reid Spencer5f016e22007-07-11 17:01:13 +00002141 // If the pointee type isn't canonical, this won't be a canonical type either,
2142 // so fill in the canonical type field.
2143 QualType Canonical;
Bob Wilsonc90cc932013-03-15 17:12:43 +00002144 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002145 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002146
Bob Wilsonc90cc932013-03-15 17:12:43 +00002147 // Get the new insert position for the node we care about.
2148 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2149 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2150 }
John McCall6b304a02009-09-24 23:30:46 +00002151 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002152 Types.push_back(New);
2153 PointerTypes.InsertNode(New, InsertPos);
2154 return QualType(New, 0);
2155}
2156
Mike Stump1eb44332009-09-09 15:08:12 +00002157/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00002158/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00002159QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00002160 assert(T->isFunctionType() && "block of function types only");
2161 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00002162 // structure.
2163 llvm::FoldingSetNodeID ID;
2164 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002165
Steve Naroff5618bd42008-08-27 16:04:49 +00002166 void *InsertPos = 0;
2167 if (BlockPointerType *PT =
2168 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2169 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002170
2171 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00002172 // type either so fill in the canonical type field.
2173 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002174 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00002175 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002176
Steve Naroff5618bd42008-08-27 16:04:49 +00002177 // Get the new insert position for the node we care about.
2178 BlockPointerType *NewIP =
2179 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002180 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00002181 }
John McCall6b304a02009-09-24 23:30:46 +00002182 BlockPointerType *New
2183 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00002184 Types.push_back(New);
2185 BlockPointerTypes.InsertNode(New, InsertPos);
2186 return QualType(New, 0);
2187}
2188
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002189/// getLValueReferenceType - Return the uniqued reference to the type for an
2190/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002191QualType
2192ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00002193 assert(getCanonicalType(T) != OverloadTy &&
2194 "Unresolved overloaded function type");
2195
Reid Spencer5f016e22007-07-11 17:01:13 +00002196 // Unique pointers, to guarantee there is only one pointer of a particular
2197 // structure.
2198 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002199 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002200
2201 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002202 if (LValueReferenceType *RT =
2203 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002204 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002205
John McCall54e14c42009-10-22 22:37:11 +00002206 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2207
Reid Spencer5f016e22007-07-11 17:01:13 +00002208 // If the referencee type isn't canonical, this won't be a canonical type
2209 // either, so fill in the canonical type field.
2210 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002211 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2212 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2213 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002214
Reid Spencer5f016e22007-07-11 17:01:13 +00002215 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002216 LValueReferenceType *NewIP =
2217 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002218 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002219 }
2220
John McCall6b304a02009-09-24 23:30:46 +00002221 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00002222 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2223 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002224 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002225 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00002226
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002227 return QualType(New, 0);
2228}
2229
2230/// getRValueReferenceType - Return the uniqued reference to the type for an
2231/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002232QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002233 // Unique pointers, to guarantee there is only one pointer of a particular
2234 // structure.
2235 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002236 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002237
2238 void *InsertPos = 0;
2239 if (RValueReferenceType *RT =
2240 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2241 return QualType(RT, 0);
2242
John McCall54e14c42009-10-22 22:37:11 +00002243 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2244
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002245 // If the referencee type isn't canonical, this won't be a canonical type
2246 // either, so fill in the canonical type field.
2247 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002248 if (InnerRef || !T.isCanonical()) {
2249 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2250 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002251
2252 // Get the new insert position for the node we care about.
2253 RValueReferenceType *NewIP =
2254 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002255 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002256 }
2257
John McCall6b304a02009-09-24 23:30:46 +00002258 RValueReferenceType *New
2259 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002260 Types.push_back(New);
2261 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002262 return QualType(New, 0);
2263}
2264
Sebastian Redlf30208a2009-01-24 21:16:55 +00002265/// getMemberPointerType - Return the uniqued reference to the type for a
2266/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00002267QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002268 // Unique pointers, to guarantee there is only one pointer of a particular
2269 // structure.
2270 llvm::FoldingSetNodeID ID;
2271 MemberPointerType::Profile(ID, T, Cls);
2272
2273 void *InsertPos = 0;
2274 if (MemberPointerType *PT =
2275 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2276 return QualType(PT, 0);
2277
2278 // If the pointee or class type isn't canonical, this won't be a canonical
2279 // type either, so fill in the canonical type field.
2280 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00002281 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002282 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2283
2284 // Get the new insert position for the node we care about.
2285 MemberPointerType *NewIP =
2286 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002287 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00002288 }
John McCall6b304a02009-09-24 23:30:46 +00002289 MemberPointerType *New
2290 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002291 Types.push_back(New);
2292 MemberPointerTypes.InsertNode(New, InsertPos);
2293 return QualType(New, 0);
2294}
2295
Mike Stump1eb44332009-09-09 15:08:12 +00002296/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00002297/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002298QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00002299 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00002300 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002301 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00002302 assert((EltTy->isDependentType() ||
2303 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00002304 "Constant array of VLAs is illegal!");
2305
Chris Lattner38aeec72009-05-13 04:12:56 +00002306 // Convert the array size into a canonical width matching the pointer size for
2307 // the target.
2308 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002309 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002310 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00002311
Reid Spencer5f016e22007-07-11 17:01:13 +00002312 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002313 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00002314
Reid Spencer5f016e22007-07-11 17:01:13 +00002315 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002316 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002317 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002318 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002319
John McCall3b657512011-01-19 10:06:00 +00002320 // If the element type isn't canonical or has qualifiers, this won't
2321 // be a canonical type either, so fill in the canonical type field.
2322 QualType Canon;
2323 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2324 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002325 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002326 ASM, IndexTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002327 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00002328
Reid Spencer5f016e22007-07-11 17:01:13 +00002329 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00002330 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002331 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002332 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002333 }
Mike Stump1eb44332009-09-09 15:08:12 +00002334
John McCall6b304a02009-09-24 23:30:46 +00002335 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002336 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002337 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002338 Types.push_back(New);
2339 return QualType(New, 0);
2340}
2341
John McCallce889032011-01-18 08:40:38 +00002342/// getVariableArrayDecayedType - Turns the given type, which may be
2343/// variably-modified, into the corresponding type with all the known
2344/// sizes replaced with [*].
2345QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2346 // Vastly most common case.
2347 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002348
John McCallce889032011-01-18 08:40:38 +00002349 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002350
John McCallce889032011-01-18 08:40:38 +00002351 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00002352 const Type *ty = split.Ty;
John McCallce889032011-01-18 08:40:38 +00002353 switch (ty->getTypeClass()) {
2354#define TYPE(Class, Base)
2355#define ABSTRACT_TYPE(Class, Base)
2356#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2357#include "clang/AST/TypeNodes.def"
2358 llvm_unreachable("didn't desugar past all non-canonical types?");
2359
2360 // These types should never be variably-modified.
2361 case Type::Builtin:
2362 case Type::Complex:
2363 case Type::Vector:
2364 case Type::ExtVector:
2365 case Type::DependentSizedExtVector:
2366 case Type::ObjCObject:
2367 case Type::ObjCInterface:
2368 case Type::ObjCObjectPointer:
2369 case Type::Record:
2370 case Type::Enum:
2371 case Type::UnresolvedUsing:
2372 case Type::TypeOfExpr:
2373 case Type::TypeOf:
2374 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00002375 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00002376 case Type::DependentName:
2377 case Type::InjectedClassName:
2378 case Type::TemplateSpecialization:
2379 case Type::DependentTemplateSpecialization:
2380 case Type::TemplateTypeParm:
2381 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00002382 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00002383 case Type::PackExpansion:
2384 llvm_unreachable("type should never be variably-modified");
2385
2386 // These types can be variably-modified but should never need to
2387 // further decay.
2388 case Type::FunctionNoProto:
2389 case Type::FunctionProto:
2390 case Type::BlockPointer:
2391 case Type::MemberPointer:
2392 return type;
2393
2394 // These types can be variably-modified. All these modifications
2395 // preserve structure except as noted by comments.
2396 // TODO: if we ever care about optimizing VLAs, there are no-op
2397 // optimizations available here.
2398 case Type::Pointer:
2399 result = getPointerType(getVariableArrayDecayedType(
2400 cast<PointerType>(ty)->getPointeeType()));
2401 break;
2402
2403 case Type::LValueReference: {
2404 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2405 result = getLValueReferenceType(
2406 getVariableArrayDecayedType(lv->getPointeeType()),
2407 lv->isSpelledAsLValue());
2408 break;
2409 }
2410
2411 case Type::RValueReference: {
2412 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2413 result = getRValueReferenceType(
2414 getVariableArrayDecayedType(lv->getPointeeType()));
2415 break;
2416 }
2417
Eli Friedmanb001de72011-10-06 23:00:33 +00002418 case Type::Atomic: {
2419 const AtomicType *at = cast<AtomicType>(ty);
2420 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2421 break;
2422 }
2423
John McCallce889032011-01-18 08:40:38 +00002424 case Type::ConstantArray: {
2425 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2426 result = getConstantArrayType(
2427 getVariableArrayDecayedType(cat->getElementType()),
2428 cat->getSize(),
2429 cat->getSizeModifier(),
2430 cat->getIndexTypeCVRQualifiers());
2431 break;
2432 }
2433
2434 case Type::DependentSizedArray: {
2435 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2436 result = getDependentSizedArrayType(
2437 getVariableArrayDecayedType(dat->getElementType()),
2438 dat->getSizeExpr(),
2439 dat->getSizeModifier(),
2440 dat->getIndexTypeCVRQualifiers(),
2441 dat->getBracketsRange());
2442 break;
2443 }
2444
2445 // Turn incomplete types into [*] types.
2446 case Type::IncompleteArray: {
2447 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2448 result = getVariableArrayType(
2449 getVariableArrayDecayedType(iat->getElementType()),
2450 /*size*/ 0,
2451 ArrayType::Normal,
2452 iat->getIndexTypeCVRQualifiers(),
2453 SourceRange());
2454 break;
2455 }
2456
2457 // Turn VLA types into [*] types.
2458 case Type::VariableArray: {
2459 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2460 result = getVariableArrayType(
2461 getVariableArrayDecayedType(vat->getElementType()),
2462 /*size*/ 0,
2463 ArrayType::Star,
2464 vat->getIndexTypeCVRQualifiers(),
2465 vat->getBracketsRange());
2466 break;
2467 }
2468 }
2469
2470 // Apply the top-level qualifiers from the original.
John McCall200fa532012-02-08 00:46:36 +00002471 return getQualifiedType(result, split.Quals);
John McCallce889032011-01-18 08:40:38 +00002472}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002473
Steve Naroffbdbf7b02007-08-30 18:14:25 +00002474/// getVariableArrayType - Returns a non-unique reference to the type for a
2475/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002476QualType ASTContext::getVariableArrayType(QualType EltTy,
2477 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00002478 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002479 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00002480 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002481 // Since we don't unique expressions, it isn't possible to unique VLA's
2482 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00002483 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00002484
John McCall3b657512011-01-19 10:06:00 +00002485 // Be sure to pull qualifiers off the element type.
2486 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2487 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002488 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002489 IndexTypeQuals, Brackets);
John McCall200fa532012-02-08 00:46:36 +00002490 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor715e9c82010-05-23 16:10:32 +00002491 }
2492
John McCall6b304a02009-09-24 23:30:46 +00002493 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002494 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002495
2496 VariableArrayTypes.push_back(New);
2497 Types.push_back(New);
2498 return QualType(New, 0);
2499}
2500
Douglas Gregor898574e2008-12-05 23:32:09 +00002501/// getDependentSizedArrayType - Returns a non-unique reference to
2502/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00002503/// type.
John McCall3b657512011-01-19 10:06:00 +00002504QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2505 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00002506 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002507 unsigned elementTypeQuals,
2508 SourceRange brackets) const {
2509 assert((!numElements || numElements->isTypeDependent() ||
2510 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00002511 "Size must be type- or value-dependent!");
2512
John McCall3b657512011-01-19 10:06:00 +00002513 // Dependently-sized array types that do not have a specified number
2514 // of elements will have their sizes deduced from a dependent
2515 // initializer. We do no canonicalization here at all, which is okay
2516 // because they can't be used in most locations.
2517 if (!numElements) {
2518 DependentSizedArrayType *newType
2519 = new (*this, TypeAlignment)
2520 DependentSizedArrayType(*this, elementType, QualType(),
2521 numElements, ASM, elementTypeQuals,
2522 brackets);
2523 Types.push_back(newType);
2524 return QualType(newType, 0);
2525 }
2526
2527 // Otherwise, we actually build a new type every time, but we
2528 // also build a canonical type.
2529
2530 SplitQualType canonElementType = getCanonicalType(elementType).split();
2531
2532 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00002533 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002534 DependentSizedArrayType::Profile(ID, *this,
John McCall200fa532012-02-08 00:46:36 +00002535 QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002536 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002537
John McCall3b657512011-01-19 10:06:00 +00002538 // Look for an existing type with these properties.
2539 DependentSizedArrayType *canonTy =
2540 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002541
John McCall3b657512011-01-19 10:06:00 +00002542 // If we don't have one, build one.
2543 if (!canonTy) {
2544 canonTy = new (*this, TypeAlignment)
John McCall200fa532012-02-08 00:46:36 +00002545 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002546 QualType(), numElements, ASM, elementTypeQuals,
2547 brackets);
2548 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2549 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002550 }
2551
John McCall3b657512011-01-19 10:06:00 +00002552 // Apply qualifiers from the element type to the array.
2553 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall200fa532012-02-08 00:46:36 +00002554 canonElementType.Quals);
Mike Stump1eb44332009-09-09 15:08:12 +00002555
John McCall3b657512011-01-19 10:06:00 +00002556 // If we didn't need extra canonicalization for the element type,
2557 // then just use that as our result.
John McCall200fa532012-02-08 00:46:36 +00002558 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall3b657512011-01-19 10:06:00 +00002559 return canon;
2560
2561 // Otherwise, we need to build a type which follows the spelling
2562 // of the element type.
2563 DependentSizedArrayType *sugaredType
2564 = new (*this, TypeAlignment)
2565 DependentSizedArrayType(*this, elementType, canon, numElements,
2566 ASM, elementTypeQuals, brackets);
2567 Types.push_back(sugaredType);
2568 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00002569}
2570
John McCall3b657512011-01-19 10:06:00 +00002571QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00002572 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002573 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002574 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002575 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002576
John McCall3b657512011-01-19 10:06:00 +00002577 void *insertPos = 0;
2578 if (IncompleteArrayType *iat =
2579 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2580 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002581
2582 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00002583 // either, so fill in the canonical type field. We also have to pull
2584 // qualifiers off the element type.
2585 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00002586
John McCall3b657512011-01-19 10:06:00 +00002587 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2588 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall200fa532012-02-08 00:46:36 +00002589 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002590 ASM, elementTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002591 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002592
2593 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00002594 IncompleteArrayType *existing =
2595 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2596 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00002597 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00002598
John McCall3b657512011-01-19 10:06:00 +00002599 IncompleteArrayType *newType = new (*this, TypeAlignment)
2600 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002601
John McCall3b657512011-01-19 10:06:00 +00002602 IncompleteArrayTypes.InsertNode(newType, insertPos);
2603 Types.push_back(newType);
2604 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00002605}
2606
Steve Naroff73322922007-07-18 18:00:27 +00002607/// getVectorType - Return the unique reference to a vector type of
2608/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00002609QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00002610 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00002611 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00002612
Reid Spencer5f016e22007-07-11 17:01:13 +00002613 // Check if we've already instantiated a vector of this type.
2614 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00002615 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00002616
Reid Spencer5f016e22007-07-11 17:01:13 +00002617 void *InsertPos = 0;
2618 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2619 return QualType(VTP, 0);
2620
2621 // If the element type isn't canonical, this won't be a canonical type either,
2622 // so fill in the canonical type field.
2623 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00002624 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00002625 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002626
Reid Spencer5f016e22007-07-11 17:01:13 +00002627 // Get the new insert position for the node we care about.
2628 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002629 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002630 }
John McCall6b304a02009-09-24 23:30:46 +00002631 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00002632 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002633 VectorTypes.InsertNode(New, InsertPos);
2634 Types.push_back(New);
2635 return QualType(New, 0);
2636}
2637
Nate Begeman213541a2008-04-18 23:10:10 +00002638/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00002639/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002640QualType
2641ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00002642 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00002643
Steve Naroff73322922007-07-18 18:00:27 +00002644 // Check if we've already instantiated a vector of this type.
2645 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00002646 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002647 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00002648 void *InsertPos = 0;
2649 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2650 return QualType(VTP, 0);
2651
2652 // If the element type isn't canonical, this won't be a canonical type either,
2653 // so fill in the canonical type field.
2654 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002655 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002656 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00002657
Steve Naroff73322922007-07-18 18:00:27 +00002658 // Get the new insert position for the node we care about.
2659 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002660 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00002661 }
John McCall6b304a02009-09-24 23:30:46 +00002662 ExtVectorType *New = new (*this, TypeAlignment)
2663 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00002664 VectorTypes.InsertNode(New, InsertPos);
2665 Types.push_back(New);
2666 return QualType(New, 0);
2667}
2668
Jay Foad4ba2a172011-01-12 09:06:06 +00002669QualType
2670ASTContext::getDependentSizedExtVectorType(QualType vecType,
2671 Expr *SizeExpr,
2672 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002673 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002674 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002675 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002676
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002677 void *InsertPos = 0;
2678 DependentSizedExtVectorType *Canon
2679 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2680 DependentSizedExtVectorType *New;
2681 if (Canon) {
2682 // We already have a canonical version of this array type; use it as
2683 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002684 New = new (*this, TypeAlignment)
2685 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2686 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002687 } else {
2688 QualType CanonVecTy = getCanonicalType(vecType);
2689 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002690 New = new (*this, TypeAlignment)
2691 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2692 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002693
2694 DependentSizedExtVectorType *CanonCheck
2695 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2696 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2697 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002698 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2699 } else {
2700 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2701 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002702 New = new (*this, TypeAlignment)
2703 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002704 }
2705 }
Mike Stump1eb44332009-09-09 15:08:12 +00002706
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002707 Types.push_back(New);
2708 return QualType(New, 0);
2709}
2710
Douglas Gregor72564e72009-02-26 23:50:07 +00002711/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002712///
Jay Foad4ba2a172011-01-12 09:06:06 +00002713QualType
2714ASTContext::getFunctionNoProtoType(QualType ResultTy,
2715 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00002716 const CallingConv DefaultCC = Info.getCC();
2717 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2718 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00002719 // Unique functions, to guarantee there is only one function of a particular
2720 // structure.
2721 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002722 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002723
Reid Spencer5f016e22007-07-11 17:01:13 +00002724 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002725 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002726 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002727 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002728
Reid Spencer5f016e22007-07-11 17:01:13 +00002729 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00002730 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00002731 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00002732 Canonical =
2733 getFunctionNoProtoType(getCanonicalType(ResultTy),
2734 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00002735
Reid Spencer5f016e22007-07-11 17:01:13 +00002736 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002737 FunctionNoProtoType *NewIP =
2738 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002739 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002740 }
Mike Stump1eb44332009-09-09 15:08:12 +00002741
Roman Divackycfe9af22011-03-01 17:40:53 +00002742 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002743 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002744 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002745 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002746 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002747 return QualType(New, 0);
2748}
2749
Douglas Gregor02dd7982013-01-17 23:36:45 +00002750/// \brief Determine whether \p T is canonical as the result type of a function.
2751static bool isCanonicalResultType(QualType T) {
2752 return T.isCanonical() &&
2753 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2754 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2755}
2756
Reid Spencer5f016e22007-07-11 17:01:13 +00002757/// getFunctionType - Return a normal function type with a typed argument
2758/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002759QualType
Jordan Rosebea522f2013-03-08 21:51:21 +00002760ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad4ba2a172011-01-12 09:06:06 +00002761 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rosebea522f2013-03-08 21:51:21 +00002762 size_t NumArgs = ArgArray.size();
2763
Reid Spencer5f016e22007-07-11 17:01:13 +00002764 // Unique functions, to guarantee there is only one function of a particular
2765 // structure.
2766 llvm::FoldingSetNodeID ID;
Jordan Rosebea522f2013-03-08 21:51:21 +00002767 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2768 *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002769
2770 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002771 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002772 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002773 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002774
2775 // Determine whether the type being created is already canonical or not.
Richard Smitheefb3d52012-02-10 09:58:53 +00002776 bool isCanonical =
Douglas Gregor02dd7982013-01-17 23:36:45 +00002777 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smitheefb3d52012-02-10 09:58:53 +00002778 !EPI.HasTrailingReturn;
Reid Spencer5f016e22007-07-11 17:01:13 +00002779 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002780 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002781 isCanonical = false;
2782
Roman Divackycfe9af22011-03-01 17:40:53 +00002783 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2784 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2785 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002786
Reid Spencer5f016e22007-07-11 17:01:13 +00002787 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002788 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002789 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002790 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002791 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002792 CanonicalArgs.reserve(NumArgs);
2793 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002794 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002795
John McCalle23cf432010-12-14 08:05:40 +00002796 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +00002797 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002798 CanonicalEPI.ExceptionSpecType = EST_None;
2799 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002800 CanonicalEPI.ExtInfo
2801 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2802
Douglas Gregor02dd7982013-01-17 23:36:45 +00002803 // Result types do not have ARC lifetime qualifiers.
2804 QualType CanResultTy = getCanonicalType(ResultTy);
2805 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2806 Qualifiers Qs = CanResultTy.getQualifiers();
2807 Qs.removeObjCLifetime();
2808 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2809 }
2810
Jordan Rosebea522f2013-03-08 21:51:21 +00002811 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002812
Reid Spencer5f016e22007-07-11 17:01:13 +00002813 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002814 FunctionProtoType *NewIP =
2815 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002816 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002817 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002818
John McCallf85e1932011-06-15 23:02:42 +00002819 // FunctionProtoType objects are allocated with extra bytes after
2820 // them for three variable size arrays at the end:
2821 // - parameter types
2822 // - exception types
2823 // - consumed-arguments flags
2824 // Instead of the exception types, there could be a noexcept
Richard Smithb9d0b762012-07-27 04:22:15 +00002825 // expression, or information used to resolve the exception
2826 // specification.
John McCalle23cf432010-12-14 08:05:40 +00002827 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002828 NumArgs * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002829 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00002830 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002831 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002832 Size += sizeof(Expr*);
Richard Smithe6975e92012-04-17 00:58:00 +00002833 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smith13bffc52012-04-19 00:08:28 +00002834 Size += 2 * sizeof(FunctionDecl*);
Richard Smithb9d0b762012-07-27 04:22:15 +00002835 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2836 Size += sizeof(FunctionDecl*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002837 }
John McCallf85e1932011-06-15 23:02:42 +00002838 if (EPI.ConsumedArguments)
2839 Size += NumArgs * sizeof(bool);
2840
John McCalle23cf432010-12-14 08:05:40 +00002841 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002842 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2843 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Jordan Rosebea522f2013-03-08 21:51:21 +00002844 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002845 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002846 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002847 return QualType(FTP, 0);
2848}
2849
John McCall3cb0ebd2010-03-10 03:28:59 +00002850#ifndef NDEBUG
2851static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2852 if (!isa<CXXRecordDecl>(D)) return false;
2853 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2854 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2855 return true;
2856 if (RD->getDescribedClassTemplate() &&
2857 !isa<ClassTemplateSpecializationDecl>(RD))
2858 return true;
2859 return false;
2860}
2861#endif
2862
2863/// getInjectedClassNameType - Return the unique reference to the
2864/// injected class name type for the specified templated declaration.
2865QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002866 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002867 assert(NeedsInjectedClassNameType(Decl));
2868 if (Decl->TypeForDecl) {
2869 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregoref96ee02012-01-14 16:38:05 +00002870 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002871 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2872 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2873 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2874 } else {
John McCallf4c73712011-01-19 06:33:43 +00002875 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002876 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002877 Decl->TypeForDecl = newType;
2878 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002879 }
2880 return QualType(Decl->TypeForDecl, 0);
2881}
2882
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002883/// getTypeDeclType - Return the unique reference to the type for the
2884/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002885QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002886 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002887 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002888
Richard Smith162e1c12011-04-15 14:24:37 +00002889 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002890 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002891
John McCallbecb8d52010-03-10 06:48:02 +00002892 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2893 "Template type parameter types are always available.");
2894
John McCall19c85762010-02-16 03:57:14 +00002895 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002896 assert(!Record->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002897 "struct/union has previous declaration");
2898 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002899 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002900 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002901 assert(!Enum->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002902 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002903 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002904 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002905 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002906 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2907 Decl->TypeForDecl = newType;
2908 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002909 } else
John McCallbecb8d52010-03-10 06:48:02 +00002910 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002911
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002912 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002913}
2914
Reid Spencer5f016e22007-07-11 17:01:13 +00002915/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002916/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002917QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002918ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2919 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002920 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002921
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002922 if (Canonical.isNull())
2923 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002924 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002925 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002926 Decl->TypeForDecl = newType;
2927 Types.push_back(newType);
2928 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002929}
2930
Jay Foad4ba2a172011-01-12 09:06:06 +00002931QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002932 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2933
Douglas Gregoref96ee02012-01-14 16:38:05 +00002934 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002935 if (PrevDecl->TypeForDecl)
2936 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2937
John McCallf4c73712011-01-19 06:33:43 +00002938 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2939 Decl->TypeForDecl = newType;
2940 Types.push_back(newType);
2941 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002942}
2943
Jay Foad4ba2a172011-01-12 09:06:06 +00002944QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002945 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2946
Douglas Gregoref96ee02012-01-14 16:38:05 +00002947 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002948 if (PrevDecl->TypeForDecl)
2949 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2950
John McCallf4c73712011-01-19 06:33:43 +00002951 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2952 Decl->TypeForDecl = newType;
2953 Types.push_back(newType);
2954 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002955}
2956
John McCall9d156a72011-01-06 01:58:22 +00002957QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2958 QualType modifiedType,
2959 QualType equivalentType) {
2960 llvm::FoldingSetNodeID id;
2961 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2962
2963 void *insertPos = 0;
2964 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2965 if (type) return QualType(type, 0);
2966
2967 QualType canon = getCanonicalType(equivalentType);
2968 type = new (*this, TypeAlignment)
2969 AttributedType(canon, attrKind, modifiedType, equivalentType);
2970
2971 Types.push_back(type);
2972 AttributedTypes.InsertNode(type, insertPos);
2973
2974 return QualType(type, 0);
2975}
2976
2977
John McCall49a832b2009-10-18 09:09:24 +00002978/// \brief Retrieve a substitution-result type.
2979QualType
2980ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002981 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002982 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002983 && "replacement types must always be canonical");
2984
2985 llvm::FoldingSetNodeID ID;
2986 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2987 void *InsertPos = 0;
2988 SubstTemplateTypeParmType *SubstParm
2989 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2990
2991 if (!SubstParm) {
2992 SubstParm = new (*this, TypeAlignment)
2993 SubstTemplateTypeParmType(Parm, Replacement);
2994 Types.push_back(SubstParm);
2995 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2996 }
2997
2998 return QualType(SubstParm, 0);
2999}
3000
Douglas Gregorc3069d62011-01-14 02:55:32 +00003001/// \brief Retrieve a
3002QualType ASTContext::getSubstTemplateTypeParmPackType(
3003 const TemplateTypeParmType *Parm,
3004 const TemplateArgument &ArgPack) {
3005#ifndef NDEBUG
3006 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
3007 PEnd = ArgPack.pack_end();
3008 P != PEnd; ++P) {
3009 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3010 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
3011 }
3012#endif
3013
3014 llvm::FoldingSetNodeID ID;
3015 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3016 void *InsertPos = 0;
3017 if (SubstTemplateTypeParmPackType *SubstParm
3018 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3019 return QualType(SubstParm, 0);
3020
3021 QualType Canon;
3022 if (!Parm->isCanonicalUnqualified()) {
3023 Canon = getCanonicalType(QualType(Parm, 0));
3024 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3025 ArgPack);
3026 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3027 }
3028
3029 SubstTemplateTypeParmPackType *SubstParm
3030 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3031 ArgPack);
3032 Types.push_back(SubstParm);
3033 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3034 return QualType(SubstParm, 0);
3035}
3036
Douglas Gregorfab9d672009-02-05 23:33:38 +00003037/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00003038/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003039/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00003040QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003041 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003042 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00003043 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003044 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00003045 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003046 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00003047 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3048
3049 if (TypeParm)
3050 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003051
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003052 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003053 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003054 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003055
3056 TemplateTypeParmType *TypeCheck
3057 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3058 assert(!TypeCheck && "Template type parameter canonical type broken");
3059 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003060 } else
John McCall6b304a02009-09-24 23:30:46 +00003061 TypeParm = new (*this, TypeAlignment)
3062 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00003063
3064 Types.push_back(TypeParm);
3065 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3066
3067 return QualType(TypeParm, 0);
3068}
3069
John McCall3cb0ebd2010-03-10 03:28:59 +00003070TypeSourceInfo *
3071ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3072 SourceLocation NameLoc,
3073 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003074 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003075 assert(!Name.getAsDependentTemplateName() &&
3076 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00003077 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00003078
3079 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie39e6ab42013-02-18 22:06:02 +00003080 TemplateSpecializationTypeLoc TL =
3081 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara55d23c92012-02-06 14:41:24 +00003082 TL.setTemplateKeywordLoc(SourceLocation());
John McCall3cb0ebd2010-03-10 03:28:59 +00003083 TL.setTemplateNameLoc(NameLoc);
3084 TL.setLAngleLoc(Args.getLAngleLoc());
3085 TL.setRAngleLoc(Args.getRAngleLoc());
3086 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3087 TL.setArgLocInfo(i, Args[i].getLocInfo());
3088 return DI;
3089}
3090
Mike Stump1eb44332009-09-09 15:08:12 +00003091QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00003092ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00003093 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003094 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003095 assert(!Template.getAsDependentTemplateName() &&
3096 "No dependent template names here!");
3097
John McCalld5532b62009-11-23 01:53:49 +00003098 unsigned NumArgs = Args.size();
3099
Chris Lattner5f9e2722011-07-23 10:55:15 +00003100 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00003101 ArgVec.reserve(NumArgs);
3102 for (unsigned i = 0; i != NumArgs; ++i)
3103 ArgVec.push_back(Args[i].getArgument());
3104
John McCall31f17ec2010-04-27 00:57:59 +00003105 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003106 Underlying);
John McCall833ca992009-10-29 08:12:44 +00003107}
3108
Douglas Gregorb70126a2012-02-03 17:16:23 +00003109#ifndef NDEBUG
3110static bool hasAnyPackExpansions(const TemplateArgument *Args,
3111 unsigned NumArgs) {
3112 for (unsigned I = 0; I != NumArgs; ++I)
3113 if (Args[I].isPackExpansion())
3114 return true;
3115
3116 return true;
3117}
3118#endif
3119
John McCall833ca992009-10-29 08:12:44 +00003120QualType
3121ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003122 const TemplateArgument *Args,
3123 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003124 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003125 assert(!Template.getAsDependentTemplateName() &&
3126 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003127 // Look through qualified template names.
3128 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3129 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003130
Douglas Gregorb70126a2012-02-03 17:16:23 +00003131 bool IsTypeAlias =
Richard Smith3e4c6c42011-05-05 21:57:07 +00003132 Template.getAsTemplateDecl() &&
3133 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00003134 QualType CanonType;
3135 if (!Underlying.isNull())
3136 CanonType = getCanonicalType(Underlying);
3137 else {
Douglas Gregorb70126a2012-02-03 17:16:23 +00003138 // We can get here with an alias template when the specialization contains
3139 // a pack expansion that does not match up with a parameter pack.
3140 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3141 "Caller must compute aliased type");
3142 IsTypeAlias = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00003143 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3144 NumArgs);
3145 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00003146
Douglas Gregor1275ae02009-07-28 23:00:59 +00003147 // Allocate the (non-canonical) template specialization type, but don't
3148 // try to unique it: these types typically have location information that
3149 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00003150 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3151 sizeof(TemplateArgument) * NumArgs +
Douglas Gregorb70126a2012-02-03 17:16:23 +00003152 (IsTypeAlias? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00003153 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00003154 TemplateSpecializationType *Spec
Douglas Gregorb70126a2012-02-03 17:16:23 +00003155 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3156 IsTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00003157
Douglas Gregor55f6b142009-02-09 18:46:07 +00003158 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00003159 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00003160}
3161
Mike Stump1eb44332009-09-09 15:08:12 +00003162QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003163ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3164 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00003165 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003166 assert(!Template.getAsDependentTemplateName() &&
3167 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00003168
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003169 // Look through qualified template names.
3170 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3171 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003172
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003173 // Build the canonical template specialization type.
3174 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003175 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003176 CanonArgs.reserve(NumArgs);
3177 for (unsigned I = 0; I != NumArgs; ++I)
3178 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3179
3180 // Determine whether this canonical template specialization type already
3181 // exists.
3182 llvm::FoldingSetNodeID ID;
3183 TemplateSpecializationType::Profile(ID, CanonTemplate,
3184 CanonArgs.data(), NumArgs, *this);
3185
3186 void *InsertPos = 0;
3187 TemplateSpecializationType *Spec
3188 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3189
3190 if (!Spec) {
3191 // Allocate a new canonical template specialization type.
3192 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3193 sizeof(TemplateArgument) * NumArgs),
3194 TypeAlignment);
3195 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3196 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003197 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003198 Types.push_back(Spec);
3199 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3200 }
3201
3202 assert(Spec->isDependentType() &&
3203 "Non-dependent template-id type must have a canonical type");
3204 return QualType(Spec, 0);
3205}
3206
3207QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003208ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3209 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00003210 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00003211 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003212 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003213
3214 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003215 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003216 if (T)
3217 return QualType(T, 0);
3218
Douglas Gregor789b1f62010-02-04 18:10:26 +00003219 QualType Canon = NamedType;
3220 if (!Canon.isCanonical()) {
3221 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003222 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3223 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00003224 (void)CheckT;
3225 }
3226
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003227 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003228 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003229 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003230 return QualType(T, 0);
3231}
3232
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003233QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00003234ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003235 llvm::FoldingSetNodeID ID;
3236 ParenType::Profile(ID, InnerType);
3237
3238 void *InsertPos = 0;
3239 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3240 if (T)
3241 return QualType(T, 0);
3242
3243 QualType Canon = InnerType;
3244 if (!Canon.isCanonical()) {
3245 Canon = getCanonicalType(InnerType);
3246 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3247 assert(!CheckT && "Paren canonical type broken");
3248 (void)CheckT;
3249 }
3250
3251 T = new (*this) ParenType(InnerType, Canon);
3252 Types.push_back(T);
3253 ParenTypes.InsertNode(T, InsertPos);
3254 return QualType(T, 0);
3255}
3256
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003257QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3258 NestedNameSpecifier *NNS,
3259 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003260 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00003261 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3262
3263 if (Canon.isNull()) {
3264 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003265 ElaboratedTypeKeyword CanonKeyword = Keyword;
3266 if (Keyword == ETK_None)
3267 CanonKeyword = ETK_Typename;
3268
3269 if (CanonNNS != NNS || CanonKeyword != Keyword)
3270 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003271 }
3272
3273 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003274 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003275
3276 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00003277 DependentNameType *T
3278 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00003279 if (T)
3280 return QualType(T, 0);
3281
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003282 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00003283 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00003284 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003285 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00003286}
3287
Mike Stump1eb44332009-09-09 15:08:12 +00003288QualType
John McCall33500952010-06-11 00:33:02 +00003289ASTContext::getDependentTemplateSpecializationType(
3290 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003291 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00003292 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003293 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00003294 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00003295 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00003296 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3297 ArgCopy.push_back(Args[I].getArgument());
3298 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3299 ArgCopy.size(),
3300 ArgCopy.data());
3301}
3302
3303QualType
3304ASTContext::getDependentTemplateSpecializationType(
3305 ElaboratedTypeKeyword Keyword,
3306 NestedNameSpecifier *NNS,
3307 const IdentifierInfo *Name,
3308 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00003309 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003310 assert((!NNS || NNS->isDependent()) &&
3311 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00003312
Douglas Gregor789b1f62010-02-04 18:10:26 +00003313 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00003314 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3315 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003316
3317 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00003318 DependentTemplateSpecializationType *T
3319 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003320 if (T)
3321 return QualType(T, 0);
3322
John McCall33500952010-06-11 00:33:02 +00003323 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003324
John McCall33500952010-06-11 00:33:02 +00003325 ElaboratedTypeKeyword CanonKeyword = Keyword;
3326 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3327
3328 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003329 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00003330 for (unsigned I = 0; I != NumArgs; ++I) {
3331 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3332 if (!CanonArgs[I].structurallyEquals(Args[I]))
3333 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00003334 }
3335
John McCall33500952010-06-11 00:33:02 +00003336 QualType Canon;
3337 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3338 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3339 Name, NumArgs,
3340 CanonArgs.data());
3341
3342 // Find the insert position again.
3343 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3344 }
3345
3346 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3347 sizeof(TemplateArgument) * NumArgs),
3348 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00003349 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00003350 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00003351 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00003352 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003353 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00003354}
3355
Douglas Gregorcded4f62011-01-14 17:04:44 +00003356QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikiedc84cd52013-02-20 22:23:23 +00003357 Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00003358 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00003359 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003360
3361 assert(Pattern->containsUnexpandedParameterPack() &&
3362 "Pack expansions must expand one or more parameter packs");
3363 void *InsertPos = 0;
3364 PackExpansionType *T
3365 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3366 if (T)
3367 return QualType(T, 0);
3368
3369 QualType Canon;
3370 if (!Pattern.isCanonical()) {
Richard Smithd8672ef2012-07-16 00:20:35 +00003371 Canon = getCanonicalType(Pattern);
3372 // The canonical type might not contain an unexpanded parameter pack, if it
3373 // contains an alias template specialization which ignores one of its
3374 // parameters.
3375 if (Canon->containsUnexpandedParameterPack()) {
3376 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003377
Richard Smithd8672ef2012-07-16 00:20:35 +00003378 // Find the insert position again, in case we inserted an element into
3379 // PackExpansionTypes and invalidated our insert position.
3380 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3381 }
Douglas Gregor7536dd52010-12-20 02:24:11 +00003382 }
3383
Douglas Gregorcded4f62011-01-14 17:04:44 +00003384 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003385 Types.push_back(T);
3386 PackExpansionTypes.InsertNode(T, InsertPos);
3387 return QualType(T, 0);
3388}
3389
Chris Lattner88cb27a2008-04-07 04:56:42 +00003390/// CmpProtocolNames - Comparison predicate for sorting protocols
3391/// alphabetically.
3392static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3393 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003394 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00003395}
3396
John McCallc12c5bb2010-05-15 11:32:37 +00003397static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00003398 unsigned NumProtocols) {
3399 if (NumProtocols == 0) return true;
3400
Douglas Gregor61cc2962012-01-02 02:00:30 +00003401 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3402 return false;
3403
John McCall54e14c42009-10-22 22:37:11 +00003404 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregor61cc2962012-01-02 02:00:30 +00003405 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3406 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCall54e14c42009-10-22 22:37:11 +00003407 return false;
3408 return true;
3409}
3410
3411static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00003412 unsigned &NumProtocols) {
3413 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00003414
Chris Lattner88cb27a2008-04-07 04:56:42 +00003415 // Sort protocols, keyed by name.
3416 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3417
Douglas Gregor61cc2962012-01-02 02:00:30 +00003418 // Canonicalize.
3419 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3420 Protocols[I] = Protocols[I]->getCanonicalDecl();
3421
Chris Lattner88cb27a2008-04-07 04:56:42 +00003422 // Remove duplicates.
3423 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3424 NumProtocols = ProtocolsEnd-Protocols;
3425}
3426
John McCallc12c5bb2010-05-15 11:32:37 +00003427QualType ASTContext::getObjCObjectType(QualType BaseType,
3428 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00003429 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003430 // If the base type is an interface and there aren't any protocols
3431 // to add, then the interface type will do just fine.
3432 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3433 return BaseType;
3434
3435 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003436 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00003437 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003438 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00003439 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3440 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003441
John McCallc12c5bb2010-05-15 11:32:37 +00003442 // Build the canonical type, which has the canonical base type and
3443 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00003444 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00003445 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3446 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3447 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003448 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00003449 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003450 unsigned UniqueCount = NumProtocols;
3451
John McCall54e14c42009-10-22 22:37:11 +00003452 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00003453 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3454 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00003455 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00003456 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3457 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003458 }
3459
3460 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00003461 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3462 }
3463
3464 unsigned Size = sizeof(ObjCObjectTypeImpl);
3465 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3466 void *Mem = Allocate(Size, TypeAlignment);
3467 ObjCObjectTypeImpl *T =
3468 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3469
3470 Types.push_back(T);
3471 ObjCObjectTypes.InsertNode(T, InsertPos);
3472 return QualType(T, 0);
3473}
3474
3475/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3476/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003477QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003478 llvm::FoldingSetNodeID ID;
3479 ObjCObjectPointerType::Profile(ID, ObjectT);
3480
3481 void *InsertPos = 0;
3482 if (ObjCObjectPointerType *QT =
3483 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3484 return QualType(QT, 0);
3485
3486 // Find the canonical object type.
3487 QualType Canonical;
3488 if (!ObjectT.isCanonical()) {
3489 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3490
3491 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00003492 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3493 }
3494
Douglas Gregorfd6a0882010-02-08 22:59:26 +00003495 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00003496 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3497 ObjCObjectPointerType *QType =
3498 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00003499
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003500 Types.push_back(QType);
3501 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00003502 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003503}
Chris Lattner88cb27a2008-04-07 04:56:42 +00003504
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003505/// getObjCInterfaceType - Return the unique reference to the type for the
3506/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00003507QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3508 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003509 if (Decl->TypeForDecl)
3510 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003511
Douglas Gregor0af55012011-12-16 03:12:41 +00003512 if (PrevDecl) {
3513 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3514 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3515 return QualType(PrevDecl->TypeForDecl, 0);
3516 }
3517
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00003518 // Prefer the definition, if there is one.
3519 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3520 Decl = Def;
3521
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003522 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3523 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3524 Decl->TypeForDecl = T;
3525 Types.push_back(T);
3526 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00003527}
3528
Douglas Gregor72564e72009-02-26 23:50:07 +00003529/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3530/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00003531/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00003532/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003533/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003534QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003535 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00003536 if (tofExpr->isTypeDependent()) {
3537 llvm::FoldingSetNodeID ID;
3538 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00003539
Douglas Gregorb1975722009-07-30 23:18:24 +00003540 void *InsertPos = 0;
3541 DependentTypeOfExprType *Canon
3542 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3543 if (Canon) {
3544 // We already have a "canonical" version of an identical, dependent
3545 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00003546 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00003547 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003548 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00003549 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003550 Canon
3551 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00003552 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3553 toe = Canon;
3554 }
3555 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003556 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00003557 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00003558 }
Steve Naroff9752f252007-08-01 18:02:17 +00003559 Types.push_back(toe);
3560 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003561}
3562
Steve Naroff9752f252007-08-01 18:02:17 +00003563/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3564/// TypeOfType AST's. The only motivation to unique these nodes would be
3565/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003566/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003567/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003568QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00003569 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00003570 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00003571 Types.push_back(tot);
3572 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003573}
3574
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00003575
Anders Carlsson395b4752009-06-24 19:06:50 +00003576/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3577/// DecltypeType AST's. The only motivation to unique these nodes would be
3578/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003579/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00003580/// on canonical types (which are always unique).
Douglas Gregorf8af9822012-02-12 18:42:33 +00003581QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003582 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00003583
3584 // C++0x [temp.type]p2:
3585 // If an expression e involves a template parameter, decltype(e) denotes a
3586 // unique dependent type. Two such decltype-specifiers refer to the same
3587 // type only if their expressions are equivalent (14.5.6.1).
3588 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003589 llvm::FoldingSetNodeID ID;
3590 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00003591
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003592 void *InsertPos = 0;
3593 DependentDecltypeType *Canon
3594 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3595 if (Canon) {
3596 // We already have a "canonical" version of an equivalent, dependent
3597 // decltype type. Use that as our canonical type.
Richard Smith0d729102012-08-13 20:08:14 +00003598 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003599 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003600 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003601 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003602 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003603 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3604 dt = Canon;
3605 }
3606 } else {
Douglas Gregorf8af9822012-02-12 18:42:33 +00003607 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3608 getCanonicalType(UnderlyingType));
Douglas Gregordd0257c2009-07-08 00:03:05 +00003609 }
Anders Carlsson395b4752009-06-24 19:06:50 +00003610 Types.push_back(dt);
3611 return QualType(dt, 0);
3612}
3613
Sean Huntca63c202011-05-24 22:41:36 +00003614/// getUnaryTransformationType - We don't unique these, since the memory
3615/// savings are minimal and these are rare.
3616QualType ASTContext::getUnaryTransformType(QualType BaseType,
3617 QualType UnderlyingType,
3618 UnaryTransformType::UTTKind Kind)
3619 const {
3620 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00003621 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3622 Kind,
3623 UnderlyingType->isDependentType() ?
Peter Collingbourne12fc4b02012-03-05 16:02:06 +00003624 QualType() : getCanonicalType(UnderlyingType));
Sean Huntca63c202011-05-24 22:41:36 +00003625 Types.push_back(Ty);
3626 return QualType(Ty, 0);
3627}
3628
Richard Smith60e141e2013-05-04 07:00:32 +00003629/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3630/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3631/// canonical deduced-but-dependent 'auto' type.
3632QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Richard Smithdc7a4f52013-04-30 13:56:41 +00003633 bool IsDependent) const {
Richard Smith60e141e2013-05-04 07:00:32 +00003634 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
3635 return getAutoDeductType();
3636
3637 // Look in the folding set for an existing type.
Richard Smith483b9f32011-02-21 20:05:19 +00003638 void *InsertPos = 0;
Richard Smith60e141e2013-05-04 07:00:32 +00003639 llvm::FoldingSetNodeID ID;
3640 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
3641 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3642 return QualType(AT, 0);
Richard Smith483b9f32011-02-21 20:05:19 +00003643
Richard Smitha2c36462013-04-26 16:15:35 +00003644 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithdc7a4f52013-04-30 13:56:41 +00003645 IsDecltypeAuto,
3646 IsDependent);
Richard Smith483b9f32011-02-21 20:05:19 +00003647 Types.push_back(AT);
3648 if (InsertPos)
3649 AutoTypes.InsertNode(AT, InsertPos);
3650 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00003651}
3652
Eli Friedmanb001de72011-10-06 23:00:33 +00003653/// getAtomicType - Return the uniqued reference to the atomic type for
3654/// the given value type.
3655QualType ASTContext::getAtomicType(QualType T) const {
3656 // Unique pointers, to guarantee there is only one pointer of a particular
3657 // structure.
3658 llvm::FoldingSetNodeID ID;
3659 AtomicType::Profile(ID, T);
3660
3661 void *InsertPos = 0;
3662 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3663 return QualType(AT, 0);
3664
3665 // If the atomic value type isn't canonical, this won't be a canonical type
3666 // either, so fill in the canonical type field.
3667 QualType Canonical;
3668 if (!T.isCanonical()) {
3669 Canonical = getAtomicType(getCanonicalType(T));
3670
3671 // Get the new insert position for the node we care about.
3672 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3673 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3674 }
3675 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3676 Types.push_back(New);
3677 AtomicTypes.InsertNode(New, InsertPos);
3678 return QualType(New, 0);
3679}
3680
Richard Smithad762fc2011-04-14 22:09:26 +00003681/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3682QualType ASTContext::getAutoDeductType() const {
3683 if (AutoDeductTy.isNull())
Richard Smith60e141e2013-05-04 07:00:32 +00003684 AutoDeductTy = QualType(
3685 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
3686 /*dependent*/false),
3687 0);
Richard Smithad762fc2011-04-14 22:09:26 +00003688 return AutoDeductTy;
3689}
3690
3691/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3692QualType ASTContext::getAutoRRefDeductType() const {
3693 if (AutoRRefDeductTy.isNull())
3694 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3695 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3696 return AutoRRefDeductTy;
3697}
3698
Reid Spencer5f016e22007-07-11 17:01:13 +00003699/// getTagDeclType - Return the unique reference to the type for the
3700/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003701QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003702 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003703 // FIXME: What is the design on getTagDeclType when it requires casting
3704 // away const? mutable?
3705 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003706}
3707
Mike Stump1eb44332009-09-09 15:08:12 +00003708/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3709/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3710/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003711CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003712 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003713}
3714
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003715/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3716CanQualType ASTContext::getIntMaxType() const {
3717 return getFromTargetType(Target->getIntMaxType());
3718}
3719
3720/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3721CanQualType ASTContext::getUIntMaxType() const {
3722 return getFromTargetType(Target->getUIntMaxType());
3723}
3724
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003725/// getSignedWCharType - Return the type of "signed wchar_t".
3726/// Used when in C++, as a GCC extension.
3727QualType ASTContext::getSignedWCharType() const {
3728 // FIXME: derive from "Target" ?
3729 return WCharTy;
3730}
3731
3732/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3733/// Used when in C++, as a GCC extension.
3734QualType ASTContext::getUnsignedWCharType() const {
3735 // FIXME: derive from "Target" ?
3736 return UnsignedIntTy;
3737}
3738
Enea Zaffanella9677eb82013-01-26 17:08:37 +00003739QualType ASTContext::getIntPtrType() const {
3740 return getFromTargetType(Target->getIntPtrType());
3741}
3742
3743QualType ASTContext::getUIntPtrType() const {
3744 return getCorrespondingUnsignedType(getIntPtrType());
3745}
3746
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003747/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003748/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3749QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003750 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003751}
3752
Eli Friedman6902e412012-11-27 02:58:24 +00003753/// \brief Return the unique type for "pid_t" defined in
3754/// <sys/types.h>. We need this to compute the correct type for vfork().
3755QualType ASTContext::getProcessIDType() const {
3756 return getFromTargetType(Target->getProcessIDType());
3757}
3758
Chris Lattnere6327742008-04-02 05:18:44 +00003759//===----------------------------------------------------------------------===//
3760// Type Operators
3761//===----------------------------------------------------------------------===//
3762
Jay Foad4ba2a172011-01-12 09:06:06 +00003763CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003764 // Push qualifiers into arrays, and then discard any remaining
3765 // qualifiers.
3766 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003767 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003768 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003769 QualType Result;
3770 if (isa<ArrayType>(Ty)) {
3771 Result = getArrayDecayedType(QualType(Ty,0));
3772 } else if (isa<FunctionType>(Ty)) {
3773 Result = getPointerType(QualType(Ty, 0));
3774 } else {
3775 Result = QualType(Ty, 0);
3776 }
3777
3778 return CanQualType::CreateUnsafe(Result);
3779}
3780
John McCall62c28c82011-01-18 07:41:22 +00003781QualType ASTContext::getUnqualifiedArrayType(QualType type,
3782 Qualifiers &quals) {
3783 SplitQualType splitType = type.getSplitUnqualifiedType();
3784
3785 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3786 // the unqualified desugared type and then drops it on the floor.
3787 // We then have to strip that sugar back off with
3788 // getUnqualifiedDesugaredType(), which is silly.
3789 const ArrayType *AT =
John McCall200fa532012-02-08 00:46:36 +00003790 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall62c28c82011-01-18 07:41:22 +00003791
3792 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003793 if (!AT) {
John McCall200fa532012-02-08 00:46:36 +00003794 quals = splitType.Quals;
3795 return QualType(splitType.Ty, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003796 }
3797
John McCall62c28c82011-01-18 07:41:22 +00003798 // Otherwise, recurse on the array's element type.
3799 QualType elementType = AT->getElementType();
3800 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3801
3802 // If that didn't change the element type, AT has no qualifiers, so we
3803 // can just use the results in splitType.
3804 if (elementType == unqualElementType) {
3805 assert(quals.empty()); // from the recursive call
John McCall200fa532012-02-08 00:46:36 +00003806 quals = splitType.Quals;
3807 return QualType(splitType.Ty, 0);
John McCall62c28c82011-01-18 07:41:22 +00003808 }
3809
3810 // Otherwise, add in the qualifiers from the outermost type, then
3811 // build the type back up.
John McCall200fa532012-02-08 00:46:36 +00003812 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003813
Douglas Gregor9dadd942010-05-17 18:45:21 +00003814 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003815 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003816 CAT->getSizeModifier(), 0);
3817 }
3818
Douglas Gregor9dadd942010-05-17 18:45:21 +00003819 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003820 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003821 }
3822
Douglas Gregor9dadd942010-05-17 18:45:21 +00003823 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003824 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003825 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003826 VAT->getSizeModifier(),
3827 VAT->getIndexTypeCVRQualifiers(),
3828 VAT->getBracketsRange());
3829 }
3830
3831 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003832 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003833 DSAT->getSizeModifier(), 0,
3834 SourceRange());
3835}
3836
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003837/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3838/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3839/// they point to and return true. If T1 and T2 aren't pointer types
3840/// or pointer-to-member types, or if they are not similar at this
3841/// level, returns false and leaves T1 and T2 unchanged. Top-level
3842/// qualifiers on T1 and T2 are ignored. This function will typically
3843/// be called in a loop that successively "unwraps" pointer and
3844/// pointer-to-member types to compare them at each level.
3845bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3846 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3847 *T2PtrType = T2->getAs<PointerType>();
3848 if (T1PtrType && T2PtrType) {
3849 T1 = T1PtrType->getPointeeType();
3850 T2 = T2PtrType->getPointeeType();
3851 return true;
3852 }
3853
3854 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3855 *T2MPType = T2->getAs<MemberPointerType>();
3856 if (T1MPType && T2MPType &&
3857 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3858 QualType(T2MPType->getClass(), 0))) {
3859 T1 = T1MPType->getPointeeType();
3860 T2 = T2MPType->getPointeeType();
3861 return true;
3862 }
3863
David Blaikie4e4d0842012-03-11 07:00:24 +00003864 if (getLangOpts().ObjC1) {
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003865 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3866 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3867 if (T1OPType && T2OPType) {
3868 T1 = T1OPType->getPointeeType();
3869 T2 = T2OPType->getPointeeType();
3870 return true;
3871 }
3872 }
3873
3874 // FIXME: Block pointers, too?
3875
3876 return false;
3877}
3878
Jay Foad4ba2a172011-01-12 09:06:06 +00003879DeclarationNameInfo
3880ASTContext::getNameForTemplate(TemplateName Name,
3881 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003882 switch (Name.getKind()) {
3883 case TemplateName::QualifiedTemplate:
3884 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003885 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003886 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3887 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003888
John McCall14606042011-06-30 08:33:18 +00003889 case TemplateName::OverloadedTemplate: {
3890 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3891 // DNInfo work in progress: CHECKME: what about DNLoc?
3892 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3893 }
3894
3895 case TemplateName::DependentTemplate: {
3896 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003897 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003898 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003899 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3900 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003901 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003902 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3903 // DNInfo work in progress: FIXME: source locations?
3904 DeclarationNameLoc DNLoc;
3905 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3906 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3907 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003908 }
3909 }
3910
John McCall14606042011-06-30 08:33:18 +00003911 case TemplateName::SubstTemplateTemplateParm: {
3912 SubstTemplateTemplateParmStorage *subst
3913 = Name.getAsSubstTemplateTemplateParm();
3914 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3915 NameLoc);
3916 }
3917
3918 case TemplateName::SubstTemplateTemplateParmPack: {
3919 SubstTemplateTemplateParmPackStorage *subst
3920 = Name.getAsSubstTemplateTemplateParmPack();
3921 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3922 NameLoc);
3923 }
3924 }
3925
3926 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003927}
3928
Jay Foad4ba2a172011-01-12 09:06:06 +00003929TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003930 switch (Name.getKind()) {
3931 case TemplateName::QualifiedTemplate:
3932 case TemplateName::Template: {
3933 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003934 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003935 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003936 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3937
3938 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003939 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003940 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003941
John McCall14606042011-06-30 08:33:18 +00003942 case TemplateName::OverloadedTemplate:
3943 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003944
John McCall14606042011-06-30 08:33:18 +00003945 case TemplateName::DependentTemplate: {
3946 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3947 assert(DTN && "Non-dependent template names must refer to template decls.");
3948 return DTN->CanonicalTemplateName;
3949 }
3950
3951 case TemplateName::SubstTemplateTemplateParm: {
3952 SubstTemplateTemplateParmStorage *subst
3953 = Name.getAsSubstTemplateTemplateParm();
3954 return getCanonicalTemplateName(subst->getReplacement());
3955 }
3956
3957 case TemplateName::SubstTemplateTemplateParmPack: {
3958 SubstTemplateTemplateParmPackStorage *subst
3959 = Name.getAsSubstTemplateTemplateParmPack();
3960 TemplateTemplateParmDecl *canonParameter
3961 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3962 TemplateArgument canonArgPack
3963 = getCanonicalTemplateArgument(subst->getArgumentPack());
3964 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3965 }
3966 }
3967
3968 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003969}
3970
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003971bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3972 X = getCanonicalTemplateName(X);
3973 Y = getCanonicalTemplateName(Y);
3974 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3975}
3976
Mike Stump1eb44332009-09-09 15:08:12 +00003977TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003978ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003979 switch (Arg.getKind()) {
3980 case TemplateArgument::Null:
3981 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003982
Douglas Gregor1275ae02009-07-28 23:00:59 +00003983 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003984 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003985
Douglas Gregord2008e22012-04-06 22:40:38 +00003986 case TemplateArgument::Declaration: {
Eli Friedmand7a6b162012-09-26 02:36:12 +00003987 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
3988 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregord2008e22012-04-06 22:40:38 +00003989 }
Mike Stump1eb44332009-09-09 15:08:12 +00003990
Eli Friedmand7a6b162012-09-26 02:36:12 +00003991 case TemplateArgument::NullPtr:
3992 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
3993 /*isNullPtr*/true);
3994
Douglas Gregor788cd062009-11-11 01:00:40 +00003995 case TemplateArgument::Template:
3996 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003997
3998 case TemplateArgument::TemplateExpansion:
3999 return TemplateArgument(getCanonicalTemplateName(
4000 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00004001 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00004002
Douglas Gregor1275ae02009-07-28 23:00:59 +00004003 case TemplateArgument::Integral:
Benjamin Kramer85524372012-06-07 15:09:51 +00004004 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00004005
Douglas Gregor1275ae02009-07-28 23:00:59 +00004006 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00004007 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00004008
Douglas Gregor1275ae02009-07-28 23:00:59 +00004009 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00004010 if (Arg.pack_size() == 0)
4011 return Arg;
4012
Douglas Gregor910f8002010-11-07 23:05:16 +00004013 TemplateArgument *CanonArgs
4014 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00004015 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004016 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00004017 AEnd = Arg.pack_end();
4018 A != AEnd; (void)++A, ++Idx)
4019 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00004020
Douglas Gregor910f8002010-11-07 23:05:16 +00004021 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00004022 }
4023 }
4024
4025 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00004026 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00004027}
4028
Douglas Gregord57959a2009-03-27 23:10:48 +00004029NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00004030ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004031 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00004032 return 0;
4033
4034 switch (NNS->getKind()) {
4035 case NestedNameSpecifier::Identifier:
4036 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00004037 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00004038 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4039 NNS->getAsIdentifier());
4040
4041 case NestedNameSpecifier::Namespace:
4042 // A namespace is canonical; build a nested-name-specifier with
4043 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00004044 return NestedNameSpecifier::Create(*this, 0,
4045 NNS->getAsNamespace()->getOriginalNamespace());
4046
4047 case NestedNameSpecifier::NamespaceAlias:
4048 // A namespace is canonical; build a nested-name-specifier with
4049 // this namespace and no prefix.
4050 return NestedNameSpecifier::Create(*this, 0,
4051 NNS->getAsNamespaceAlias()->getNamespace()
4052 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00004053
4054 case NestedNameSpecifier::TypeSpec:
4055 case NestedNameSpecifier::TypeSpecWithTemplate: {
4056 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00004057
4058 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4059 // break it apart into its prefix and identifier, then reconsititute those
4060 // as the canonical nested-name-specifier. This is required to canonicalize
4061 // a dependent nested-name-specifier involving typedefs of dependent-name
4062 // types, e.g.,
4063 // typedef typename T::type T1;
4064 // typedef typename T1::type T2;
Eli Friedman16412ef2012-03-03 04:09:56 +00004065 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4066 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor264bf662010-11-04 00:09:33 +00004067 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor264bf662010-11-04 00:09:33 +00004068
Eli Friedman16412ef2012-03-03 04:09:56 +00004069 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4070 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4071 // first place?
John McCall3b657512011-01-19 10:06:00 +00004072 return NestedNameSpecifier::Create(*this, 0, false,
4073 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00004074 }
4075
4076 case NestedNameSpecifier::Global:
4077 // The global specifier is canonical and unique.
4078 return NNS;
4079 }
4080
David Blaikie7530c032012-01-17 06:56:22 +00004081 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregord57959a2009-03-27 23:10:48 +00004082}
4083
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004084
Jay Foad4ba2a172011-01-12 09:06:06 +00004085const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004086 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004087 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004088 // Handle the common positive case fast.
4089 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4090 return AT;
4091 }
Mike Stump1eb44332009-09-09 15:08:12 +00004092
John McCall0953e762009-09-24 19:53:00 +00004093 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00004094 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004095 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004096
John McCall0953e762009-09-24 19:53:00 +00004097 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004098 // implements C99 6.7.3p8: "If the specification of an array type includes
4099 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00004100
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004101 // If we get here, we either have type qualifiers on the type, or we have
4102 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00004103 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00004104
John McCall3b657512011-01-19 10:06:00 +00004105 SplitQualType split = T.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004106 Qualifiers qs = split.Quals;
Mike Stump1eb44332009-09-09 15:08:12 +00004107
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004108 // If we have a simple case, just return now.
John McCall200fa532012-02-08 00:46:36 +00004109 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall3b657512011-01-19 10:06:00 +00004110 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004111 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00004112
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004113 // Otherwise, we have an array and we have qualifiers on it. Push the
4114 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00004115 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00004116
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004117 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4118 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4119 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004120 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004121 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4122 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4123 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004124 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00004125
Mike Stump1eb44332009-09-09 15:08:12 +00004126 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00004127 = dyn_cast<DependentSizedArrayType>(ATy))
4128 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00004129 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00004130 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00004131 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004132 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004133 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00004134
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004135 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004136 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00004137 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004138 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004139 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004140 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00004141}
4142
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004143QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004144 // C99 6.7.5.3p7:
4145 // A declaration of a parameter as "array of type" shall be
4146 // adjusted to "qualified pointer to type", where the type
4147 // qualifiers (if any) are those specified within the [ and ] of
4148 // the array type derivation.
4149 if (T->isArrayType())
4150 return getArrayDecayedType(T);
4151
4152 // C99 6.7.5.3p8:
4153 // A declaration of a parameter as "function returning type"
4154 // shall be adjusted to "pointer to function returning type", as
4155 // in 6.3.2.1.
4156 if (T->isFunctionType())
4157 return getPointerType(T);
4158
4159 return T;
4160}
4161
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004162QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004163 T = getVariableArrayDecayedType(T);
4164 T = getAdjustedParameterType(T);
4165 return T.getUnqualifiedType();
4166}
4167
Chris Lattnere6327742008-04-02 05:18:44 +00004168/// getArrayDecayedType - Return the properly qualified result of decaying the
4169/// specified array type to a pointer. This operation is non-trivial when
4170/// handling typedefs etc. The canonical type of "T" must be an array type,
4171/// this returns a pointer to a properly qualified element of the array.
4172///
4173/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00004174QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004175 // Get the element type with 'getAsArrayType' so that we don't lose any
4176 // typedefs in the element type of the array. This also handles propagation
4177 // of type qualifiers from the array type into the element type if present
4178 // (C99 6.7.3p8).
4179 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4180 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00004181
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004182 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00004183
4184 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00004185 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00004186}
4187
John McCall3b657512011-01-19 10:06:00 +00004188QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4189 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00004190}
4191
John McCall3b657512011-01-19 10:06:00 +00004192QualType ASTContext::getBaseElementType(QualType type) const {
4193 Qualifiers qs;
4194 while (true) {
4195 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004196 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall3b657512011-01-19 10:06:00 +00004197 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00004198
John McCall3b657512011-01-19 10:06:00 +00004199 type = array->getElementType();
John McCall200fa532012-02-08 00:46:36 +00004200 qs.addConsistentQualifiers(split.Quals);
John McCall3b657512011-01-19 10:06:00 +00004201 }
Mike Stump1eb44332009-09-09 15:08:12 +00004202
John McCall3b657512011-01-19 10:06:00 +00004203 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00004204}
4205
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004206/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00004207uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004208ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4209 uint64_t ElementCount = 1;
4210 do {
4211 ElementCount *= CA->getSize().getZExtValue();
Richard Smithd5e83942012-12-06 03:04:50 +00004212 CA = dyn_cast_or_null<ConstantArrayType>(
4213 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004214 } while (CA);
4215 return ElementCount;
4216}
4217
Reid Spencer5f016e22007-07-11 17:01:13 +00004218/// getFloatingRank - Return a relative rank for floating point types.
4219/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00004220static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00004221 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00004222 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00004223
John McCall183700f2009-09-21 23:43:11 +00004224 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4225 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004226 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00004227 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00004228 case BuiltinType::Float: return FloatRank;
4229 case BuiltinType::Double: return DoubleRank;
4230 case BuiltinType::LongDouble: return LongDoubleRank;
4231 }
4232}
4233
Mike Stump1eb44332009-09-09 15:08:12 +00004234/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4235/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00004236/// 'typeDomain' is a real floating point or complex type.
4237/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00004238QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4239 QualType Domain) const {
4240 FloatingRank EltRank = getFloatingRank(Size);
4241 if (Domain->isComplexType()) {
4242 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00004243 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Narofff1448a02007-08-27 01:27:54 +00004244 case FloatRank: return FloatComplexTy;
4245 case DoubleRank: return DoubleComplexTy;
4246 case LongDoubleRank: return LongDoubleComplexTy;
4247 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004248 }
Chris Lattner1361b112008-04-06 23:58:54 +00004249
4250 assert(Domain->isRealFloatingType() && "Unknown domain!");
4251 switch (EltRank) {
Joey Gouly19dbb202013-01-23 11:56:20 +00004252 case HalfRank: return HalfTy;
Chris Lattner1361b112008-04-06 23:58:54 +00004253 case FloatRank: return FloatTy;
4254 case DoubleRank: return DoubleTy;
4255 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00004256 }
David Blaikie561d3ab2012-01-17 02:30:50 +00004257 llvm_unreachable("getFloatingRank(): illegal value for rank");
Reid Spencer5f016e22007-07-11 17:01:13 +00004258}
4259
Chris Lattner7cfeb082008-04-06 23:55:33 +00004260/// getFloatingTypeOrder - Compare the rank of the two specified floating
4261/// point types, ignoring the domain of the type (i.e. 'double' ==
4262/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004263/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004264int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00004265 FloatingRank LHSR = getFloatingRank(LHS);
4266 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004267
Chris Lattnera75cea32008-04-06 23:38:49 +00004268 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004269 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00004270 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004271 return 1;
4272 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004273}
4274
Chris Lattnerf52ab252008-04-06 22:59:24 +00004275/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4276/// routine will assert if passed a built-in type that isn't an integer or enum,
4277/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00004278unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00004279 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00004280
Chris Lattnerf52ab252008-04-06 22:59:24 +00004281 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004282 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00004283 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004284 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004285 case BuiltinType::Char_S:
4286 case BuiltinType::Char_U:
4287 case BuiltinType::SChar:
4288 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004289 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004290 case BuiltinType::Short:
4291 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004292 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004293 case BuiltinType::Int:
4294 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004295 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004296 case BuiltinType::Long:
4297 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004298 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004299 case BuiltinType::LongLong:
4300 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004301 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00004302 case BuiltinType::Int128:
4303 case BuiltinType::UInt128:
4304 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00004305 }
4306}
4307
Eli Friedman04e83572009-08-20 04:21:42 +00004308/// \brief Whether this is a promotable bitfield reference according
4309/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4310///
4311/// \returns the type this bit-field will promote to, or NULL if no
4312/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00004313QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00004314 if (E->isTypeDependent() || E->isValueDependent())
4315 return QualType();
4316
John McCall993f43f2013-05-06 21:39:12 +00004317 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman04e83572009-08-20 04:21:42 +00004318 if (!Field)
4319 return QualType();
4320
4321 QualType FT = Field->getType();
4322
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004323 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00004324 uint64_t IntSize = getTypeSize(IntTy);
4325 // GCC extension compatibility: if the bit-field size is less than or equal
4326 // to the size of int, it gets promoted no matter what its type is.
4327 // For instance, unsigned long bf : 4 gets promoted to signed int.
4328 if (BitWidth < IntSize)
4329 return IntTy;
4330
4331 if (BitWidth == IntSize)
4332 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4333
4334 // Types bigger than int are not subject to promotions, and therefore act
4335 // like the base type.
4336 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4337 // is ridiculous.
4338 return QualType();
4339}
4340
Eli Friedmana95d7572009-08-19 07:44:53 +00004341/// getPromotedIntegerType - Returns the type that Promotable will
4342/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4343/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00004344QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00004345 assert(!Promotable.isNull());
4346 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00004347 if (const EnumType *ET = Promotable->getAs<EnumType>())
4348 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00004349
4350 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4351 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4352 // (3.9.1) can be converted to a prvalue of the first of the following
4353 // types that can represent all the values of its underlying type:
4354 // int, unsigned int, long int, unsigned long int, long long int, or
4355 // unsigned long long int [...]
4356 // FIXME: Is there some better way to compute this?
4357 if (BT->getKind() == BuiltinType::WChar_S ||
4358 BT->getKind() == BuiltinType::WChar_U ||
4359 BT->getKind() == BuiltinType::Char16 ||
4360 BT->getKind() == BuiltinType::Char32) {
4361 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4362 uint64_t FromSize = getTypeSize(BT);
4363 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4364 LongLongTy, UnsignedLongLongTy };
4365 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4366 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4367 if (FromSize < ToSize ||
4368 (FromSize == ToSize &&
4369 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4370 return PromoteTypes[Idx];
4371 }
4372 llvm_unreachable("char type should fit into long long");
4373 }
4374 }
4375
4376 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00004377 if (Promotable->isSignedIntegerType())
4378 return IntTy;
Eli Friedman5b64e772012-11-15 01:21:59 +00004379 uint64_t PromotableSize = getIntWidth(Promotable);
4380 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedmana95d7572009-08-19 07:44:53 +00004381 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4382 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4383}
4384
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004385/// \brief Recurses in pointer/array types until it finds an objc retainable
4386/// type and returns its ownership.
4387Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4388 while (!T.isNull()) {
4389 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4390 return T.getObjCLifetime();
4391 if (T->isArrayType())
4392 T = getBaseElementType(T);
4393 else if (const PointerType *PT = T->getAs<PointerType>())
4394 T = PT->getPointeeType();
4395 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00004396 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004397 else
4398 break;
4399 }
4400
4401 return Qualifiers::OCL_None;
4402}
4403
Mike Stump1eb44332009-09-09 15:08:12 +00004404/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00004405/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004406/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004407int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00004408 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4409 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00004410 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004411
Chris Lattnerf52ab252008-04-06 22:59:24 +00004412 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4413 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00004414
Chris Lattner7cfeb082008-04-06 23:55:33 +00004415 unsigned LHSRank = getIntegerRank(LHSC);
4416 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00004417
Chris Lattner7cfeb082008-04-06 23:55:33 +00004418 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4419 if (LHSRank == RHSRank) return 0;
4420 return LHSRank > RHSRank ? 1 : -1;
4421 }
Mike Stump1eb44332009-09-09 15:08:12 +00004422
Chris Lattner7cfeb082008-04-06 23:55:33 +00004423 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4424 if (LHSUnsigned) {
4425 // If the unsigned [LHS] type is larger, return it.
4426 if (LHSRank >= RHSRank)
4427 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004428
Chris Lattner7cfeb082008-04-06 23:55:33 +00004429 // If the signed type can represent all values of the unsigned type, it
4430 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004431 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004432 return -1;
4433 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00004434
Chris Lattner7cfeb082008-04-06 23:55:33 +00004435 // If the unsigned [RHS] type is larger, return it.
4436 if (RHSRank >= LHSRank)
4437 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00004438
Chris Lattner7cfeb082008-04-06 23:55:33 +00004439 // If the signed type can represent all values of the unsigned type, it
4440 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004441 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004442 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004443}
Anders Carlsson71993dd2007-08-17 05:31:46 +00004444
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004445static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004446CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4447 DeclContext *DC, IdentifierInfo *Id) {
4448 SourceLocation Loc;
David Blaikie4e4d0842012-03-11 07:00:24 +00004449 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004450 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004451 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004452 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004453}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004454
Mike Stump1eb44332009-09-09 15:08:12 +00004455// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00004456QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00004457 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004458 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004459 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004460 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00004461 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004462
Anders Carlssonf06273f2007-11-19 00:25:30 +00004463 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00004464
Anders Carlsson71993dd2007-08-17 05:31:46 +00004465 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00004466 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00004467 // int flags;
4468 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00004469 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00004470 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00004471 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00004472 FieldTypes[3] = LongTy;
4473
Anders Carlsson71993dd2007-08-17 05:31:46 +00004474 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00004475 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00004476 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004477 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00004478 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00004479 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00004480 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004481 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004482 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004483 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004484 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00004485 }
4486
Douglas Gregor838db382010-02-11 01:19:42 +00004487 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00004488 }
Mike Stump1eb44332009-09-09 15:08:12 +00004489
Anders Carlsson71993dd2007-08-17 05:31:46 +00004490 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00004491}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004492
Fariborz Jahanianf7992132013-01-04 18:45:40 +00004493QualType ASTContext::getObjCSuperType() const {
4494 if (ObjCSuperType.isNull()) {
4495 RecordDecl *ObjCSuperTypeDecl =
4496 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4497 TUDecl->addDecl(ObjCSuperTypeDecl);
4498 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4499 }
4500 return ObjCSuperType;
4501}
4502
Douglas Gregor319ac892009-04-23 22:29:11 +00004503void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004504 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00004505 assert(Rec && "Invalid CFConstantStringType");
4506 CFConstantStringTypeDecl = Rec->getDecl();
4507}
4508
Jay Foad4ba2a172011-01-12 09:06:06 +00004509QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00004510 if (BlockDescriptorType)
4511 return getTagDeclType(BlockDescriptorType);
4512
4513 RecordDecl *T;
4514 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004515 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004516 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00004517 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004518
4519 QualType FieldTypes[] = {
4520 UnsignedLongTy,
4521 UnsignedLongTy,
4522 };
4523
4524 const char *FieldNames[] = {
4525 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00004526 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00004527 };
4528
4529 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004530 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00004531 SourceLocation(),
4532 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004533 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00004534 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004535 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004536 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004537 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00004538 T->addDecl(Field);
4539 }
4540
Douglas Gregor838db382010-02-11 01:19:42 +00004541 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004542
4543 BlockDescriptorType = T;
4544
4545 return getTagDeclType(BlockDescriptorType);
4546}
4547
Jay Foad4ba2a172011-01-12 09:06:06 +00004548QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00004549 if (BlockDescriptorExtendedType)
4550 return getTagDeclType(BlockDescriptorExtendedType);
4551
4552 RecordDecl *T;
4553 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004554 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004555 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00004556 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004557
4558 QualType FieldTypes[] = {
4559 UnsignedLongTy,
4560 UnsignedLongTy,
4561 getPointerType(VoidPtrTy),
4562 getPointerType(VoidPtrTy)
4563 };
4564
4565 const char *FieldNames[] = {
4566 "reserved",
4567 "Size",
4568 "CopyFuncPtr",
4569 "DestroyFuncPtr"
4570 };
4571
4572 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004573 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00004574 SourceLocation(),
4575 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004576 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00004577 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004578 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004579 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004580 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00004581 T->addDecl(Field);
4582 }
4583
Douglas Gregor838db382010-02-11 01:19:42 +00004584 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004585
4586 BlockDescriptorExtendedType = T;
4587
4588 return getTagDeclType(BlockDescriptorExtendedType);
4589}
4590
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004591/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4592/// requires copy/dispose. Note that this must match the logic
4593/// in buildByrefHelpers.
4594bool ASTContext::BlockRequiresCopying(QualType Ty,
4595 const VarDecl *D) {
4596 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4597 const Expr *copyExpr = getBlockVarCopyInits(D);
4598 if (!copyExpr && record->hasTrivialDestructor()) return false;
4599
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004600 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00004601 }
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004602
4603 if (!Ty->isObjCRetainableType()) return false;
4604
4605 Qualifiers qs = Ty.getQualifiers();
4606
4607 // If we have lifetime, that dominates.
4608 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4609 assert(getLangOpts().ObjCAutoRefCount);
4610
4611 switch (lifetime) {
4612 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4613
4614 // These are just bits as far as the runtime is concerned.
4615 case Qualifiers::OCL_ExplicitNone:
4616 case Qualifiers::OCL_Autoreleasing:
4617 return false;
4618
4619 // Tell the runtime that this is ARC __weak, called by the
4620 // byref routines.
4621 case Qualifiers::OCL_Weak:
4622 // ARC __strong __block variables need to be retained.
4623 case Qualifiers::OCL_Strong:
4624 return true;
4625 }
4626 llvm_unreachable("fell out of lifetime switch!");
4627 }
4628 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4629 Ty->isObjCObjectPointerType());
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004630}
4631
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004632bool ASTContext::getByrefLifetime(QualType Ty,
4633 Qualifiers::ObjCLifetime &LifeTime,
4634 bool &HasByrefExtendedLayout) const {
4635
4636 if (!getLangOpts().ObjC1 ||
4637 getLangOpts().getGC() != LangOptions::NonGC)
4638 return false;
4639
4640 HasByrefExtendedLayout = false;
Fariborz Jahanian34db84f2012-12-11 19:58:01 +00004641 if (Ty->isRecordType()) {
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004642 HasByrefExtendedLayout = true;
4643 LifeTime = Qualifiers::OCL_None;
4644 }
4645 else if (getLangOpts().ObjCAutoRefCount)
4646 LifeTime = Ty.getObjCLifetime();
4647 // MRR.
4648 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4649 LifeTime = Qualifiers::OCL_ExplicitNone;
4650 else
4651 LifeTime = Qualifiers::OCL_None;
4652 return true;
4653}
4654
Douglas Gregore97179c2011-09-08 01:46:34 +00004655TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4656 if (!ObjCInstanceTypeDecl)
4657 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4658 getTranslationUnitDecl(),
4659 SourceLocation(),
4660 SourceLocation(),
4661 &Idents.get("instancetype"),
4662 getTrivialTypeSourceInfo(getObjCIdType()));
4663 return ObjCInstanceTypeDecl;
4664}
4665
Anders Carlssone8c49532007-10-29 06:33:42 +00004666// This returns true if a type has been typedefed to BOOL:
4667// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00004668static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00004669 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00004670 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4671 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00004672
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004673 return false;
4674}
4675
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004676/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004677/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00004678CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00004679 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4680 return CharUnits::Zero();
4681
Ken Dyck199c3d62010-01-11 17:06:35 +00004682 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004683
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004684 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004685 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004686 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004687 // Treat arrays as pointers, since that's how they're passed in.
4688 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004689 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004690 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004691}
4692
4693static inline
4694std::string charUnitsToString(const CharUnits &CU) {
4695 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004696}
4697
John McCall6b5a61b2011-02-07 10:33:21 +00004698/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004699/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004700std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4701 std::string S;
4702
David Chisnall5e530af2009-11-17 19:33:30 +00004703 const BlockDecl *Decl = Expr->getBlockDecl();
4704 QualType BlockTy =
4705 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4706 // Encode result type.
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004707 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004708 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4709 BlockTy->getAs<FunctionType>()->getResultType(),
4710 S, true /*Extended*/);
4711 else
4712 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4713 S);
David Chisnall5e530af2009-11-17 19:33:30 +00004714 // Compute size of all parameters.
4715 // Start with computing size of a pointer in number of bytes.
4716 // FIXME: There might(should) be a better way of doing this computation!
4717 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004718 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4719 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004720 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004721 E = Decl->param_end(); PI != E; ++PI) {
4722 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004723 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahanian075a5432012-06-30 00:48:59 +00004724 if (sz.isZero())
4725 continue;
Ken Dyck199c3d62010-01-11 17:06:35 +00004726 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004727 ParmOffset += sz;
4728 }
4729 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004730 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004731 // Block pointer and offset.
4732 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004733
4734 // Argument types.
4735 ParmOffset = PtrSize;
4736 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4737 Decl->param_end(); PI != E; ++PI) {
4738 ParmVarDecl *PVDecl = *PI;
4739 QualType PType = PVDecl->getOriginalType();
4740 if (const ArrayType *AT =
4741 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4742 // Use array's original type only if it has known number of
4743 // elements.
4744 if (!isa<ConstantArrayType>(AT))
4745 PType = PVDecl->getType();
4746 } else if (PType->isFunctionType())
4747 PType = PVDecl->getType();
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004748 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004749 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4750 S, true /*Extended*/);
4751 else
4752 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004753 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004754 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004755 }
John McCall6b5a61b2011-02-07 10:33:21 +00004756
4757 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004758}
4759
Douglas Gregorf968d832011-05-27 01:19:52 +00004760bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004761 std::string& S) {
4762 // Encode result type.
4763 getObjCEncodingForType(Decl->getResultType(), S);
4764 CharUnits ParmOffset;
4765 // Compute size of all parameters.
4766 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4767 E = Decl->param_end(); PI != E; ++PI) {
4768 QualType PType = (*PI)->getType();
4769 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004770 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004771 continue;
4772
David Chisnall5389f482010-12-30 14:05:53 +00004773 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004774 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004775 ParmOffset += sz;
4776 }
4777 S += charUnitsToString(ParmOffset);
4778 ParmOffset = CharUnits::Zero();
4779
4780 // Argument types.
4781 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4782 E = Decl->param_end(); PI != E; ++PI) {
4783 ParmVarDecl *PVDecl = *PI;
4784 QualType PType = PVDecl->getOriginalType();
4785 if (const ArrayType *AT =
4786 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4787 // Use array's original type only if it has known number of
4788 // elements.
4789 if (!isa<ConstantArrayType>(AT))
4790 PType = PVDecl->getType();
4791 } else if (PType->isFunctionType())
4792 PType = PVDecl->getType();
4793 getObjCEncodingForType(PType, S);
4794 S += charUnitsToString(ParmOffset);
4795 ParmOffset += getObjCEncodingTypeSize(PType);
4796 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004797
4798 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004799}
4800
Bob Wilsondc8dab62011-11-30 01:57:58 +00004801/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4802/// method parameter or return type. If Extended, include class names and
4803/// block object types.
4804void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4805 QualType T, std::string& S,
4806 bool Extended) const {
4807 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4808 getObjCEncodingForTypeQualifier(QT, S);
4809 // Encode parameter type.
4810 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4811 true /*OutermostType*/,
4812 false /*EncodingProperty*/,
4813 false /*StructField*/,
4814 Extended /*EncodeBlockParameters*/,
4815 Extended /*EncodeClassNames*/);
4816}
4817
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004818/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004819/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004820bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004821 std::string& S,
4822 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004823 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004824 // Encode return type.
4825 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4826 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004827 // Compute size of all parameters.
4828 // Start with computing size of a pointer in number of bytes.
4829 // FIXME: There might(should) be a better way of doing this computation!
4830 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004831 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004832 // The first two arguments (self and _cmd) are pointers; account for
4833 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004834 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004835 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004836 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004837 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004838 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004839 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004840 continue;
4841
Ken Dyck199c3d62010-01-11 17:06:35 +00004842 assert (sz.isPositive() &&
4843 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004844 ParmOffset += sz;
4845 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004846 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004847 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004848 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004849
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004850 // Argument types.
4851 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004852 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004853 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004854 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004855 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004856 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004857 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4858 // Use array's original type only if it has known number of
4859 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004860 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004861 PType = PVDecl->getType();
4862 } else if (PType->isFunctionType())
4863 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004864 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4865 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004866 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004867 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004868 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004869
4870 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004871}
4872
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004873/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004874/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004875/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4876/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004877/// Property attributes are stored as a comma-delimited C string. The simple
4878/// attributes readonly and bycopy are encoded as single characters. The
4879/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4880/// encoded as single characters, followed by an identifier. Property types
4881/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004882/// these attributes are defined by the following enumeration:
4883/// @code
4884/// enum PropertyAttributes {
4885/// kPropertyReadOnly = 'R', // property is read-only.
4886/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4887/// kPropertyByref = '&', // property is a reference to the value last assigned
4888/// kPropertyDynamic = 'D', // property is dynamic
4889/// kPropertyGetter = 'G', // followed by getter selector name
4890/// kPropertySetter = 'S', // followed by setter selector name
4891/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson0d4cb852012-03-22 17:48:02 +00004892/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004893/// kPropertyWeak = 'W' // 'weak' property
4894/// kPropertyStrong = 'P' // property GC'able
4895/// kPropertyNonAtomic = 'N' // property non-atomic
4896/// };
4897/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004898void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004899 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004900 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004901 // Collect information from the property implementation decl(s).
4902 bool Dynamic = false;
4903 ObjCPropertyImplDecl *SynthesizePID = 0;
4904
4905 // FIXME: Duplicated code due to poor abstraction.
4906 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004907 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004908 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4909 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004910 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004911 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004912 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004913 if (PID->getPropertyDecl() == PD) {
4914 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4915 Dynamic = true;
4916 } else {
4917 SynthesizePID = PID;
4918 }
4919 }
4920 }
4921 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004922 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004923 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004924 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004925 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004926 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004927 if (PID->getPropertyDecl() == PD) {
4928 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4929 Dynamic = true;
4930 } else {
4931 SynthesizePID = PID;
4932 }
4933 }
Mike Stump1eb44332009-09-09 15:08:12 +00004934 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004935 }
4936 }
4937
4938 // FIXME: This is not very efficient.
4939 S = "T";
4940
4941 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004942 // GCC has some special rules regarding encoding of properties which
4943 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004944 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004945 true /* outermost type */,
4946 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004947
4948 if (PD->isReadOnly()) {
4949 S += ",R";
Nico Weberd7ceab32013-05-08 23:47:40 +00004950 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
4951 S += ",C";
4952 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
4953 S += ",&";
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004954 } else {
4955 switch (PD->getSetterKind()) {
4956 case ObjCPropertyDecl::Assign: break;
4957 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004958 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004959 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004960 }
4961 }
4962
4963 // It really isn't clear at all what this means, since properties
4964 // are "dynamic by default".
4965 if (Dynamic)
4966 S += ",D";
4967
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004968 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4969 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004970
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004971 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4972 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004973 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004974 }
4975
4976 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4977 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004978 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004979 }
4980
4981 if (SynthesizePID) {
4982 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4983 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004984 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004985 }
4986
4987 // FIXME: OBJCGC: weak & strong
4988}
4989
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004990/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004991/// Another legacy compatibility encoding: 32-bit longs are encoded as
4992/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004993/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4994///
4995void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004996 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004997 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004998 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004999 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00005000 else
Jay Foad4ba2a172011-01-12 09:06:06 +00005001 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005002 PointeeTy = IntTy;
5003 }
5004 }
5005}
5006
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005007void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00005008 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005009 // We follow the behavior of gcc, expanding structures which are
5010 // directly pointed to, and expanding embedded structures. Note that
5011 // these rules are sufficient to prevent recursive encoding of the
5012 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00005013 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00005014 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005015}
5016
John McCall3624e9e2012-12-20 02:45:14 +00005017static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5018 BuiltinType::Kind kind) {
5019 switch (kind) {
David Chisnall64fd7e82010-06-04 01:10:52 +00005020 case BuiltinType::Void: return 'v';
5021 case BuiltinType::Bool: return 'B';
5022 case BuiltinType::Char_U:
5023 case BuiltinType::UChar: return 'C';
John McCall3624e9e2012-12-20 02:45:14 +00005024 case BuiltinType::Char16:
David Chisnall64fd7e82010-06-04 01:10:52 +00005025 case BuiltinType::UShort: return 'S';
John McCall3624e9e2012-12-20 02:45:14 +00005026 case BuiltinType::Char32:
David Chisnall64fd7e82010-06-04 01:10:52 +00005027 case BuiltinType::UInt: return 'I';
5028 case BuiltinType::ULong:
John McCall3624e9e2012-12-20 02:45:14 +00005029 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00005030 case BuiltinType::UInt128: return 'T';
5031 case BuiltinType::ULongLong: return 'Q';
5032 case BuiltinType::Char_S:
5033 case BuiltinType::SChar: return 'c';
5034 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00005035 case BuiltinType::WChar_S:
5036 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00005037 case BuiltinType::Int: return 'i';
5038 case BuiltinType::Long:
John McCall3624e9e2012-12-20 02:45:14 +00005039 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00005040 case BuiltinType::LongLong: return 'q';
5041 case BuiltinType::Int128: return 't';
5042 case BuiltinType::Float: return 'f';
5043 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00005044 case BuiltinType::LongDouble: return 'D';
John McCall3624e9e2012-12-20 02:45:14 +00005045 case BuiltinType::NullPtr: return '*'; // like char*
5046
5047 case BuiltinType::Half:
5048 // FIXME: potentially need @encodes for these!
5049 return ' ';
5050
5051 case BuiltinType::ObjCId:
5052 case BuiltinType::ObjCClass:
5053 case BuiltinType::ObjCSel:
5054 llvm_unreachable("@encoding ObjC primitive type");
5055
5056 // OpenCL and placeholder types don't need @encodings.
5057 case BuiltinType::OCLImage1d:
5058 case BuiltinType::OCLImage1dArray:
5059 case BuiltinType::OCLImage1dBuffer:
5060 case BuiltinType::OCLImage2d:
5061 case BuiltinType::OCLImage2dArray:
5062 case BuiltinType::OCLImage3d:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005063 case BuiltinType::OCLEvent:
Guy Benyei21f18c42013-02-07 10:55:47 +00005064 case BuiltinType::OCLSampler:
John McCall3624e9e2012-12-20 02:45:14 +00005065 case BuiltinType::Dependent:
5066#define BUILTIN_TYPE(KIND, ID)
5067#define PLACEHOLDER_TYPE(KIND, ID) \
5068 case BuiltinType::KIND:
5069#include "clang/AST/BuiltinTypes.def"
5070 llvm_unreachable("invalid builtin type for @encode");
David Chisnall64fd7e82010-06-04 01:10:52 +00005071 }
David Blaikie719e53f2013-01-09 17:48:41 +00005072 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnall64fd7e82010-06-04 01:10:52 +00005073}
5074
Douglas Gregor5471bc82011-09-08 17:18:35 +00005075static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5076 EnumDecl *Enum = ET->getDecl();
5077
5078 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5079 if (!Enum->isFixed())
5080 return 'i';
5081
5082 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall3624e9e2012-12-20 02:45:14 +00005083 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5084 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor5471bc82011-09-08 17:18:35 +00005085}
5086
Jay Foad4ba2a172011-01-12 09:06:06 +00005087static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00005088 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005089 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00005090 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00005091 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5092 // The GNU runtime requires more information; bitfields are encoded as b,
5093 // then the offset (in bits) of the first element, then the type of the
5094 // bitfield, then the size in bits. For example, in this structure:
5095 //
5096 // struct
5097 // {
5098 // int integer;
5099 // int flags:2;
5100 // };
5101 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5102 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5103 // information is not especially sensible, but we're stuck with it for
5104 // compatibility with GCC, although providing it breaks anything that
5105 // actually uses runtime introspection and wants to work on both runtimes...
John McCall260611a2012-06-20 06:18:46 +00005106 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnall64fd7e82010-06-04 01:10:52 +00005107 const RecordDecl *RD = FD->getParent();
5108 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00005109 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00005110 if (const EnumType *ET = T->getAs<EnumType>())
5111 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall3624e9e2012-12-20 02:45:14 +00005112 else {
5113 const BuiltinType *BT = T->castAs<BuiltinType>();
5114 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5115 }
David Chisnall64fd7e82010-06-04 01:10:52 +00005116 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005117 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00005118}
5119
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00005120// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005121void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5122 bool ExpandPointedToStructures,
5123 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00005124 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00005125 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005126 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00005127 bool StructField,
5128 bool EncodeBlockParameters,
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005129 bool EncodeClassNames,
5130 bool EncodePointerToObjCTypedef) const {
John McCall3624e9e2012-12-20 02:45:14 +00005131 CanQualType CT = getCanonicalType(T);
5132 switch (CT->getTypeClass()) {
5133 case Type::Builtin:
5134 case Type::Enum:
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005135 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00005136 return EncodeBitField(this, S, T, FD);
John McCall3624e9e2012-12-20 02:45:14 +00005137 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5138 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5139 else
5140 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005141 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005142
John McCall3624e9e2012-12-20 02:45:14 +00005143 case Type::Complex: {
5144 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005145 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00005146 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005147 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005148 return;
5149 }
John McCall3624e9e2012-12-20 02:45:14 +00005150
5151 case Type::Atomic: {
5152 const AtomicType *AT = T->castAs<AtomicType>();
5153 S += 'A';
5154 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5155 false, false);
5156 return;
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00005157 }
John McCall3624e9e2012-12-20 02:45:14 +00005158
5159 // encoding for pointer or reference types.
5160 case Type::Pointer:
5161 case Type::LValueReference:
5162 case Type::RValueReference: {
5163 QualType PointeeTy;
5164 if (isa<PointerType>(CT)) {
5165 const PointerType *PT = T->castAs<PointerType>();
5166 if (PT->isObjCSelType()) {
5167 S += ':';
5168 return;
5169 }
5170 PointeeTy = PT->getPointeeType();
5171 } else {
5172 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5173 }
5174
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005175 bool isReadOnly = false;
5176 // For historical/compatibility reasons, the read-only qualifier of the
5177 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5178 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00005179 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00005180 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005181 if (OutermostType && T.isConstQualified()) {
5182 isReadOnly = true;
5183 S += 'r';
5184 }
Mike Stump9fdbab32009-07-31 02:02:20 +00005185 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005186 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00005187 while (P->getAs<PointerType>())
5188 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005189 if (P.isConstQualified()) {
5190 isReadOnly = true;
5191 S += 'r';
5192 }
5193 }
5194 if (isReadOnly) {
5195 // Another legacy compatibility encoding. Some ObjC qualifier and type
5196 // combinations need to be rearranged.
5197 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00005198 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00005199 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005200 }
Mike Stump1eb44332009-09-09 15:08:12 +00005201
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005202 if (PointeeTy->isCharType()) {
5203 // char pointer types should be encoded as '*' unless it is a
5204 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00005205 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005206 S += '*';
5207 return;
5208 }
Ted Kremenek6217b802009-07-29 21:53:49 +00005209 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00005210 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5211 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5212 S += '#';
5213 return;
5214 }
5215 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5216 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5217 S += '@';
5218 return;
5219 }
5220 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005221 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005222 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005223 getLegacyIntegralTypeEncoding(PointeeTy);
5224
Mike Stump1eb44332009-09-09 15:08:12 +00005225 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005226 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005227 return;
5228 }
John McCall3624e9e2012-12-20 02:45:14 +00005229
5230 case Type::ConstantArray:
5231 case Type::IncompleteArray:
5232 case Type::VariableArray: {
5233 const ArrayType *AT = cast<ArrayType>(CT);
5234
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005235 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00005236 // Incomplete arrays are encoded as a pointer to the array element.
5237 S += '^';
5238
Mike Stump1eb44332009-09-09 15:08:12 +00005239 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005240 false, ExpandStructures, FD);
5241 } else {
5242 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00005243
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005244 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
5245 if (getTypeSize(CAT->getElementType()) == 0)
5246 S += '0';
5247 else
5248 S += llvm::utostr(CAT->getSize().getZExtValue());
5249 } else {
Anders Carlsson559a8332009-02-22 01:38:57 +00005250 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005251 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5252 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00005253 S += '0';
5254 }
Mike Stump1eb44332009-09-09 15:08:12 +00005255
5256 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005257 false, ExpandStructures, FD);
5258 S += ']';
5259 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005260 return;
5261 }
Mike Stump1eb44332009-09-09 15:08:12 +00005262
John McCall3624e9e2012-12-20 02:45:14 +00005263 case Type::FunctionNoProto:
5264 case Type::FunctionProto:
Anders Carlssonc0a87b72007-10-30 00:06:20 +00005265 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005266 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005267
John McCall3624e9e2012-12-20 02:45:14 +00005268 case Type::Record: {
5269 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005270 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005271 // Anonymous structures print as '?'
5272 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5273 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005274 if (ClassTemplateSpecializationDecl *Spec
5275 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5276 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer5eada842013-02-22 15:46:01 +00005277 llvm::raw_string_ostream OS(S);
5278 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor910f8002010-11-07 23:05:16 +00005279 TemplateArgs.data(),
5280 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00005281 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005282 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005283 } else {
5284 S += '?';
5285 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00005286 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005287 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005288 if (!RDecl->isUnion()) {
5289 getObjCEncodingForStructureImpl(RDecl, S, FD);
5290 } else {
5291 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5292 FieldEnd = RDecl->field_end();
5293 Field != FieldEnd; ++Field) {
5294 if (FD) {
5295 S += '"';
5296 S += Field->getNameAsString();
5297 S += '"';
5298 }
Mike Stump1eb44332009-09-09 15:08:12 +00005299
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005300 // Special case bit-fields.
5301 if (Field->isBitField()) {
5302 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie581deb32012-06-06 20:45:41 +00005303 *Field);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005304 } else {
5305 QualType qt = Field->getType();
5306 getLegacyIntegralTypeEncoding(qt);
5307 getObjCEncodingForTypeImpl(qt, S, false, true,
5308 FD, /*OutermostType*/false,
5309 /*EncodingProperty*/false,
5310 /*StructField*/true);
5311 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005312 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005313 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00005314 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005315 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005316 return;
5317 }
Mike Stump1eb44332009-09-09 15:08:12 +00005318
John McCall3624e9e2012-12-20 02:45:14 +00005319 case Type::BlockPointer: {
5320 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff21a98b12009-02-02 18:24:29 +00005321 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00005322 if (EncodeBlockParameters) {
John McCall3624e9e2012-12-20 02:45:14 +00005323 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilsondc8dab62011-11-30 01:57:58 +00005324
5325 S += '<';
5326 // Block return type
5327 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5328 ExpandPointedToStructures, ExpandStructures,
5329 FD,
5330 false /* OutermostType */,
5331 EncodingProperty,
5332 false /* StructField */,
5333 EncodeBlockParameters,
5334 EncodeClassNames);
5335 // Block self
5336 S += "@?";
5337 // Block parameters
5338 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5339 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5340 E = FPT->arg_type_end(); I && (I != E); ++I) {
5341 getObjCEncodingForTypeImpl(*I, S,
5342 ExpandPointedToStructures,
5343 ExpandStructures,
5344 FD,
5345 false /* OutermostType */,
5346 EncodingProperty,
5347 false /* StructField */,
5348 EncodeBlockParameters,
5349 EncodeClassNames);
5350 }
5351 }
5352 S += '>';
5353 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005354 return;
5355 }
Mike Stump1eb44332009-09-09 15:08:12 +00005356
John McCall3624e9e2012-12-20 02:45:14 +00005357 case Type::ObjCObject:
5358 case Type::ObjCInterface: {
5359 // Ignore protocol qualifiers when mangling at this level.
5360 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCallc12c5bb2010-05-15 11:32:37 +00005361
John McCall3624e9e2012-12-20 02:45:14 +00005362 // The assumption seems to be that this assert will succeed
5363 // because nested levels will have filtered out 'id' and 'Class'.
5364 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005365 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00005366 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005367 S += '{';
5368 const IdentifierInfo *II = OI->getIdentifier();
5369 S += II->getName();
5370 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00005371 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005372 DeepCollectObjCIvars(OI, true, Ivars);
5373 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00005374 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005375 if (Field->isBitField())
5376 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005377 else
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005378 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5379 false, false, false, false, false,
5380 EncodePointerToObjCTypedef);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005381 }
5382 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005383 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005384 }
Mike Stump1eb44332009-09-09 15:08:12 +00005385
John McCall3624e9e2012-12-20 02:45:14 +00005386 case Type::ObjCObjectPointer: {
5387 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00005388 if (OPT->isObjCIdType()) {
5389 S += '@';
5390 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005391 }
Mike Stump1eb44332009-09-09 15:08:12 +00005392
Steve Naroff27d20a22009-10-28 22:03:49 +00005393 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5394 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5395 // Since this is a binary compatibility issue, need to consult with runtime
5396 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00005397 S += '#';
5398 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005399 }
Mike Stump1eb44332009-09-09 15:08:12 +00005400
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005401 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005402 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00005403 ExpandPointedToStructures,
5404 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00005405 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00005406 // Note that we do extended encoding of protocol qualifer list
5407 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00005408 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005409 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5410 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00005411 S += '<';
5412 S += (*I)->getNameAsString();
5413 S += '>';
5414 }
5415 S += '"';
5416 }
5417 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005418 }
Mike Stump1eb44332009-09-09 15:08:12 +00005419
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005420 QualType PointeeTy = OPT->getPointeeType();
5421 if (!EncodingProperty &&
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005422 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5423 !EncodePointerToObjCTypedef) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005424 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00005425 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005426 // {...};
5427 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00005428 getObjCEncodingForTypeImpl(PointeeTy, S,
5429 false, ExpandPointedToStructures,
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005430 NULL,
5431 false, false, false, false, false,
5432 /*EncodePointerToObjCTypedef*/true);
Steve Naroff14108da2009-07-10 23:34:53 +00005433 return;
5434 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005435
5436 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00005437 if (OPT->getInterfaceDecl() &&
5438 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005439 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00005440 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005441 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5442 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005443 S += '<';
5444 S += (*I)->getNameAsString();
5445 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00005446 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005447 S += '"';
5448 }
5449 return;
5450 }
Mike Stump1eb44332009-09-09 15:08:12 +00005451
John McCall532ec7b2010-05-17 23:56:34 +00005452 // gcc just blithely ignores member pointers.
John McCall3624e9e2012-12-20 02:45:14 +00005453 // FIXME: we shoul do better than that. 'M' is available.
5454 case Type::MemberPointer:
John McCall532ec7b2010-05-17 23:56:34 +00005455 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005456
John McCall3624e9e2012-12-20 02:45:14 +00005457 case Type::Vector:
5458 case Type::ExtVector:
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005459 // This matches gcc's encoding, even though technically it is
5460 // insufficient.
5461 // FIXME. We should do a better job than gcc.
5462 return;
John McCall3624e9e2012-12-20 02:45:14 +00005463
Richard Smithdc7a4f52013-04-30 13:56:41 +00005464 case Type::Auto:
5465 // We could see an undeduced auto type here during error recovery.
5466 // Just ignore it.
5467 return;
5468
John McCall3624e9e2012-12-20 02:45:14 +00005469#define ABSTRACT_TYPE(KIND, BASE)
5470#define TYPE(KIND, BASE)
5471#define DEPENDENT_TYPE(KIND, BASE) \
5472 case Type::KIND:
5473#define NON_CANONICAL_TYPE(KIND, BASE) \
5474 case Type::KIND:
5475#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5476 case Type::KIND:
5477#include "clang/AST/TypeNodes.def"
5478 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005479 }
John McCall3624e9e2012-12-20 02:45:14 +00005480 llvm_unreachable("bad type kind!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005481}
5482
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005483void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5484 std::string &S,
5485 const FieldDecl *FD,
5486 bool includeVBases) const {
5487 assert(RDecl && "Expected non-null RecordDecl");
5488 assert(!RDecl->isUnion() && "Should not be called for unions");
5489 if (!RDecl->getDefinition())
5490 return;
5491
5492 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5493 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5494 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5495
5496 if (CXXRec) {
5497 for (CXXRecordDecl::base_class_iterator
5498 BI = CXXRec->bases_begin(),
5499 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5500 if (!BI->isVirtual()) {
5501 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005502 if (base->isEmpty())
5503 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005504 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005505 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5506 std::make_pair(offs, base));
5507 }
5508 }
5509 }
5510
5511 unsigned i = 0;
5512 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5513 FieldEnd = RDecl->field_end();
5514 Field != FieldEnd; ++Field, ++i) {
5515 uint64_t offs = layout.getFieldOffset(i);
5516 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie581deb32012-06-06 20:45:41 +00005517 std::make_pair(offs, *Field));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005518 }
5519
5520 if (CXXRec && includeVBases) {
5521 for (CXXRecordDecl::base_class_iterator
5522 BI = CXXRec->vbases_begin(),
5523 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5524 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005525 if (base->isEmpty())
5526 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005527 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00005528 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5529 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5530 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005531 }
5532 }
5533
5534 CharUnits size;
5535 if (CXXRec) {
5536 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5537 } else {
5538 size = layout.getSize();
5539 }
5540
5541 uint64_t CurOffs = 0;
5542 std::multimap<uint64_t, NamedDecl *>::iterator
5543 CurLayObj = FieldOrBaseOffsets.begin();
5544
Douglas Gregor58db7a52012-04-27 22:30:01 +00005545 if (CXXRec && CXXRec->isDynamicClass() &&
5546 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005547 if (FD) {
5548 S += "\"_vptr$";
5549 std::string recname = CXXRec->getNameAsString();
5550 if (recname.empty()) recname = "?";
5551 S += recname;
5552 S += '"';
5553 }
5554 S += "^^?";
5555 CurOffs += getTypeSize(VoidPtrTy);
5556 }
5557
5558 if (!RDecl->hasFlexibleArrayMember()) {
5559 // Mark the end of the structure.
5560 uint64_t offs = toBits(size);
5561 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5562 std::make_pair(offs, (NamedDecl*)0));
5563 }
5564
5565 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5566 assert(CurOffs <= CurLayObj->first);
5567
5568 if (CurOffs < CurLayObj->first) {
5569 uint64_t padding = CurLayObj->first - CurOffs;
5570 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5571 // packing/alignment of members is different that normal, in which case
5572 // the encoding will be out-of-sync with the real layout.
5573 // If the runtime switches to just consider the size of types without
5574 // taking into account alignment, we could make padding explicit in the
5575 // encoding (e.g. using arrays of chars). The encoding strings would be
5576 // longer then though.
5577 CurOffs += padding;
5578 }
5579
5580 NamedDecl *dcl = CurLayObj->second;
5581 if (dcl == 0)
5582 break; // reached end of structure.
5583
5584 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5585 // We expand the bases without their virtual bases since those are going
5586 // in the initial structure. Note that this differs from gcc which
5587 // expands virtual bases each time one is encountered in the hierarchy,
5588 // making the encoding type bigger than it really is.
5589 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005590 assert(!base->isEmpty());
5591 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005592 } else {
5593 FieldDecl *field = cast<FieldDecl>(dcl);
5594 if (FD) {
5595 S += '"';
5596 S += field->getNameAsString();
5597 S += '"';
5598 }
5599
5600 if (field->isBitField()) {
5601 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005602 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005603 } else {
5604 QualType qt = field->getType();
5605 getLegacyIntegralTypeEncoding(qt);
5606 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5607 /*OutermostType*/false,
5608 /*EncodingProperty*/false,
5609 /*StructField*/true);
5610 CurOffs += getTypeSize(field->getType());
5611 }
5612 }
5613 }
5614}
5615
Mike Stump1eb44332009-09-09 15:08:12 +00005616void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00005617 std::string& S) const {
5618 if (QT & Decl::OBJC_TQ_In)
5619 S += 'n';
5620 if (QT & Decl::OBJC_TQ_Inout)
5621 S += 'N';
5622 if (QT & Decl::OBJC_TQ_Out)
5623 S += 'o';
5624 if (QT & Decl::OBJC_TQ_Bycopy)
5625 S += 'O';
5626 if (QT & Decl::OBJC_TQ_Byref)
5627 S += 'R';
5628 if (QT & Decl::OBJC_TQ_Oneway)
5629 S += 'V';
5630}
5631
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00005632TypedefDecl *ASTContext::getObjCIdDecl() const {
5633 if (!ObjCIdDecl) {
5634 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5635 T = getObjCObjectPointerType(T);
5636 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5637 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5638 getTranslationUnitDecl(),
5639 SourceLocation(), SourceLocation(),
5640 &Idents.get("id"), IdInfo);
5641 }
5642
5643 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00005644}
5645
Douglas Gregor7a27ea52011-08-12 06:17:30 +00005646TypedefDecl *ASTContext::getObjCSelDecl() const {
5647 if (!ObjCSelDecl) {
5648 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5649 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5650 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5651 getTranslationUnitDecl(),
5652 SourceLocation(), SourceLocation(),
5653 &Idents.get("SEL"), SelInfo);
5654 }
5655 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00005656}
5657
Douglas Gregor79d67262011-08-12 05:59:41 +00005658TypedefDecl *ASTContext::getObjCClassDecl() const {
5659 if (!ObjCClassDecl) {
5660 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5661 T = getObjCObjectPointerType(T);
5662 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5663 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5664 getTranslationUnitDecl(),
5665 SourceLocation(), SourceLocation(),
5666 &Idents.get("Class"), ClassInfo);
5667 }
5668
5669 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00005670}
5671
Douglas Gregora6ea10e2012-01-17 18:09:05 +00005672ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5673 if (!ObjCProtocolClassDecl) {
5674 ObjCProtocolClassDecl
5675 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5676 SourceLocation(),
5677 &Idents.get("Protocol"),
5678 /*PrevDecl=*/0,
5679 SourceLocation(), true);
5680 }
5681
5682 return ObjCProtocolClassDecl;
5683}
5684
Meador Ingec5613b22012-06-16 03:34:49 +00005685//===----------------------------------------------------------------------===//
5686// __builtin_va_list Construction Functions
5687//===----------------------------------------------------------------------===//
5688
5689static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5690 // typedef char* __builtin_va_list;
5691 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5692 TypeSourceInfo *TInfo
5693 = Context->getTrivialTypeSourceInfo(CharPtrType);
5694
5695 TypedefDecl *VaListTypeDecl
5696 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5697 Context->getTranslationUnitDecl(),
5698 SourceLocation(), SourceLocation(),
5699 &Context->Idents.get("__builtin_va_list"),
5700 TInfo);
5701 return VaListTypeDecl;
5702}
5703
5704static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5705 // typedef void* __builtin_va_list;
5706 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5707 TypeSourceInfo *TInfo
5708 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5709
5710 TypedefDecl *VaListTypeDecl
5711 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5712 Context->getTranslationUnitDecl(),
5713 SourceLocation(), SourceLocation(),
5714 &Context->Idents.get("__builtin_va_list"),
5715 TInfo);
5716 return VaListTypeDecl;
5717}
5718
Tim Northoverc264e162013-01-31 12:13:10 +00005719static TypedefDecl *
5720CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5721 RecordDecl *VaListTagDecl;
5722 if (Context->getLangOpts().CPlusPlus) {
5723 // namespace std { struct __va_list {
5724 NamespaceDecl *NS;
5725 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5726 Context->getTranslationUnitDecl(),
5727 /*Inline*/false, SourceLocation(),
5728 SourceLocation(), &Context->Idents.get("std"),
5729 /*PrevDecl*/0);
5730
5731 VaListTagDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5732 Context->getTranslationUnitDecl(),
5733 SourceLocation(), SourceLocation(),
5734 &Context->Idents.get("__va_list"));
5735 VaListTagDecl->setDeclContext(NS);
5736 } else {
5737 // struct __va_list
5738 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5739 Context->getTranslationUnitDecl(),
5740 &Context->Idents.get("__va_list"));
5741 }
5742
5743 VaListTagDecl->startDefinition();
5744
5745 const size_t NumFields = 5;
5746 QualType FieldTypes[NumFields];
5747 const char *FieldNames[NumFields];
5748
5749 // void *__stack;
5750 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5751 FieldNames[0] = "__stack";
5752
5753 // void *__gr_top;
5754 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5755 FieldNames[1] = "__gr_top";
5756
5757 // void *__vr_top;
5758 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5759 FieldNames[2] = "__vr_top";
5760
5761 // int __gr_offs;
5762 FieldTypes[3] = Context->IntTy;
5763 FieldNames[3] = "__gr_offs";
5764
5765 // int __vr_offs;
5766 FieldTypes[4] = Context->IntTy;
5767 FieldNames[4] = "__vr_offs";
5768
5769 // Create fields
5770 for (unsigned i = 0; i < NumFields; ++i) {
5771 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5772 VaListTagDecl,
5773 SourceLocation(),
5774 SourceLocation(),
5775 &Context->Idents.get(FieldNames[i]),
5776 FieldTypes[i], /*TInfo=*/0,
5777 /*BitWidth=*/0,
5778 /*Mutable=*/false,
5779 ICIS_NoInit);
5780 Field->setAccess(AS_public);
5781 VaListTagDecl->addDecl(Field);
5782 }
5783 VaListTagDecl->completeDefinition();
5784 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5785 Context->VaListTagTy = VaListTagType;
5786
5787 // } __builtin_va_list;
5788 TypedefDecl *VaListTypedefDecl
5789 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5790 Context->getTranslationUnitDecl(),
5791 SourceLocation(), SourceLocation(),
5792 &Context->Idents.get("__builtin_va_list"),
5793 Context->getTrivialTypeSourceInfo(VaListTagType));
5794
5795 return VaListTypedefDecl;
5796}
5797
Meador Ingec5613b22012-06-16 03:34:49 +00005798static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5799 // typedef struct __va_list_tag {
5800 RecordDecl *VaListTagDecl;
5801
5802 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5803 Context->getTranslationUnitDecl(),
5804 &Context->Idents.get("__va_list_tag"));
5805 VaListTagDecl->startDefinition();
5806
5807 const size_t NumFields = 5;
5808 QualType FieldTypes[NumFields];
5809 const char *FieldNames[NumFields];
5810
5811 // unsigned char gpr;
5812 FieldTypes[0] = Context->UnsignedCharTy;
5813 FieldNames[0] = "gpr";
5814
5815 // unsigned char fpr;
5816 FieldTypes[1] = Context->UnsignedCharTy;
5817 FieldNames[1] = "fpr";
5818
5819 // unsigned short reserved;
5820 FieldTypes[2] = Context->UnsignedShortTy;
5821 FieldNames[2] = "reserved";
5822
5823 // void* overflow_arg_area;
5824 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5825 FieldNames[3] = "overflow_arg_area";
5826
5827 // void* reg_save_area;
5828 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5829 FieldNames[4] = "reg_save_area";
5830
5831 // Create fields
5832 for (unsigned i = 0; i < NumFields; ++i) {
5833 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5834 SourceLocation(),
5835 SourceLocation(),
5836 &Context->Idents.get(FieldNames[i]),
5837 FieldTypes[i], /*TInfo=*/0,
5838 /*BitWidth=*/0,
5839 /*Mutable=*/false,
5840 ICIS_NoInit);
5841 Field->setAccess(AS_public);
5842 VaListTagDecl->addDecl(Field);
5843 }
5844 VaListTagDecl->completeDefinition();
5845 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005846 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005847
5848 // } __va_list_tag;
5849 TypedefDecl *VaListTagTypedefDecl
5850 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5851 Context->getTranslationUnitDecl(),
5852 SourceLocation(), SourceLocation(),
5853 &Context->Idents.get("__va_list_tag"),
5854 Context->getTrivialTypeSourceInfo(VaListTagType));
5855 QualType VaListTagTypedefType =
5856 Context->getTypedefType(VaListTagTypedefDecl);
5857
5858 // typedef __va_list_tag __builtin_va_list[1];
5859 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5860 QualType VaListTagArrayType
5861 = Context->getConstantArrayType(VaListTagTypedefType,
5862 Size, ArrayType::Normal, 0);
5863 TypeSourceInfo *TInfo
5864 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5865 TypedefDecl *VaListTypedefDecl
5866 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5867 Context->getTranslationUnitDecl(),
5868 SourceLocation(), SourceLocation(),
5869 &Context->Idents.get("__builtin_va_list"),
5870 TInfo);
5871
5872 return VaListTypedefDecl;
5873}
5874
5875static TypedefDecl *
5876CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5877 // typedef struct __va_list_tag {
5878 RecordDecl *VaListTagDecl;
5879 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5880 Context->getTranslationUnitDecl(),
5881 &Context->Idents.get("__va_list_tag"));
5882 VaListTagDecl->startDefinition();
5883
5884 const size_t NumFields = 4;
5885 QualType FieldTypes[NumFields];
5886 const char *FieldNames[NumFields];
5887
5888 // unsigned gp_offset;
5889 FieldTypes[0] = Context->UnsignedIntTy;
5890 FieldNames[0] = "gp_offset";
5891
5892 // unsigned fp_offset;
5893 FieldTypes[1] = Context->UnsignedIntTy;
5894 FieldNames[1] = "fp_offset";
5895
5896 // void* overflow_arg_area;
5897 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5898 FieldNames[2] = "overflow_arg_area";
5899
5900 // void* reg_save_area;
5901 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5902 FieldNames[3] = "reg_save_area";
5903
5904 // Create fields
5905 for (unsigned i = 0; i < NumFields; ++i) {
5906 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5907 VaListTagDecl,
5908 SourceLocation(),
5909 SourceLocation(),
5910 &Context->Idents.get(FieldNames[i]),
5911 FieldTypes[i], /*TInfo=*/0,
5912 /*BitWidth=*/0,
5913 /*Mutable=*/false,
5914 ICIS_NoInit);
5915 Field->setAccess(AS_public);
5916 VaListTagDecl->addDecl(Field);
5917 }
5918 VaListTagDecl->completeDefinition();
5919 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005920 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005921
5922 // } __va_list_tag;
5923 TypedefDecl *VaListTagTypedefDecl
5924 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5925 Context->getTranslationUnitDecl(),
5926 SourceLocation(), SourceLocation(),
5927 &Context->Idents.get("__va_list_tag"),
5928 Context->getTrivialTypeSourceInfo(VaListTagType));
5929 QualType VaListTagTypedefType =
5930 Context->getTypedefType(VaListTagTypedefDecl);
5931
5932 // typedef __va_list_tag __builtin_va_list[1];
5933 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5934 QualType VaListTagArrayType
5935 = Context->getConstantArrayType(VaListTagTypedefType,
5936 Size, ArrayType::Normal,0);
5937 TypeSourceInfo *TInfo
5938 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5939 TypedefDecl *VaListTypedefDecl
5940 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5941 Context->getTranslationUnitDecl(),
5942 SourceLocation(), SourceLocation(),
5943 &Context->Idents.get("__builtin_va_list"),
5944 TInfo);
5945
5946 return VaListTypedefDecl;
5947}
5948
5949static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5950 // typedef int __builtin_va_list[4];
5951 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5952 QualType IntArrayType
5953 = Context->getConstantArrayType(Context->IntTy,
5954 Size, ArrayType::Normal, 0);
5955 TypedefDecl *VaListTypedefDecl
5956 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5957 Context->getTranslationUnitDecl(),
5958 SourceLocation(), SourceLocation(),
5959 &Context->Idents.get("__builtin_va_list"),
5960 Context->getTrivialTypeSourceInfo(IntArrayType));
5961
5962 return VaListTypedefDecl;
5963}
5964
Logan Chieneae5a8202012-10-10 06:56:20 +00005965static TypedefDecl *
5966CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5967 RecordDecl *VaListDecl;
5968 if (Context->getLangOpts().CPlusPlus) {
5969 // namespace std { struct __va_list {
5970 NamespaceDecl *NS;
5971 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5972 Context->getTranslationUnitDecl(),
5973 /*Inline*/false, SourceLocation(),
5974 SourceLocation(), &Context->Idents.get("std"),
5975 /*PrevDecl*/0);
5976
5977 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5978 Context->getTranslationUnitDecl(),
5979 SourceLocation(), SourceLocation(),
5980 &Context->Idents.get("__va_list"));
5981
5982 VaListDecl->setDeclContext(NS);
5983
5984 } else {
5985 // struct __va_list {
5986 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
5987 Context->getTranslationUnitDecl(),
5988 &Context->Idents.get("__va_list"));
5989 }
5990
5991 VaListDecl->startDefinition();
5992
5993 // void * __ap;
5994 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5995 VaListDecl,
5996 SourceLocation(),
5997 SourceLocation(),
5998 &Context->Idents.get("__ap"),
5999 Context->getPointerType(Context->VoidTy),
6000 /*TInfo=*/0,
6001 /*BitWidth=*/0,
6002 /*Mutable=*/false,
6003 ICIS_NoInit);
6004 Field->setAccess(AS_public);
6005 VaListDecl->addDecl(Field);
6006
6007 // };
6008 VaListDecl->completeDefinition();
6009
6010 // typedef struct __va_list __builtin_va_list;
6011 TypeSourceInfo *TInfo
6012 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
6013
6014 TypedefDecl *VaListTypeDecl
6015 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6016 Context->getTranslationUnitDecl(),
6017 SourceLocation(), SourceLocation(),
6018 &Context->Idents.get("__builtin_va_list"),
6019 TInfo);
6020
6021 return VaListTypeDecl;
6022}
6023
Ulrich Weigandb8409212013-05-06 16:26:41 +00006024static TypedefDecl *
6025CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6026 // typedef struct __va_list_tag {
6027 RecordDecl *VaListTagDecl;
6028 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
6029 Context->getTranslationUnitDecl(),
6030 &Context->Idents.get("__va_list_tag"));
6031 VaListTagDecl->startDefinition();
6032
6033 const size_t NumFields = 4;
6034 QualType FieldTypes[NumFields];
6035 const char *FieldNames[NumFields];
6036
6037 // long __gpr;
6038 FieldTypes[0] = Context->LongTy;
6039 FieldNames[0] = "__gpr";
6040
6041 // long __fpr;
6042 FieldTypes[1] = Context->LongTy;
6043 FieldNames[1] = "__fpr";
6044
6045 // void *__overflow_arg_area;
6046 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6047 FieldNames[2] = "__overflow_arg_area";
6048
6049 // void *__reg_save_area;
6050 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6051 FieldNames[3] = "__reg_save_area";
6052
6053 // Create fields
6054 for (unsigned i = 0; i < NumFields; ++i) {
6055 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6056 VaListTagDecl,
6057 SourceLocation(),
6058 SourceLocation(),
6059 &Context->Idents.get(FieldNames[i]),
6060 FieldTypes[i], /*TInfo=*/0,
6061 /*BitWidth=*/0,
6062 /*Mutable=*/false,
6063 ICIS_NoInit);
6064 Field->setAccess(AS_public);
6065 VaListTagDecl->addDecl(Field);
6066 }
6067 VaListTagDecl->completeDefinition();
6068 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6069 Context->VaListTagTy = VaListTagType;
6070
6071 // } __va_list_tag;
6072 TypedefDecl *VaListTagTypedefDecl
6073 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6074 Context->getTranslationUnitDecl(),
6075 SourceLocation(), SourceLocation(),
6076 &Context->Idents.get("__va_list_tag"),
6077 Context->getTrivialTypeSourceInfo(VaListTagType));
6078 QualType VaListTagTypedefType =
6079 Context->getTypedefType(VaListTagTypedefDecl);
6080
6081 // typedef __va_list_tag __builtin_va_list[1];
6082 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6083 QualType VaListTagArrayType
6084 = Context->getConstantArrayType(VaListTagTypedefType,
6085 Size, ArrayType::Normal,0);
6086 TypeSourceInfo *TInfo
6087 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
6088 TypedefDecl *VaListTypedefDecl
6089 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6090 Context->getTranslationUnitDecl(),
6091 SourceLocation(), SourceLocation(),
6092 &Context->Idents.get("__builtin_va_list"),
6093 TInfo);
6094
6095 return VaListTypedefDecl;
6096}
6097
Meador Ingec5613b22012-06-16 03:34:49 +00006098static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6099 TargetInfo::BuiltinVaListKind Kind) {
6100 switch (Kind) {
6101 case TargetInfo::CharPtrBuiltinVaList:
6102 return CreateCharPtrBuiltinVaListDecl(Context);
6103 case TargetInfo::VoidPtrBuiltinVaList:
6104 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northoverc264e162013-01-31 12:13:10 +00006105 case TargetInfo::AArch64ABIBuiltinVaList:
6106 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00006107 case TargetInfo::PowerABIBuiltinVaList:
6108 return CreatePowerABIBuiltinVaListDecl(Context);
6109 case TargetInfo::X86_64ABIBuiltinVaList:
6110 return CreateX86_64ABIBuiltinVaListDecl(Context);
6111 case TargetInfo::PNaClABIBuiltinVaList:
6112 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chieneae5a8202012-10-10 06:56:20 +00006113 case TargetInfo::AAPCSABIBuiltinVaList:
6114 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigandb8409212013-05-06 16:26:41 +00006115 case TargetInfo::SystemZBuiltinVaList:
6116 return CreateSystemZBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00006117 }
6118
6119 llvm_unreachable("Unhandled __builtin_va_list type kind");
6120}
6121
6122TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6123 if (!BuiltinVaListDecl)
6124 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6125
6126 return BuiltinVaListDecl;
6127}
6128
Meador Ingefb40e3f2012-07-01 15:57:25 +00006129QualType ASTContext::getVaListTagType() const {
6130 // Force the creation of VaListTagTy by building the __builtin_va_list
6131 // declaration.
6132 if (VaListTagTy.isNull())
6133 (void) getBuiltinVaListDecl();
6134
6135 return VaListTagTy;
6136}
6137
Ted Kremeneka526c5c2008-01-07 19:49:32 +00006138void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00006139 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00006140 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00006141
Ted Kremeneka526c5c2008-01-07 19:49:32 +00006142 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00006143}
6144
John McCall0bd6feb2009-12-02 08:04:21 +00006145/// \brief Retrieve the template name that corresponds to a non-empty
6146/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00006147TemplateName
6148ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6149 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00006150 unsigned size = End - Begin;
6151 assert(size > 1 && "set is not overloaded!");
6152
6153 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6154 size * sizeof(FunctionTemplateDecl*));
6155 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6156
6157 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00006158 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00006159 NamedDecl *D = *I;
6160 assert(isa<FunctionTemplateDecl>(D) ||
6161 (isa<UsingShadowDecl>(D) &&
6162 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6163 *Storage++ = D;
6164 }
6165
6166 return TemplateName(OT);
6167}
6168
Douglas Gregor7532dc62009-03-30 22:58:21 +00006169/// \brief Retrieve the template name that represents a qualified
6170/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00006171TemplateName
6172ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6173 bool TemplateKeyword,
6174 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00006175 assert(NNS && "Missing nested-name-specifier in qualified template name");
6176
Douglas Gregor789b1f62010-02-04 18:10:26 +00006177 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00006178 llvm::FoldingSetNodeID ID;
6179 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6180
6181 void *InsertPos = 0;
6182 QualifiedTemplateName *QTN =
6183 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6184 if (!QTN) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006185 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6186 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregor7532dc62009-03-30 22:58:21 +00006187 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6188 }
6189
6190 return TemplateName(QTN);
6191}
6192
6193/// \brief Retrieve the template name that represents a dependent
6194/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00006195TemplateName
6196ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6197 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00006198 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00006199 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00006200
6201 llvm::FoldingSetNodeID ID;
6202 DependentTemplateName::Profile(ID, NNS, Name);
6203
6204 void *InsertPos = 0;
6205 DependentTemplateName *QTN =
6206 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6207
6208 if (QTN)
6209 return TemplateName(QTN);
6210
6211 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6212 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006213 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6214 DependentTemplateName(NNS, Name);
Douglas Gregor7532dc62009-03-30 22:58:21 +00006215 } else {
6216 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smith2f47cab2012-08-16 01:19:31 +00006217 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6218 DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00006219 DependentTemplateName *CheckQTN =
6220 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6221 assert(!CheckQTN && "Dependent type name canonicalization broken");
6222 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00006223 }
6224
6225 DependentTemplateNames.InsertNode(QTN, InsertPos);
6226 return TemplateName(QTN);
6227}
6228
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006229/// \brief Retrieve the template name that represents a dependent
6230/// template name such as \c MetaFun::template operator+.
6231TemplateName
6232ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00006233 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006234 assert((!NNS || NNS->isDependent()) &&
6235 "Nested name specifier must be dependent");
6236
6237 llvm::FoldingSetNodeID ID;
6238 DependentTemplateName::Profile(ID, NNS, Operator);
6239
6240 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00006241 DependentTemplateName *QTN
6242 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006243
6244 if (QTN)
6245 return TemplateName(QTN);
6246
6247 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6248 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006249 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6250 DependentTemplateName(NNS, Operator);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006251 } else {
6252 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smith2f47cab2012-08-16 01:19:31 +00006253 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6254 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00006255
6256 DependentTemplateName *CheckQTN
6257 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6258 assert(!CheckQTN && "Dependent template name canonicalization broken");
6259 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006260 }
6261
6262 DependentTemplateNames.InsertNode(QTN, InsertPos);
6263 return TemplateName(QTN);
6264}
6265
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006266TemplateName
John McCall14606042011-06-30 08:33:18 +00006267ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6268 TemplateName replacement) const {
6269 llvm::FoldingSetNodeID ID;
6270 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6271
6272 void *insertPos = 0;
6273 SubstTemplateTemplateParmStorage *subst
6274 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6275
6276 if (!subst) {
6277 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6278 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6279 }
6280
6281 return TemplateName(subst);
6282}
6283
6284TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006285ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6286 const TemplateArgument &ArgPack) const {
6287 ASTContext &Self = const_cast<ASTContext &>(*this);
6288 llvm::FoldingSetNodeID ID;
6289 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6290
6291 void *InsertPos = 0;
6292 SubstTemplateTemplateParmPackStorage *Subst
6293 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6294
6295 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00006296 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006297 ArgPack.pack_size(),
6298 ArgPack.pack_begin());
6299 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6300 }
6301
6302 return TemplateName(Subst);
6303}
6304
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006305/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00006306/// TargetInfo, produce the corresponding type. The unsigned @p Type
6307/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00006308CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006309 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00006310 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006311 case TargetInfo::SignedShort: return ShortTy;
6312 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6313 case TargetInfo::SignedInt: return IntTy;
6314 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6315 case TargetInfo::SignedLong: return LongTy;
6316 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6317 case TargetInfo::SignedLongLong: return LongLongTy;
6318 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6319 }
6320
David Blaikieb219cfc2011-09-23 05:06:16 +00006321 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006322}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00006323
6324//===----------------------------------------------------------------------===//
6325// Type Predicates.
6326//===----------------------------------------------------------------------===//
6327
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006328/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6329/// garbage collection attribute.
6330///
John McCallae278a32011-01-12 00:34:59 +00006331Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006332 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00006333 return Qualifiers::GCNone;
6334
David Blaikie4e4d0842012-03-11 07:00:24 +00006335 assert(getLangOpts().ObjC1);
John McCallae278a32011-01-12 00:34:59 +00006336 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6337
6338 // Default behaviour under objective-C's gc is for ObjC pointers
6339 // (or pointers to them) be treated as though they were declared
6340 // as __strong.
6341 if (GCAttrs == Qualifiers::GCNone) {
6342 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6343 return Qualifiers::Strong;
6344 else if (Ty->isPointerType())
6345 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6346 } else {
6347 // It's not valid to set GC attributes on anything that isn't a
6348 // pointer.
6349#ifndef NDEBUG
6350 QualType CT = Ty->getCanonicalTypeInternal();
6351 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6352 CT = AT->getElementType();
6353 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6354#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006355 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00006356 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006357}
6358
Chris Lattner6ac46a42008-04-07 06:51:04 +00006359//===----------------------------------------------------------------------===//
6360// Type Compatibility Testing
6361//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00006362
Mike Stump1eb44332009-09-09 15:08:12 +00006363/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006364/// compatible.
6365static bool areCompatVectorTypes(const VectorType *LHS,
6366 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00006367 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00006368 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00006369 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00006370}
6371
Douglas Gregor255210e2010-08-06 10:14:59 +00006372bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6373 QualType SecondVec) {
6374 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6375 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6376
6377 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6378 return true;
6379
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006380 // Treat Neon vector types and most AltiVec vector types as if they are the
6381 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00006382 const VectorType *First = FirstVec->getAs<VectorType>();
6383 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006384 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00006385 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006386 First->getVectorKind() != VectorType::AltiVecPixel &&
6387 First->getVectorKind() != VectorType::AltiVecBool &&
6388 Second->getVectorKind() != VectorType::AltiVecPixel &&
6389 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00006390 return true;
6391
6392 return false;
6393}
6394
Steve Naroff4084c302009-07-23 01:01:38 +00006395//===----------------------------------------------------------------------===//
6396// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6397//===----------------------------------------------------------------------===//
6398
6399/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6400/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00006401bool
6402ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6403 ObjCProtocolDecl *rProto) const {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00006404 if (declaresSameEntity(lProto, rProto))
Steve Naroff4084c302009-07-23 01:01:38 +00006405 return true;
6406 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6407 E = rProto->protocol_end(); PI != E; ++PI)
6408 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6409 return true;
6410 return false;
6411}
6412
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00006413/// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
Steve Naroff4084c302009-07-23 01:01:38 +00006414/// return true if lhs's protocols conform to rhs's protocol; false
6415/// otherwise.
6416bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
6417 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
6418 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
6419 return false;
6420}
6421
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00006422/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6423/// Class<pr1, ...>.
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006424bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6425 QualType rhs) {
6426 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6427 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6428 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6429
6430 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6431 E = lhsQID->qual_end(); I != E; ++I) {
6432 bool match = false;
6433 ObjCProtocolDecl *lhsProto = *I;
6434 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6435 E = rhsOPT->qual_end(); J != E; ++J) {
6436 ObjCProtocolDecl *rhsProto = *J;
6437 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6438 match = true;
6439 break;
6440 }
6441 }
6442 if (!match)
6443 return false;
6444 }
6445 return true;
6446}
6447
Steve Naroff4084c302009-07-23 01:01:38 +00006448/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6449/// ObjCQualifiedIDType.
6450bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6451 bool compare) {
6452 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00006453 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006454 lhs->isObjCIdType() || lhs->isObjCClassType())
6455 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006456 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006457 rhs->isObjCIdType() || rhs->isObjCClassType())
6458 return true;
6459
6460 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00006461 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006462
Steve Naroff4084c302009-07-23 01:01:38 +00006463 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006464
Steve Naroff4084c302009-07-23 01:01:38 +00006465 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006466 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00006467 // make sure we check the class hierarchy.
6468 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6469 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6470 E = lhsQID->qual_end(); I != E; ++I) {
6471 // when comparing an id<P> on lhs with a static type on rhs,
6472 // see if static class implements all of id's protocols, directly or
6473 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006474 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00006475 return false;
6476 }
6477 }
6478 // If there are no qualifiers and no interface, we have an 'id'.
6479 return true;
6480 }
Mike Stump1eb44332009-09-09 15:08:12 +00006481 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006482 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6483 E = lhsQID->qual_end(); I != E; ++I) {
6484 ObjCProtocolDecl *lhsProto = *I;
6485 bool match = false;
6486
6487 // when comparing an id<P> on lhs with a static type on rhs,
6488 // see if static class implements all of id's protocols, directly or
6489 // through its super class and categories.
6490 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6491 E = rhsOPT->qual_end(); J != E; ++J) {
6492 ObjCProtocolDecl *rhsProto = *J;
6493 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6494 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6495 match = true;
6496 break;
6497 }
6498 }
Mike Stump1eb44332009-09-09 15:08:12 +00006499 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00006500 // make sure we check the class hierarchy.
6501 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6502 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6503 E = lhsQID->qual_end(); I != E; ++I) {
6504 // when comparing an id<P> on lhs with a static type on rhs,
6505 // see if static class implements all of id's protocols, directly or
6506 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006507 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00006508 match = true;
6509 break;
6510 }
6511 }
6512 }
6513 if (!match)
6514 return false;
6515 }
Mike Stump1eb44332009-09-09 15:08:12 +00006516
Steve Naroff4084c302009-07-23 01:01:38 +00006517 return true;
6518 }
Mike Stump1eb44332009-09-09 15:08:12 +00006519
Steve Naroff4084c302009-07-23 01:01:38 +00006520 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6521 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6522
Mike Stump1eb44332009-09-09 15:08:12 +00006523 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00006524 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006525 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006526 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6527 E = lhsOPT->qual_end(); I != E; ++I) {
6528 ObjCProtocolDecl *lhsProto = *I;
6529 bool match = false;
6530
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006531 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00006532 // see if static class implements all of id's protocols, directly or
6533 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006534 // First, lhs protocols in the qualifier list must be found, direct
6535 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00006536 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6537 E = rhsQID->qual_end(); J != E; ++J) {
6538 ObjCProtocolDecl *rhsProto = *J;
6539 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6540 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6541 match = true;
6542 break;
6543 }
6544 }
6545 if (!match)
6546 return false;
6547 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006548
6549 // Static class's protocols, or its super class or category protocols
6550 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6551 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6552 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6553 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6554 // This is rather dubious but matches gcc's behavior. If lhs has
6555 // no type qualifier and its class has no static protocol(s)
6556 // assume that it is mismatch.
6557 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6558 return false;
6559 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6560 LHSInheritedProtocols.begin(),
6561 E = LHSInheritedProtocols.end(); I != E; ++I) {
6562 bool match = false;
6563 ObjCProtocolDecl *lhsProto = (*I);
6564 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6565 E = rhsQID->qual_end(); J != E; ++J) {
6566 ObjCProtocolDecl *rhsProto = *J;
6567 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6568 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6569 match = true;
6570 break;
6571 }
6572 }
6573 if (!match)
6574 return false;
6575 }
6576 }
Steve Naroff4084c302009-07-23 01:01:38 +00006577 return true;
6578 }
6579 return false;
6580}
6581
Eli Friedman3d815e72008-08-22 00:56:42 +00006582/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006583/// compatible for assignment from RHS to LHS. This handles validation of any
6584/// protocol qualifiers on the LHS or RHS.
6585///
Steve Naroff14108da2009-07-10 23:34:53 +00006586bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6587 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00006588 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6589 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6590
Steve Naroffde2e22d2009-07-15 18:40:39 +00006591 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00006592 if (LHS->isObjCUnqualifiedIdOrClass() ||
6593 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00006594 return true;
6595
John McCallc12c5bb2010-05-15 11:32:37 +00006596 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00006597 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6598 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00006599 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006600
6601 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6602 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6603 QualType(RHSOPT,0));
6604
John McCallc12c5bb2010-05-15 11:32:37 +00006605 // If we have 2 user-defined types, fall into that path.
6606 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00006607 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006608
Steve Naroff4084c302009-07-23 01:01:38 +00006609 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006610}
6611
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006612/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00006613/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006614/// arguments in block literals. When passed as arguments, passing 'A*' where
6615/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6616/// not OK. For the return type, the opposite is not OK.
6617bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6618 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006619 const ObjCObjectPointerType *RHSOPT,
6620 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006621 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006622 return true;
6623
6624 if (LHSOPT->isObjCBuiltinType()) {
6625 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6626 }
6627
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006628 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006629 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6630 QualType(RHSOPT,0),
6631 false);
6632
6633 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6634 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6635 if (LHS && RHS) { // We have 2 user-defined types.
6636 if (LHS != RHS) {
6637 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006638 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006639 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006640 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006641 }
6642 else
6643 return true;
6644 }
6645 return false;
6646}
6647
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006648/// getIntersectionOfProtocols - This routine finds the intersection of set
6649/// of protocols inherited from two distinct objective-c pointer objects.
6650/// It is used to build composite qualifier list of the composite type of
6651/// the conditional expression involving two objective-c pointer objects.
6652static
6653void getIntersectionOfProtocols(ASTContext &Context,
6654 const ObjCObjectPointerType *LHSOPT,
6655 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006656 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006657
John McCallc12c5bb2010-05-15 11:32:37 +00006658 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6659 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6660 assert(LHS->getInterface() && "LHS must have an interface base");
6661 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006662
6663 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6664 unsigned LHSNumProtocols = LHS->getNumProtocols();
6665 if (LHSNumProtocols > 0)
6666 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6667 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006668 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006669 Context.CollectInheritedProtocols(LHS->getInterface(),
6670 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006671 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6672 LHSInheritedProtocols.end());
6673 }
6674
6675 unsigned RHSNumProtocols = RHS->getNumProtocols();
6676 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00006677 ObjCProtocolDecl **RHSProtocols =
6678 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006679 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6680 if (InheritedProtocolSet.count(RHSProtocols[i]))
6681 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00006682 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006683 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006684 Context.CollectInheritedProtocols(RHS->getInterface(),
6685 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006686 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6687 RHSInheritedProtocols.begin(),
6688 E = RHSInheritedProtocols.end(); I != E; ++I)
6689 if (InheritedProtocolSet.count((*I)))
6690 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006691 }
6692}
6693
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006694/// areCommonBaseCompatible - Returns common base class of the two classes if
6695/// one found. Note that this is O'2 algorithm. But it will be called as the
6696/// last type comparison in a ?-exp of ObjC pointer types before a
6697/// warning is issued. So, its invokation is extremely rare.
6698QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00006699 const ObjCObjectPointerType *Lptr,
6700 const ObjCObjectPointerType *Rptr) {
6701 const ObjCObjectType *LHS = Lptr->getObjectType();
6702 const ObjCObjectType *RHS = Rptr->getObjectType();
6703 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6704 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor60ef3082011-12-15 00:29:59 +00006705 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006706 return QualType();
6707
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006708 do {
John McCallc12c5bb2010-05-15 11:32:37 +00006709 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006710 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006711 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006712 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6713
6714 QualType Result = QualType(LHS, 0);
6715 if (!Protocols.empty())
6716 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6717 Result = getObjCObjectPointerType(Result);
6718 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006719 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006720 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006721
6722 return QualType();
6723}
6724
John McCallc12c5bb2010-05-15 11:32:37 +00006725bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6726 const ObjCObjectType *RHS) {
6727 assert(LHS->getInterface() && "LHS is not an interface type");
6728 assert(RHS->getInterface() && "RHS is not an interface type");
6729
Chris Lattner6ac46a42008-04-07 06:51:04 +00006730 // Verify that the base decls are compatible: the RHS must be a subclass of
6731 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00006732 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00006733 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006734
Chris Lattner6ac46a42008-04-07 06:51:04 +00006735 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6736 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00006737 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00006738 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006739
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006740 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6741 // more detailed analysis is required.
6742 if (RHS->getNumProtocols() == 0) {
6743 // OK, if LHS is a superclass of RHS *and*
6744 // this superclass is assignment compatible with LHS.
6745 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006746 bool IsSuperClass =
6747 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6748 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006749 // OK if conversion of LHS to SuperClass results in narrowing of types
6750 // ; i.e., SuperClass may implement at least one of the protocols
6751 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6752 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6753 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006754 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006755 // If super class has no protocols, it is not a match.
6756 if (SuperClassInheritedProtocols.empty())
6757 return false;
6758
6759 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6760 LHSPE = LHS->qual_end();
6761 LHSPI != LHSPE; LHSPI++) {
6762 bool SuperImplementsProtocol = false;
6763 ObjCProtocolDecl *LHSProto = (*LHSPI);
6764
6765 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6766 SuperClassInheritedProtocols.begin(),
6767 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6768 ObjCProtocolDecl *SuperClassProto = (*I);
6769 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6770 SuperImplementsProtocol = true;
6771 break;
6772 }
6773 }
6774 if (!SuperImplementsProtocol)
6775 return false;
6776 }
6777 return true;
6778 }
6779 return false;
6780 }
Mike Stump1eb44332009-09-09 15:08:12 +00006781
John McCallc12c5bb2010-05-15 11:32:37 +00006782 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6783 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006784 LHSPI != LHSPE; LHSPI++) {
6785 bool RHSImplementsProtocol = false;
6786
6787 // If the RHS doesn't implement the protocol on the left, the types
6788 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00006789 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6790 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00006791 RHSPI != RHSPE; RHSPI++) {
6792 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006793 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00006794 break;
6795 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006796 }
6797 // FIXME: For better diagnostics, consider passing back the protocol name.
6798 if (!RHSImplementsProtocol)
6799 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006800 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006801 // The RHS implements all protocols listed on the LHS.
6802 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006803}
6804
Steve Naroff389bf462009-02-12 17:52:19 +00006805bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6806 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00006807 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6808 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006809
Steve Naroff14108da2009-07-10 23:34:53 +00006810 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00006811 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006812
6813 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6814 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00006815}
6816
Douglas Gregor569c3162010-08-07 11:51:51 +00006817bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6818 return canAssignObjCInterfaces(
6819 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6820 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6821}
6822
Mike Stump1eb44332009-09-09 15:08:12 +00006823/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00006824/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00006825/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00006826/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00006827bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6828 bool CompareUnqualified) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006829 if (getLangOpts().CPlusPlus)
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006830 return hasSameType(LHS, RHS);
6831
Douglas Gregor447234d2010-07-29 15:18:02 +00006832 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00006833}
6834
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006835bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00006836 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006837}
6838
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006839bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6840 return !mergeTypes(LHS, RHS, true).isNull();
6841}
6842
Peter Collingbourne48466752010-10-24 18:30:18 +00006843/// mergeTransparentUnionType - if T is a transparent union type and a member
6844/// of T is compatible with SubType, return the merged type, else return
6845/// QualType()
6846QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6847 bool OfBlockPointer,
6848 bool Unqualified) {
6849 if (const RecordType *UT = T->getAsUnionType()) {
6850 RecordDecl *UD = UT->getDecl();
6851 if (UD->hasAttr<TransparentUnionAttr>()) {
6852 for (RecordDecl::field_iterator it = UD->field_begin(),
6853 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00006854 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006855 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6856 if (!MT.isNull())
6857 return MT;
6858 }
6859 }
6860 }
6861
6862 return QualType();
6863}
6864
6865/// mergeFunctionArgumentTypes - merge two types which appear as function
6866/// argument types
6867QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6868 bool OfBlockPointer,
6869 bool Unqualified) {
6870 // GNU extension: two types are compatible if they appear as a function
6871 // argument, one of the types is a transparent union type and the other
6872 // type is compatible with a union member
6873 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6874 Unqualified);
6875 if (!lmerge.isNull())
6876 return lmerge;
6877
6878 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6879 Unqualified);
6880 if (!rmerge.isNull())
6881 return rmerge;
6882
6883 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6884}
6885
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006886QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00006887 bool OfBlockPointer,
6888 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00006889 const FunctionType *lbase = lhs->getAs<FunctionType>();
6890 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00006891 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6892 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00006893 bool allLTypes = true;
6894 bool allRTypes = true;
6895
6896 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006897 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006898 if (OfBlockPointer) {
6899 QualType RHS = rbase->getResultType();
6900 QualType LHS = lbase->getResultType();
6901 bool UnqualifiedResult = Unqualified;
6902 if (!UnqualifiedResult)
6903 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006904 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006905 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006906 else
John McCall8cc246c2010-12-15 01:06:38 +00006907 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6908 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006909 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006910
6911 if (Unqualified)
6912 retType = retType.getUnqualifiedType();
6913
6914 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6915 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6916 if (Unqualified) {
6917 LRetType = LRetType.getUnqualifiedType();
6918 RRetType = RRetType.getUnqualifiedType();
6919 }
6920
6921 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006922 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00006923 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006924 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00006925
Daniel Dunbar6a15c852010-04-28 16:20:58 +00006926 // FIXME: double check this
6927 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6928 // rbase->getRegParmAttr() != 0 &&
6929 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00006930 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6931 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00006932
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006933 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00006934 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006935 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006936
John McCall8cc246c2010-12-15 01:06:38 +00006937 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00006938 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6939 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00006940 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6941 return QualType();
6942
John McCallf85e1932011-06-15 23:02:42 +00006943 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6944 return QualType();
6945
John McCall8cc246c2010-12-15 01:06:38 +00006946 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6947 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00006948
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00006949 if (lbaseInfo.getNoReturn() != NoReturn)
6950 allLTypes = false;
6951 if (rbaseInfo.getNoReturn() != NoReturn)
6952 allRTypes = false;
6953
John McCallf85e1932011-06-15 23:02:42 +00006954 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00006955
Eli Friedman3d815e72008-08-22 00:56:42 +00006956 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00006957 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6958 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006959 unsigned lproto_nargs = lproto->getNumArgs();
6960 unsigned rproto_nargs = rproto->getNumArgs();
6961
6962 // Compatible functions must have the same number of arguments
6963 if (lproto_nargs != rproto_nargs)
6964 return QualType();
6965
6966 // Variadic and non-variadic functions aren't compatible
6967 if (lproto->isVariadic() != rproto->isVariadic())
6968 return QualType();
6969
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00006970 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6971 return QualType();
6972
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006973 if (LangOpts.ObjCAutoRefCount &&
6974 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6975 return QualType();
6976
Eli Friedman3d815e72008-08-22 00:56:42 +00006977 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00006978 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00006979 for (unsigned i = 0; i < lproto_nargs; i++) {
6980 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6981 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006982 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6983 OfBlockPointer,
6984 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006985 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006986
6987 if (Unqualified)
6988 argtype = argtype.getUnqualifiedType();
6989
Eli Friedman3d815e72008-08-22 00:56:42 +00006990 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00006991 if (Unqualified) {
6992 largtype = largtype.getUnqualifiedType();
6993 rargtype = rargtype.getUnqualifiedType();
6994 }
6995
Chris Lattner61710852008-10-05 17:34:18 +00006996 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6997 allLTypes = false;
6998 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6999 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00007000 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00007001
Eli Friedman3d815e72008-08-22 00:56:42 +00007002 if (allLTypes) return lhs;
7003 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00007004
7005 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7006 EPI.ExtInfo = einfo;
Jordan Rosebea522f2013-03-08 21:51:21 +00007007 return getFunctionType(retType, types, EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00007008 }
7009
7010 if (lproto) allRTypes = false;
7011 if (rproto) allLTypes = false;
7012
Douglas Gregor72564e72009-02-26 23:50:07 +00007013 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00007014 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00007015 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00007016 if (proto->isVariadic()) return QualType();
7017 // Check that the types are compatible with the types that
7018 // would result from default argument promotions (C99 6.7.5.3p15).
7019 // The only types actually affected are promotable integer
7020 // types and floats, which would be passed as a different
7021 // type depending on whether the prototype is visible.
7022 unsigned proto_nargs = proto->getNumArgs();
7023 for (unsigned i = 0; i < proto_nargs; ++i) {
7024 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007025
Eli Friedmanc586d5d2012-08-30 00:44:15 +00007026 // Look at the converted type of enum types, since that is the type used
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007027 // to pass enum values.
Eli Friedmanc586d5d2012-08-30 00:44:15 +00007028 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
7029 argTy = Enum->getDecl()->getIntegerType();
7030 if (argTy.isNull())
7031 return QualType();
7032 }
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007033
Eli Friedman3d815e72008-08-22 00:56:42 +00007034 if (argTy->isPromotableIntegerType() ||
7035 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
7036 return QualType();
7037 }
7038
7039 if (allLTypes) return lhs;
7040 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00007041
7042 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7043 EPI.ExtInfo = einfo;
Jordan Rosebea522f2013-03-08 21:51:21 +00007044 return getFunctionType(retType,
7045 ArrayRef<QualType>(proto->arg_type_begin(),
7046 proto->getNumArgs()),
7047 EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00007048 }
7049
7050 if (allLTypes) return lhs;
7051 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00007052 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00007053}
7054
John McCallb9da7132013-03-21 00:10:07 +00007055/// Given that we have an enum type and a non-enum type, try to merge them.
7056static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7057 QualType other, bool isBlockReturnType) {
7058 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7059 // a signed integer type, or an unsigned integer type.
7060 // Compatibility is based on the underlying type, not the promotion
7061 // type.
7062 QualType underlyingType = ET->getDecl()->getIntegerType();
7063 if (underlyingType.isNull()) return QualType();
7064 if (Context.hasSameType(underlyingType, other))
7065 return other;
7066
7067 // In block return types, we're more permissive and accept any
7068 // integral type of the same size.
7069 if (isBlockReturnType && other->isIntegerType() &&
7070 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7071 return other;
7072
7073 return QualType();
7074}
7075
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007076QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00007077 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00007078 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00007079 // C++ [expr]: If an expression initially has the type "reference to T", the
7080 // type is adjusted to "T" prior to any further analysis, the expression
7081 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00007082 // expression is an lvalue unless the reference is an rvalue reference and
7083 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00007084 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7085 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00007086
7087 if (Unqualified) {
7088 LHS = LHS.getUnqualifiedType();
7089 RHS = RHS.getUnqualifiedType();
7090 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00007091
Eli Friedman3d815e72008-08-22 00:56:42 +00007092 QualType LHSCan = getCanonicalType(LHS),
7093 RHSCan = getCanonicalType(RHS);
7094
7095 // If two types are identical, they are compatible.
7096 if (LHSCan == RHSCan)
7097 return LHS;
7098
John McCall0953e762009-09-24 19:53:00 +00007099 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00007100 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7101 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00007102 if (LQuals != RQuals) {
7103 // If any of these qualifiers are different, we have a type
7104 // mismatch.
7105 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00007106 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7107 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00007108 return QualType();
7109
7110 // Exactly one GC qualifier difference is allowed: __strong is
7111 // okay if the other type has no GC qualifier but is an Objective
7112 // C object pointer (i.e. implicitly strong by default). We fix
7113 // this by pretending that the unqualified type was actually
7114 // qualified __strong.
7115 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7116 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7117 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7118
7119 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7120 return QualType();
7121
7122 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7123 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7124 }
7125 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7126 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7127 }
Eli Friedman3d815e72008-08-22 00:56:42 +00007128 return QualType();
John McCall0953e762009-09-24 19:53:00 +00007129 }
7130
7131 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00007132
Eli Friedman852d63b2009-06-01 01:22:52 +00007133 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7134 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00007135
Chris Lattner1adb8832008-01-14 05:45:46 +00007136 // We want to consider the two function types to be the same for these
7137 // comparisons, just force one to the other.
7138 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7139 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00007140
7141 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00007142 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7143 LHSClass = Type::ConstantArray;
7144 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7145 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00007146
John McCallc12c5bb2010-05-15 11:32:37 +00007147 // ObjCInterfaces are just specialized ObjCObjects.
7148 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7149 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7150
Nate Begeman213541a2008-04-18 23:10:10 +00007151 // Canonicalize ExtVector -> Vector.
7152 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7153 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00007154
Chris Lattnera36a61f2008-04-07 05:43:21 +00007155 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00007156 if (LHSClass != RHSClass) {
John McCallb9da7132013-03-21 00:10:07 +00007157 // Note that we only have special rules for turning block enum
7158 // returns into block int returns, not vice-versa.
John McCall183700f2009-09-21 23:43:11 +00007159 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCallb9da7132013-03-21 00:10:07 +00007160 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmanbab96962008-02-12 08:46:17 +00007161 }
John McCall183700f2009-09-21 23:43:11 +00007162 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCallb9da7132013-03-21 00:10:07 +00007163 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmanbab96962008-02-12 08:46:17 +00007164 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00007165 // allow block pointer type to match an 'id' type.
Fariborz Jahanian41963632012-01-26 17:08:50 +00007166 if (OfBlockPointer && !BlockReturnType) {
7167 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7168 return LHS;
7169 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7170 return RHS;
7171 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00007172
Eli Friedman3d815e72008-08-22 00:56:42 +00007173 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00007174 }
Eli Friedman3d815e72008-08-22 00:56:42 +00007175
Steve Naroff4a746782008-01-09 22:43:08 +00007176 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00007177 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00007178#define TYPE(Class, Base)
7179#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00007180#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00007181#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7182#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7183#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00007184 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00007185
Richard Smithdc7a4f52013-04-30 13:56:41 +00007186 case Type::Auto:
Sebastian Redl7c80bd62009-03-16 23:22:08 +00007187 case Type::LValueReference:
7188 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00007189 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00007190 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00007191
John McCallc12c5bb2010-05-15 11:32:37 +00007192 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00007193 case Type::IncompleteArray:
7194 case Type::VariableArray:
7195 case Type::FunctionProto:
7196 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00007197 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00007198
Chris Lattner1adb8832008-01-14 05:45:46 +00007199 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00007200 {
7201 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00007202 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7203 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007204 if (Unqualified) {
7205 LHSPointee = LHSPointee.getUnqualifiedType();
7206 RHSPointee = RHSPointee.getUnqualifiedType();
7207 }
7208 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7209 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00007210 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00007211 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00007212 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00007213 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00007214 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00007215 return getPointerType(ResultType);
7216 }
Steve Naroffc0febd52008-12-10 17:49:55 +00007217 case Type::BlockPointer:
7218 {
7219 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00007220 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7221 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007222 if (Unqualified) {
7223 LHSPointee = LHSPointee.getUnqualifiedType();
7224 RHSPointee = RHSPointee.getUnqualifiedType();
7225 }
7226 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7227 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00007228 if (ResultType.isNull()) return QualType();
7229 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7230 return LHS;
7231 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7232 return RHS;
7233 return getBlockPointerType(ResultType);
7234 }
Eli Friedmanb001de72011-10-06 23:00:33 +00007235 case Type::Atomic:
7236 {
7237 // Merge two pointer types, while trying to preserve typedef info
7238 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7239 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7240 if (Unqualified) {
7241 LHSValue = LHSValue.getUnqualifiedType();
7242 RHSValue = RHSValue.getUnqualifiedType();
7243 }
7244 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7245 Unqualified);
7246 if (ResultType.isNull()) return QualType();
7247 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7248 return LHS;
7249 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7250 return RHS;
7251 return getAtomicType(ResultType);
7252 }
Chris Lattner1adb8832008-01-14 05:45:46 +00007253 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00007254 {
7255 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7256 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7257 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7258 return QualType();
7259
7260 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7261 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007262 if (Unqualified) {
7263 LHSElem = LHSElem.getUnqualifiedType();
7264 RHSElem = RHSElem.getUnqualifiedType();
7265 }
7266
7267 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00007268 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00007269 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7270 return LHS;
7271 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7272 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00007273 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7274 ArrayType::ArraySizeModifier(), 0);
7275 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7276 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00007277 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7278 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00007279 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7280 return LHS;
7281 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7282 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00007283 if (LVAT) {
7284 // FIXME: This isn't correct! But tricky to implement because
7285 // the array's size has to be the size of LHS, but the type
7286 // has to be different.
7287 return LHS;
7288 }
7289 if (RVAT) {
7290 // FIXME: This isn't correct! But tricky to implement because
7291 // the array's size has to be the size of RHS, but the type
7292 // has to be different.
7293 return RHS;
7294 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00007295 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7296 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00007297 return getIncompleteArrayType(ResultType,
7298 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00007299 }
Chris Lattner1adb8832008-01-14 05:45:46 +00007300 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00007301 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00007302 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00007303 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00007304 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00007305 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00007306 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00007307 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00007308 case Type::Complex:
7309 // Distinct complex types are incompatible.
7310 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00007311 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00007312 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00007313 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7314 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00007315 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00007316 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00007317 case Type::ObjCObject: {
7318 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00007319 // FIXME: This should be type compatibility, e.g. whether
7320 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00007321 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7322 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7323 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00007324 return LHS;
7325
Eli Friedman3d815e72008-08-22 00:56:42 +00007326 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00007327 }
Steve Naroff14108da2009-07-10 23:34:53 +00007328 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007329 if (OfBlockPointer) {
7330 if (canAssignObjCInterfacesInBlockPointer(
7331 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00007332 RHS->getAs<ObjCObjectPointerType>(),
7333 BlockReturnType))
David Blaikie7530c032012-01-17 06:56:22 +00007334 return LHS;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007335 return QualType();
7336 }
John McCall183700f2009-09-21 23:43:11 +00007337 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7338 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00007339 return LHS;
7340
Steve Naroffbc76dd02008-12-10 22:14:21 +00007341 return QualType();
David Blaikie7530c032012-01-17 06:56:22 +00007342 }
Steve Naroffec0550f2007-10-15 20:41:53 +00007343 }
Douglas Gregor72564e72009-02-26 23:50:07 +00007344
David Blaikie7530c032012-01-17 06:56:22 +00007345 llvm_unreachable("Invalid Type::Class!");
Steve Naroffec0550f2007-10-15 20:41:53 +00007346}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00007347
Fariborz Jahanian78213e42011-09-28 21:52:05 +00007348bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7349 const FunctionProtoType *FromFunctionType,
7350 const FunctionProtoType *ToFunctionType) {
7351 if (FromFunctionType->hasAnyConsumedArgs() !=
7352 ToFunctionType->hasAnyConsumedArgs())
7353 return false;
7354 FunctionProtoType::ExtProtoInfo FromEPI =
7355 FromFunctionType->getExtProtoInfo();
7356 FunctionProtoType::ExtProtoInfo ToEPI =
7357 ToFunctionType->getExtProtoInfo();
7358 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
7359 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
7360 ArgIdx != NumArgs; ++ArgIdx) {
7361 if (FromEPI.ConsumedArguments[ArgIdx] !=
7362 ToEPI.ConsumedArguments[ArgIdx])
7363 return false;
7364 }
7365 return true;
7366}
7367
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007368/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7369/// 'RHS' attributes and returns the merged version; including for function
7370/// return types.
7371QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7372 QualType LHSCan = getCanonicalType(LHS),
7373 RHSCan = getCanonicalType(RHS);
7374 // If two types are identical, they are compatible.
7375 if (LHSCan == RHSCan)
7376 return LHS;
7377 if (RHSCan->isFunctionType()) {
7378 if (!LHSCan->isFunctionType())
7379 return QualType();
7380 QualType OldReturnType =
7381 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7382 QualType NewReturnType =
7383 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7384 QualType ResReturnType =
7385 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7386 if (ResReturnType.isNull())
7387 return QualType();
7388 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7389 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7390 // In either case, use OldReturnType to build the new function type.
7391 const FunctionType *F = LHS->getAs<FunctionType>();
7392 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00007393 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7394 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007395 QualType ResultType
Jordan Rosebea522f2013-03-08 21:51:21 +00007396 = getFunctionType(OldReturnType,
7397 ArrayRef<QualType>(FPT->arg_type_begin(),
7398 FPT->getNumArgs()),
7399 EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007400 return ResultType;
7401 }
7402 }
7403 return QualType();
7404 }
7405
7406 // If the qualifiers are different, the types can still be merged.
7407 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7408 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7409 if (LQuals != RQuals) {
7410 // If any of these qualifiers are different, we have a type mismatch.
7411 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7412 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7413 return QualType();
7414
7415 // Exactly one GC qualifier difference is allowed: __strong is
7416 // okay if the other type has no GC qualifier but is an Objective
7417 // C object pointer (i.e. implicitly strong by default). We fix
7418 // this by pretending that the unqualified type was actually
7419 // qualified __strong.
7420 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7421 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7422 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7423
7424 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7425 return QualType();
7426
7427 if (GC_L == Qualifiers::Strong)
7428 return LHS;
7429 if (GC_R == Qualifiers::Strong)
7430 return RHS;
7431 return QualType();
7432 }
7433
7434 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7435 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7436 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7437 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7438 if (ResQT == LHSBaseQT)
7439 return LHS;
7440 if (ResQT == RHSBaseQT)
7441 return RHS;
7442 }
7443 return QualType();
7444}
7445
Chris Lattner5426bf62008-04-07 07:01:58 +00007446//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00007447// Integer Predicates
7448//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00007449
Jay Foad4ba2a172011-01-12 09:06:06 +00007450unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00007451 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00007452 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007453 if (T->isBooleanType())
7454 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00007455 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00007456 return (unsigned)getTypeSize(T);
7457}
7458
Abramo Bagnara762f1592012-09-09 10:21:24 +00007459QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregorf6094622010-07-23 15:58:24 +00007460 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00007461
7462 // Turn <4 x signed int> -> <4 x unsigned int>
7463 if (const VectorType *VTy = T->getAs<VectorType>())
7464 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00007465 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00007466
7467 // For enums, we return the unsigned version of the base type.
7468 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00007469 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00007470
7471 const BuiltinType *BTy = T->getAs<BuiltinType>();
7472 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007473 switch (BTy->getKind()) {
7474 case BuiltinType::Char_S:
7475 case BuiltinType::SChar:
7476 return UnsignedCharTy;
7477 case BuiltinType::Short:
7478 return UnsignedShortTy;
7479 case BuiltinType::Int:
7480 return UnsignedIntTy;
7481 case BuiltinType::Long:
7482 return UnsignedLongTy;
7483 case BuiltinType::LongLong:
7484 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00007485 case BuiltinType::Int128:
7486 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00007487 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00007488 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007489 }
7490}
7491
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00007492ASTMutationListener::~ASTMutationListener() { }
7493
Richard Smith9dadfab2013-05-11 05:45:24 +00007494void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7495 QualType ReturnType) {}
Chris Lattner86df27b2009-06-14 00:45:47 +00007496
7497//===----------------------------------------------------------------------===//
7498// Builtin Type Computation
7499//===----------------------------------------------------------------------===//
7500
7501/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00007502/// pointer over the consumed characters. This returns the resultant type. If
7503/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7504/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7505/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00007506///
7507/// RequiresICE is filled in on return to indicate whether the value is required
7508/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00007509static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00007510 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00007511 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00007512 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00007513 // Modifiers.
7514 int HowLong = 0;
7515 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00007516 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007517
Chris Lattner33daae62010-10-01 22:42:38 +00007518 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00007519 bool Done = false;
7520 while (!Done) {
7521 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00007522 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007523 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00007524 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007525 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007526 case 'S':
7527 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7528 assert(!Signed && "Can't use 'S' modifier multiple times!");
7529 Signed = true;
7530 break;
7531 case 'U':
7532 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7533 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7534 Unsigned = true;
7535 break;
7536 case 'L':
7537 assert(HowLong <= 2 && "Can't have LLLL modifier");
7538 ++HowLong;
7539 break;
7540 }
7541 }
7542
7543 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00007544
Chris Lattner86df27b2009-06-14 00:45:47 +00007545 // Read the base type.
7546 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00007547 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00007548 case 'v':
7549 assert(HowLong == 0 && !Signed && !Unsigned &&
7550 "Bad modifiers used with 'v'!");
7551 Type = Context.VoidTy;
7552 break;
7553 case 'f':
7554 assert(HowLong == 0 && !Signed && !Unsigned &&
7555 "Bad modifiers used with 'f'!");
7556 Type = Context.FloatTy;
7557 break;
7558 case 'd':
7559 assert(HowLong < 2 && !Signed && !Unsigned &&
7560 "Bad modifiers used with 'd'!");
7561 if (HowLong)
7562 Type = Context.LongDoubleTy;
7563 else
7564 Type = Context.DoubleTy;
7565 break;
7566 case 's':
7567 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7568 if (Unsigned)
7569 Type = Context.UnsignedShortTy;
7570 else
7571 Type = Context.ShortTy;
7572 break;
7573 case 'i':
7574 if (HowLong == 3)
7575 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7576 else if (HowLong == 2)
7577 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7578 else if (HowLong == 1)
7579 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7580 else
7581 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7582 break;
7583 case 'c':
7584 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7585 if (Signed)
7586 Type = Context.SignedCharTy;
7587 else if (Unsigned)
7588 Type = Context.UnsignedCharTy;
7589 else
7590 Type = Context.CharTy;
7591 break;
7592 case 'b': // boolean
7593 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7594 Type = Context.BoolTy;
7595 break;
7596 case 'z': // size_t.
7597 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7598 Type = Context.getSizeType();
7599 break;
7600 case 'F':
7601 Type = Context.getCFConstantStringType();
7602 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00007603 case 'G':
7604 Type = Context.getObjCIdType();
7605 break;
7606 case 'H':
7607 Type = Context.getObjCSelType();
7608 break;
Fariborz Jahanianf7992132013-01-04 18:45:40 +00007609 case 'M':
7610 Type = Context.getObjCSuperType();
7611 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007612 case 'a':
7613 Type = Context.getBuiltinVaListType();
7614 assert(!Type.isNull() && "builtin va list type not initialized!");
7615 break;
7616 case 'A':
7617 // This is a "reference" to a va_list; however, what exactly
7618 // this means depends on how va_list is defined. There are two
7619 // different kinds of va_list: ones passed by value, and ones
7620 // passed by reference. An example of a by-value va_list is
7621 // x86, where va_list is a char*. An example of by-ref va_list
7622 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7623 // we want this argument to be a char*&; for x86-64, we want
7624 // it to be a __va_list_tag*.
7625 Type = Context.getBuiltinVaListType();
7626 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00007627 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00007628 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00007629 else
Chris Lattner86df27b2009-06-14 00:45:47 +00007630 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00007631 break;
7632 case 'V': {
7633 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00007634 unsigned NumElements = strtoul(Str, &End, 10);
7635 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00007636 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00007637
Chris Lattner14e0e742010-10-01 22:53:11 +00007638 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7639 RequiresICE, false);
7640 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00007641
7642 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00007643 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00007644 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00007645 break;
7646 }
Douglas Gregorb4bc99b2012-06-07 18:08:25 +00007647 case 'E': {
7648 char *End;
7649
7650 unsigned NumElements = strtoul(Str, &End, 10);
7651 assert(End != Str && "Missing vector size");
7652
7653 Str = End;
7654
7655 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7656 false);
7657 Type = Context.getExtVectorType(ElementType, NumElements);
7658 break;
7659 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00007660 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00007661 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7662 false);
7663 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00007664 Type = Context.getComplexType(ElementType);
7665 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00007666 }
7667 case 'Y' : {
7668 Type = Context.getPointerDiffType();
7669 break;
7670 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007671 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00007672 Type = Context.getFILEType();
7673 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007674 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00007675 return QualType();
7676 }
Mike Stumpfd612db2009-07-28 23:47:15 +00007677 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007678 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00007679 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00007680 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00007681 else
7682 Type = Context.getjmp_bufType();
7683
Mike Stumpfd612db2009-07-28 23:47:15 +00007684 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007685 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00007686 return QualType();
7687 }
7688 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00007689 case 'K':
7690 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7691 Type = Context.getucontext_tType();
7692
7693 if (Type.isNull()) {
7694 Error = ASTContext::GE_Missing_ucontext;
7695 return QualType();
7696 }
7697 break;
Eli Friedman6902e412012-11-27 02:58:24 +00007698 case 'p':
7699 Type = Context.getProcessIDType();
7700 break;
Mike Stump782fa302009-07-28 02:25:19 +00007701 }
Mike Stump1eb44332009-09-09 15:08:12 +00007702
Chris Lattner33daae62010-10-01 22:42:38 +00007703 // If there are modifiers and if we're allowed to parse them, go for it.
7704 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00007705 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00007706 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00007707 default: Done = true; --Str; break;
7708 case '*':
7709 case '&': {
7710 // Both pointers and references can have their pointee types
7711 // qualified with an address space.
7712 char *End;
7713 unsigned AddrSpace = strtoul(Str, &End, 10);
7714 if (End != Str && AddrSpace != 0) {
7715 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7716 Str = End;
7717 }
7718 if (c == '*')
7719 Type = Context.getPointerType(Type);
7720 else
7721 Type = Context.getLValueReferenceType(Type);
7722 break;
7723 }
7724 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7725 case 'C':
7726 Type = Type.withConst();
7727 break;
7728 case 'D':
7729 Type = Context.getVolatileType(Type);
7730 break;
Ted Kremenek18932a02012-01-20 21:40:12 +00007731 case 'R':
7732 Type = Type.withRestrict();
7733 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007734 }
7735 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00007736
Chris Lattner14e0e742010-10-01 22:53:11 +00007737 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00007738 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00007739
Chris Lattner86df27b2009-06-14 00:45:47 +00007740 return Type;
7741}
7742
7743/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00007744QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00007745 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00007746 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00007747 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00007748
Chris Lattner5f9e2722011-07-23 10:55:15 +00007749 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00007750
Chris Lattner14e0e742010-10-01 22:53:11 +00007751 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00007752 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00007753 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7754 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007755 if (Error != GE_None)
7756 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00007757
7758 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7759
Chris Lattner86df27b2009-06-14 00:45:47 +00007760 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00007761 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007762 if (Error != GE_None)
7763 return QualType();
7764
Chris Lattner14e0e742010-10-01 22:53:11 +00007765 // If this argument is required to be an IntegerConstantExpression and the
7766 // caller cares, fill in the bitmask we return.
7767 if (RequiresICE && IntegerConstantArgs)
7768 *IntegerConstantArgs |= 1 << ArgTypes.size();
7769
Chris Lattner86df27b2009-06-14 00:45:47 +00007770 // Do array -> pointer decay. The builtin should use the decayed type.
7771 if (Ty->isArrayType())
7772 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00007773
Chris Lattner86df27b2009-06-14 00:45:47 +00007774 ArgTypes.push_back(Ty);
7775 }
7776
7777 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7778 "'.' should only occur at end of builtin type list!");
7779
John McCall00ccbef2010-12-21 00:44:39 +00007780 FunctionType::ExtInfo EI;
7781 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7782
7783 bool Variadic = (TypeStr[0] == '.');
7784
7785 // We really shouldn't be making a no-proto type here, especially in C++.
7786 if (ArgTypes.empty() && Variadic)
7787 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00007788
John McCalle23cf432010-12-14 08:05:40 +00007789 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00007790 EPI.ExtInfo = EI;
7791 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00007792
Jordan Rosebea522f2013-03-08 21:51:21 +00007793 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00007794}
Eli Friedmana95d7572009-08-19 07:44:53 +00007795
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007796GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007797 if (!FD->isExternallyVisible())
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007798 return GVA_Internal;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007799
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007800 GVALinkage External = GVA_StrongExternal;
7801 switch (FD->getTemplateSpecializationKind()) {
7802 case TSK_Undeclared:
7803 case TSK_ExplicitSpecialization:
7804 External = GVA_StrongExternal;
7805 break;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007806
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007807 case TSK_ExplicitInstantiationDefinition:
7808 return GVA_ExplicitTemplateInstantiation;
7809
7810 case TSK_ExplicitInstantiationDeclaration:
7811 case TSK_ImplicitInstantiation:
7812 External = GVA_TemplateInstantiation;
7813 break;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007814 }
7815
7816 if (!FD->isInlined())
7817 return External;
7818
David Blaikie4e4d0842012-03-11 07:00:24 +00007819 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007820 // GNU or C99 inline semantics. Determine whether this symbol should be
7821 // externally visible.
7822 if (FD->isInlineDefinitionExternallyVisible())
7823 return External;
7824
7825 // C99 inline semantics, where the symbol is not externally visible.
7826 return GVA_C99Inline;
7827 }
7828
7829 // C++0x [temp.explicit]p9:
7830 // [ Note: The intent is that an inline function that is the subject of
7831 // an explicit instantiation declaration will still be implicitly
7832 // instantiated when used so that the body can be considered for
7833 // inlining, but that no out-of-line copy of the inline function would be
7834 // generated in the translation unit. -- end note ]
7835 if (FD->getTemplateSpecializationKind()
7836 == TSK_ExplicitInstantiationDeclaration)
7837 return GVA_C99Inline;
7838
7839 return GVA_CXXInline;
7840}
7841
7842GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007843 if (!VD->isExternallyVisible())
7844 return GVA_Internal;
7845
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007846 // If this is a static data member, compute the kind of template
7847 // specialization. Otherwise, this variable is not part of a
7848 // template.
7849 TemplateSpecializationKind TSK = TSK_Undeclared;
7850 if (VD->isStaticDataMember())
7851 TSK = VD->getTemplateSpecializationKind();
7852
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007853 switch (TSK) {
7854 case TSK_Undeclared:
7855 case TSK_ExplicitSpecialization:
7856 return GVA_StrongExternal;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007857
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007858 case TSK_ExplicitInstantiationDeclaration:
7859 llvm_unreachable("Variable should not be instantiated");
7860 // Fall through to treat this like any other instantiation.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007861
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007862 case TSK_ExplicitInstantiationDefinition:
7863 return GVA_ExplicitTemplateInstantiation;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007864
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007865 case TSK_ImplicitInstantiation:
7866 return GVA_TemplateInstantiation;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007867 }
Rafael Espindola77b50252013-05-13 14:05:53 +00007868
7869 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007870}
7871
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00007872bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007873 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7874 if (!VD->isFileVarDecl())
7875 return false;
Richard Smithf396ad92013-04-01 20:22:16 +00007876 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7877 // We never need to emit an uninstantiated function template.
7878 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7879 return false;
7880 } else
7881 return false;
7882
7883 // If this is a member of a class template, we do not need to emit it.
7884 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007885 return false;
7886
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007887 // Weak references don't produce any output by themselves.
7888 if (D->hasAttr<WeakRefAttr>())
7889 return false;
7890
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007891 // Aliases and used decls are required.
7892 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7893 return true;
7894
7895 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7896 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00007897 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00007898 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007899
7900 // Constructors and destructors are required.
7901 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7902 return true;
7903
John McCalld5617ee2013-01-25 22:31:03 +00007904 // The key function for a class is required. This rule only comes
7905 // into play when inline functions can be key functions, though.
7906 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7907 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7908 const CXXRecordDecl *RD = MD->getParent();
7909 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7910 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7911 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7912 return true;
7913 }
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007914 }
7915 }
7916
7917 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7918
7919 // static, static inline, always_inline, and extern inline functions can
7920 // always be deferred. Normal inline functions can be deferred in C99/C++.
7921 // Implicit template instantiations can also be deferred in C++.
7922 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev3a5aca82012-02-02 06:06:34 +00007923 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007924 return false;
7925 return true;
7926 }
Douglas Gregor94da1582011-09-10 00:22:34 +00007927
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007928 const VarDecl *VD = cast<VarDecl>(D);
7929 assert(VD->isFileVarDecl() && "Expected file scoped var");
7930
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007931 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7932 return false;
7933
Richard Smith5f9a7e32012-11-12 21:38:00 +00007934 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007935 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smith5f9a7e32012-11-12 21:38:00 +00007936 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7937 return true;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007938
Richard Smith5f9a7e32012-11-12 21:38:00 +00007939 // Variables that have destruction with side-effects are required.
7940 if (VD->getType().isDestructedType())
7941 return true;
7942
7943 // Variables that have initialization with side-effects are required.
7944 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7945 return true;
7946
7947 return false;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007948}
Charles Davis071cc7d2010-08-16 03:33:14 +00007949
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007950CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davisee743f92010-11-09 18:04:24 +00007951 // Pass through to the C++ ABI object
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007952 return ABI->getDefaultMethodCallConv(isVariadic);
7953}
7954
7955CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
John McCallb8b2c9d2013-01-25 22:30:49 +00007956 if (CC == CC_C && !LangOpts.MRTD &&
7957 getTargetInfo().getCXXABI().isMemberFunctionCCDefault())
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007958 return CC_Default;
7959 return CC;
Charles Davisee743f92010-11-09 18:04:24 +00007960}
7961
Jay Foad4ba2a172011-01-12 09:06:06 +00007962bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00007963 // Pass through to the C++ ABI object
7964 return ABI->isNearlyEmpty(RD);
7965}
7966
Peter Collingbourne14110472011-01-13 18:57:25 +00007967MangleContext *ASTContext::createMangleContext() {
John McCallb8b2c9d2013-01-25 22:30:49 +00007968 switch (Target->getCXXABI().getKind()) {
Tim Northoverc264e162013-01-31 12:13:10 +00007969 case TargetCXXABI::GenericAArch64:
John McCallb8b2c9d2013-01-25 22:30:49 +00007970 case TargetCXXABI::GenericItanium:
7971 case TargetCXXABI::GenericARM:
7972 case TargetCXXABI::iOS:
Peter Collingbourne14110472011-01-13 18:57:25 +00007973 return createItaniumMangleContext(*this, getDiagnostics());
John McCallb8b2c9d2013-01-25 22:30:49 +00007974 case TargetCXXABI::Microsoft:
Peter Collingbourne14110472011-01-13 18:57:25 +00007975 return createMicrosoftMangleContext(*this, getDiagnostics());
7976 }
David Blaikieb219cfc2011-09-23 05:06:16 +00007977 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00007978}
7979
Charles Davis071cc7d2010-08-16 03:33:14 +00007980CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00007981
7982size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00007983 return ASTRecordLayouts.getMemorySize()
7984 + llvm::capacity_in_bytes(ObjCLayouts)
7985 + llvm::capacity_in_bytes(KeyFunctions)
7986 + llvm::capacity_in_bytes(ObjCImpls)
7987 + llvm::capacity_in_bytes(BlockVarCopyInits)
7988 + llvm::capacity_in_bytes(DeclAttrs)
7989 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7990 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7991 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7992 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7993 + llvm::capacity_in_bytes(OverriddenMethods)
7994 + llvm::capacity_in_bytes(Types)
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007995 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet0d95f0d2011-08-14 14:28:49 +00007996 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00007997}
Ted Kremenekd211cb72011-10-06 05:00:56 +00007998
David Blaikie66cff722012-11-14 01:52:05 +00007999void ASTContext::addUnnamedTag(const TagDecl *Tag) {
8000 // FIXME: This mangling should be applied to function local classes too
8001 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl() ||
Rafael Espindola5bbb0582013-05-28 14:09:46 +00008002 !isa<CXXRecordDecl>(Tag->getParent()))
David Blaikie66cff722012-11-14 01:52:05 +00008003 return;
8004
8005 std::pair<llvm::DenseMap<const DeclContext *, unsigned>::iterator, bool> P =
8006 UnnamedMangleContexts.insert(std::make_pair(Tag->getParent(), 0));
8007 UnnamedMangleNumbers.insert(std::make_pair(Tag, P.first->second++));
8008}
8009
8010int ASTContext::getUnnamedTagManglingNumber(const TagDecl *Tag) const {
8011 llvm::DenseMap<const TagDecl *, unsigned>::const_iterator I =
8012 UnnamedMangleNumbers.find(Tag);
8013 return I != UnnamedMangleNumbers.end() ? I->second : -1;
8014}
8015
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00008016unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
8017 CXXRecordDecl *Lambda = CallOperator->getParent();
8018 return LambdaMangleContexts[Lambda->getDeclContext()]
8019 .getManglingNumber(CallOperator);
8020}
8021
8022
Ted Kremenekd211cb72011-10-06 05:00:56 +00008023void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8024 ParamIndices[D] = index;
8025}
8026
8027unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8028 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8029 assert(I != ParamIndices.end() &&
8030 "ParmIndices lacks entry set by ParmVarDecl");
8031 return I->second;
8032}