blob: 406760400c4d47788a675e8bc78ea8011f1558be [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),
Rafael Espindola42b78612013-05-29 19:51:12 +0000719 LastSDM(0, 0)
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000720{
Mike Stump1eb44332009-09-09 15:08:12 +0000721 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000722 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000723
724 if (!DelayInitialization) {
725 assert(t && "No target supplied for ASTContext initialization");
726 InitBuiltinTypes(*t);
727 }
Daniel Dunbare91593e2008-08-11 04:54:23 +0000728}
729
Reid Spencer5f016e22007-07-11 17:01:13 +0000730ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000731 // Release the DenseMaps associated with DeclContext objects.
732 // FIXME: Is this the ideal solution?
733 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000734
Manuel Klimekf0f353b2013-06-03 13:51:33 +0000735 // Call all of the deallocation functions on all of their targets.
736 for (DeallocationMap::const_iterator I = Deallocations.begin(),
737 E = Deallocations.end(); I != E; ++I)
738 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
739 (I->first)((I->second)[J]);
740
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000741 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000742 // because they can contain DenseMaps.
743 for (llvm::DenseMap<const ObjCContainerDecl*,
744 const ASTRecordLayout*>::iterator
745 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
746 // Increment in loop to prevent using deallocated memory.
747 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
748 R->Destroy(*this);
749
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000750 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
751 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
752 // Increment in loop to prevent using deallocated memory.
753 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
754 R->Destroy(*this);
755 }
Douglas Gregor63200642010-08-30 16:49:28 +0000756
757 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
758 AEnd = DeclAttrs.end();
759 A != AEnd; ++A)
760 A->second->~AttrVec();
761}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000762
Douglas Gregor00545312010-05-23 18:26:36 +0000763void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimekf0f353b2013-06-03 13:51:33 +0000764 Deallocations[Callback].push_back(Data);
Douglas Gregor00545312010-05-23 18:26:36 +0000765}
766
Mike Stump1eb44332009-09-09 15:08:12 +0000767void
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000768ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000769 ExternalSource.reset(Source.take());
770}
771
Reid Spencer5f016e22007-07-11 17:01:13 +0000772void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000773 llvm::errs() << "\n*** AST Context Stats:\n";
774 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000775
Douglas Gregordbe833d2009-05-26 14:40:08 +0000776 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000777#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000778#define ABSTRACT_TYPE(Name, Parent)
779#include "clang/AST/TypeNodes.def"
780 0 // Extra
781 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000782
Reid Spencer5f016e22007-07-11 17:01:13 +0000783 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
784 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000785 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000786 }
787
Douglas Gregordbe833d2009-05-26 14:40:08 +0000788 unsigned Idx = 0;
789 unsigned TotalBytes = 0;
790#define TYPE(Name, Parent) \
791 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000792 llvm::errs() << " " << counts[Idx] << " " << #Name \
793 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000794 TotalBytes += counts[Idx] * sizeof(Name##Type); \
795 ++Idx;
796#define ABSTRACT_TYPE(Name, Parent)
797#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000798
Chandler Carruthcd92a652011-07-04 05:32:14 +0000799 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
800
Douglas Gregor4923aa22010-07-02 20:37:36 +0000801 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000802 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
803 << NumImplicitDefaultConstructors
804 << " implicit default constructors created\n";
805 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
806 << NumImplicitCopyConstructors
807 << " implicit copy constructors created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000808 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000809 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
810 << NumImplicitMoveConstructors
811 << " implicit move constructors created\n";
812 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
813 << NumImplicitCopyAssignmentOperators
814 << " implicit copy assignment operators created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000815 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000816 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
817 << NumImplicitMoveAssignmentOperators
818 << " implicit move assignment operators created\n";
819 llvm::errs() << NumImplicitDestructorsDeclared << "/"
820 << NumImplicitDestructors
821 << " implicit destructors created\n";
822
Douglas Gregor2cf26342009-04-09 22:27:44 +0000823 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000824 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000825 ExternalSource->PrintStats();
826 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000827
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000828 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000829}
830
Douglas Gregor772eeae2011-08-12 06:49:56 +0000831TypedefDecl *ASTContext::getInt128Decl() const {
832 if (!Int128Decl) {
833 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
834 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
835 getTranslationUnitDecl(),
836 SourceLocation(),
837 SourceLocation(),
838 &Idents.get("__int128_t"),
839 TInfo);
840 }
841
842 return Int128Decl;
843}
844
845TypedefDecl *ASTContext::getUInt128Decl() const {
846 if (!UInt128Decl) {
847 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
848 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
849 getTranslationUnitDecl(),
850 SourceLocation(),
851 SourceLocation(),
852 &Idents.get("__uint128_t"),
853 TInfo);
854 }
855
856 return UInt128Decl;
857}
Reid Spencer5f016e22007-07-11 17:01:13 +0000858
John McCalle27ec8a2009-10-23 23:03:21 +0000859void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000860 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000861 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000862 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000863}
864
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000865void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
866 assert((!this->Target || this->Target == &Target) &&
867 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000868 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000869
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000870 this->Target = &Target;
871
872 ABI.reset(createCXXABI(Target));
873 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
874
Reid Spencer5f016e22007-07-11 17:01:13 +0000875 // C99 6.2.5p19.
876 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000877
Reid Spencer5f016e22007-07-11 17:01:13 +0000878 // C99 6.2.5p2.
879 InitBuiltinType(BoolTy, BuiltinType::Bool);
880 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000881 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000882 InitBuiltinType(CharTy, BuiltinType::Char_S);
883 else
884 InitBuiltinType(CharTy, BuiltinType::Char_U);
885 // C99 6.2.5p4.
886 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
887 InitBuiltinType(ShortTy, BuiltinType::Short);
888 InitBuiltinType(IntTy, BuiltinType::Int);
889 InitBuiltinType(LongTy, BuiltinType::Long);
890 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000891
Reid Spencer5f016e22007-07-11 17:01:13 +0000892 // C99 6.2.5p6.
893 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
894 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
895 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
896 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
897 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000898
Reid Spencer5f016e22007-07-11 17:01:13 +0000899 // C99 6.2.5p10.
900 InitBuiltinType(FloatTy, BuiltinType::Float);
901 InitBuiltinType(DoubleTy, BuiltinType::Double);
902 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000903
Chris Lattner2df9ced2009-04-30 02:43:43 +0000904 // GNU extension, 128-bit integers.
905 InitBuiltinType(Int128Ty, BuiltinType::Int128);
906 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
907
Hans Wennborg15f92ba2013-05-10 10:08:40 +0000908 // C++ 3.9.1p5
909 if (TargetInfo::isTypeSigned(Target.getWCharType()))
910 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
911 else // -fshort-wchar makes wchar_t be unsigned.
912 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
913 if (LangOpts.CPlusPlus && LangOpts.WChar)
914 WideCharTy = WCharTy;
915 else {
916 // C99 (or C++ using -fno-wchar).
917 WideCharTy = getFromTargetType(Target.getWCharType());
918 }
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000919
James Molloy392da482012-05-04 10:55:22 +0000920 WIntTy = getFromTargetType(Target.getWIntType());
921
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000922 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
923 InitBuiltinType(Char16Ty, BuiltinType::Char16);
924 else // C99
925 Char16Ty = getFromTargetType(Target.getChar16Type());
926
927 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
928 InitBuiltinType(Char32Ty, BuiltinType::Char32);
929 else // C99
930 Char32Ty = getFromTargetType(Target.getChar32Type());
931
Douglas Gregor898574e2008-12-05 23:32:09 +0000932 // Placeholder type for type-dependent expressions whose type is
933 // completely unknown. No code should ever check a type against
934 // DependentTy and users should never see it; however, it is here to
935 // help diagnose failures to properly check for type-dependent
936 // expressions.
937 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000938
John McCall2a984ca2010-10-12 00:20:44 +0000939 // Placeholder type for functions.
940 InitBuiltinType(OverloadTy, BuiltinType::Overload);
941
John McCall864c0412011-04-26 20:42:42 +0000942 // Placeholder type for bound members.
943 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
944
John McCall3c3b7f92011-10-25 17:37:35 +0000945 // Placeholder type for pseudo-objects.
946 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
947
John McCall1de4d4e2011-04-07 08:22:57 +0000948 // "any" type; useful for debugger-like clients.
949 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
950
John McCall0ddaeb92011-10-17 18:09:15 +0000951 // Placeholder type for unbridged ARC casts.
952 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
953
Eli Friedmana6c66ce2012-08-31 00:14:07 +0000954 // Placeholder type for builtin functions.
955 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
956
Reid Spencer5f016e22007-07-11 17:01:13 +0000957 // C99 6.2.5p11.
958 FloatComplexTy = getComplexType(FloatTy);
959 DoubleComplexTy = getComplexType(DoubleTy);
960 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000961
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000962 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000963 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
964 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000965 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeib13621d2012-12-18 14:38:23 +0000966
967 if (LangOpts.OpenCL) {
968 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
969 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
970 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
971 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
972 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
973 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000974
Guy Benyei21f18c42013-02-07 10:55:47 +0000975 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000976 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeib13621d2012-12-18 14:38:23 +0000977 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000978
979 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian93a49942012-04-16 21:03:30 +0000980 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
981 SignedCharTy : BoolTy);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000982
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000983 ObjCConstantStringType = QualType();
Fariborz Jahanianf7992132013-01-04 18:45:40 +0000984
985 ObjCSuperType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000986
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000987 // void * type
988 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000989
990 // nullptr type (C++0x 2.14.7)
991 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000992
993 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
994 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingefb40e3f2012-07-01 15:57:25 +0000995
996 // Builtin type used to help define __builtin_va_list.
997 VaListTagTy = QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000998}
999
David Blaikied6471f72011-09-25 23:23:43 +00001000DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001001 return SourceMgr.getDiagnostics();
1002}
1003
Douglas Gregor63200642010-08-30 16:49:28 +00001004AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1005 AttrVec *&Result = DeclAttrs[D];
1006 if (!Result) {
1007 void *Mem = Allocate(sizeof(AttrVec));
1008 Result = new (Mem) AttrVec;
1009 }
1010
1011 return *Result;
1012}
1013
1014/// \brief Erase the attributes corresponding to the given declaration.
1015void ASTContext::eraseDeclAttrs(const Decl *D) {
1016 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1017 if (Pos != DeclAttrs.end()) {
1018 Pos->second->~AttrVec();
1019 DeclAttrs.erase(Pos);
1020 }
1021}
1022
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001023MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +00001024ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001025 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +00001026 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +00001027 = InstantiatedFromStaticDataMember.find(Var);
1028 if (Pos == InstantiatedFromStaticDataMember.end())
1029 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001030
Douglas Gregor7caa6822009-07-24 20:34:43 +00001031 return Pos->second;
1032}
1033
Mike Stump1eb44332009-09-09 15:08:12 +00001034void
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001035ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +00001036 TemplateSpecializationKind TSK,
1037 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001038 assert(Inst->isStaticDataMember() && "Not a static data member");
1039 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1040 assert(!InstantiatedFromStaticDataMember[Inst] &&
1041 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001042 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +00001043 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +00001044}
1045
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001046FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1047 const FunctionDecl *FD){
1048 assert(FD && "Specialization is 0");
1049 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +00001050 = ClassScopeSpecializationPattern.find(FD);
1051 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001052 return 0;
1053
1054 return Pos->second;
1055}
1056
1057void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1058 FunctionDecl *Pattern) {
1059 assert(FD && "Specialization is 0");
1060 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +00001061 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001062}
1063
John McCall7ba107a2009-11-18 02:36:19 +00001064NamedDecl *
John McCalled976492009-12-04 22:46:56 +00001065ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +00001066 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +00001067 = InstantiatedFromUsingDecl.find(UUD);
1068 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +00001069 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001070
Anders Carlsson0d8df782009-08-29 19:37:28 +00001071 return Pos->second;
1072}
1073
1074void
John McCalled976492009-12-04 22:46:56 +00001075ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1076 assert((isa<UsingDecl>(Pattern) ||
1077 isa<UnresolvedUsingValueDecl>(Pattern) ||
1078 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1079 "pattern decl is not a using decl");
1080 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1081 InstantiatedFromUsingDecl[Inst] = Pattern;
1082}
1083
1084UsingShadowDecl *
1085ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1086 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1087 = InstantiatedFromUsingShadowDecl.find(Inst);
1088 if (Pos == InstantiatedFromUsingShadowDecl.end())
1089 return 0;
1090
1091 return Pos->second;
1092}
1093
1094void
1095ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1096 UsingShadowDecl *Pattern) {
1097 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1098 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00001099}
1100
Anders Carlssond8b285f2009-09-01 04:26:58 +00001101FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1102 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1103 = InstantiatedFromUnnamedFieldDecl.find(Field);
1104 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1105 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001106
Anders Carlssond8b285f2009-09-01 04:26:58 +00001107 return Pos->second;
1108}
1109
1110void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1111 FieldDecl *Tmpl) {
1112 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1113 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1114 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1115 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +00001116
Anders Carlssond8b285f2009-09-01 04:26:58 +00001117 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1118}
1119
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +00001120bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
1121 const FieldDecl *LastFD) const {
1122 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001123 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +00001124}
1125
Fariborz Jahanian340fa242011-05-02 17:20:56 +00001126bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
1127 const FieldDecl *LastFD) const {
1128 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001129 FD->getBitWidthValue(*this) == 0 &&
1130 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +00001131}
1132
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001133bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
1134 const FieldDecl *LastFD) const {
1135 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001136 FD->getBitWidthValue(*this) &&
1137 LastFD->getBitWidthValue(*this));
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001138}
1139
Chad Rosierdd7fddb2011-08-04 23:34:15 +00001140bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001141 const FieldDecl *LastFD) const {
1142 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001143 LastFD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001144}
1145
Chad Rosierdd7fddb2011-08-04 23:34:15 +00001146bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001147 const FieldDecl *LastFD) const {
1148 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001149 FD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001150}
1151
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001152ASTContext::overridden_cxx_method_iterator
1153ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1154 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001155 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001156 if (Pos == OverriddenMethods.end())
1157 return 0;
1158
1159 return Pos->second.begin();
1160}
1161
1162ASTContext::overridden_cxx_method_iterator
1163ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1164 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001165 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001166 if (Pos == OverriddenMethods.end())
1167 return 0;
1168
1169 return Pos->second.end();
1170}
1171
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001172unsigned
1173ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1174 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001175 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001176 if (Pos == OverriddenMethods.end())
1177 return 0;
1178
1179 return Pos->second.size();
1180}
1181
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001182void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1183 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001184 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001185 OverriddenMethods[Method].push_back(Overridden);
1186}
1187
Dmitri Gribenko1e905da2012-11-03 14:24:57 +00001188void ASTContext::getOverriddenMethods(
1189 const NamedDecl *D,
1190 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001191 assert(D);
1192
1193 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis685d1042013-04-17 00:09:03 +00001194 Overridden.append(overridden_methods_begin(CXXMethod),
1195 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001196 return;
1197 }
1198
1199 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1200 if (!Method)
1201 return;
1202
Argyrios Kyrtzidis740ae672012-10-09 18:19:01 +00001203 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1204 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisbc0a2bb2012-10-09 20:08:43 +00001205 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001206}
1207
Douglas Gregore6649772011-12-03 00:30:27 +00001208void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1209 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1210 assert(!Import->isFromASTFile() && "Non-local import declaration");
1211 if (!FirstLocalImport) {
1212 FirstLocalImport = Import;
1213 LastLocalImport = Import;
1214 return;
1215 }
1216
1217 LastLocalImport->NextLocalImport = Import;
1218 LastLocalImport = Import;
1219}
1220
Chris Lattner464175b2007-07-18 17:52:12 +00001221//===----------------------------------------------------------------------===//
1222// Type Sizing and Analysis
1223//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +00001224
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001225/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1226/// scalar floating point type.
1227const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +00001228 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001229 assert(BT && "Not a floating point type!");
1230 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001231 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001232 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001233 case BuiltinType::Float: return Target->getFloatFormat();
1234 case BuiltinType::Double: return Target->getDoubleFormat();
1235 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001236 }
1237}
1238
Ken Dyck8b752f12010-01-27 17:10:57 +00001239/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +00001240/// specified decl. Note that bitfields do not have a valid alignment, so
1241/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +00001242/// If @p RefAsPointee, references are treated like their underlying type
1243/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +00001244CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001245 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +00001246
John McCall4081a5c2010-10-08 18:24:19 +00001247 bool UseAlignAttrOnly = false;
1248 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1249 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +00001250
John McCall4081a5c2010-10-08 18:24:19 +00001251 // __attribute__((aligned)) can increase or decrease alignment
1252 // *except* on a struct or struct member, where it only increases
1253 // alignment unless 'packed' is also specified.
1254 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +00001255 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +00001256 // ignore that possibility; Sema should diagnose it.
1257 if (isa<FieldDecl>(D)) {
1258 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1259 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1260 } else {
1261 UseAlignAttrOnly = true;
1262 }
1263 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +00001264 else if (isa<FieldDecl>(D))
1265 UseAlignAttrOnly =
1266 D->hasAttr<PackedAttr>() ||
1267 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +00001268
John McCallba4f5d52011-01-20 07:57:12 +00001269 // If we're using the align attribute only, just ignore everything
1270 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +00001271 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +00001272 // do nothing
1273
John McCall4081a5c2010-10-08 18:24:19 +00001274 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001275 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001276 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001277 if (RefAsPointee)
1278 T = RT->getPointeeType();
1279 else
1280 T = getPointerType(RT->getPointeeType());
1281 }
1282 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +00001283 // Adjust alignments of declarations with array type by the
1284 // large-array alignment on the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001285 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +00001286 const ArrayType *arrayType;
1287 if (MinWidth && (arrayType = getAsArrayType(T))) {
1288 if (isa<VariableArrayType>(arrayType))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001289 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall3b657512011-01-19 10:06:00 +00001290 else if (isa<ConstantArrayType>(arrayType) &&
1291 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001292 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +00001293
John McCall3b657512011-01-19 10:06:00 +00001294 // Walk through any array types while we're at it.
1295 T = getBaseElementType(arrayType);
1296 }
Chad Rosier9f1210c2011-07-26 07:03:04 +00001297 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigand6b203512013-05-06 16:23:57 +00001298 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1299 if (VD->hasGlobalStorage())
1300 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1301 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001302 }
John McCallba4f5d52011-01-20 07:57:12 +00001303
1304 // Fields can be subject to extra alignment constraints, like if
1305 // the field is packed, the struct is packed, or the struct has a
1306 // a max-field-alignment constraint (#pragma pack). So calculate
1307 // the actual alignment of the field within the struct, and then
1308 // (as we're expected to) constrain that by the alignment of the type.
1309 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1310 // So calculate the alignment of the field.
1311 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1312
1313 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +00001314 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +00001315
1316 // Use the GCD of that and the offset within the record.
1317 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1318 if (offset > 0) {
1319 // Alignment is always a power of 2, so the GCD will be a power of 2,
1320 // which means we get to do this crazy thing instead of Euclid's.
1321 uint64_t lowBitOfOffset = offset & (~offset + 1);
1322 if (lowBitOfOffset < fieldAlign)
1323 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1324 }
1325
1326 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +00001327 }
Chris Lattneraf707ab2009-01-24 21:53:27 +00001328 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001329
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001330 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001331}
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001332
John McCall929bbfb2012-08-21 04:10:00 +00001333// getTypeInfoDataSizeInChars - Return the size of a type, in
1334// chars. If the type is a record, its data size is returned. This is
1335// the size of the memcpy that's performed when assigning this type
1336// using a trivial copy/move assignment operator.
1337std::pair<CharUnits, CharUnits>
1338ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1339 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1340
1341 // In C++, objects can sometimes be allocated into the tail padding
1342 // of a base-class subobject. We decide whether that's possible
1343 // during class layout, so here we can just trust the layout results.
1344 if (getLangOpts().CPlusPlus) {
1345 if (const RecordType *RT = T->getAs<RecordType>()) {
1346 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1347 sizeAndAlign.first = layout.getDataSize();
1348 }
1349 }
1350
1351 return sizeAndAlign;
1352}
1353
Richard Trieu910f17e2013-05-14 21:59:17 +00001354/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1355/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1356std::pair<CharUnits, CharUnits>
1357static getConstantArrayInfoInChars(const ASTContext &Context,
1358 const ConstantArrayType *CAT) {
1359 std::pair<CharUnits, CharUnits> EltInfo =
1360 Context.getTypeInfoInChars(CAT->getElementType());
1361 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieu1069b732013-05-14 23:41:50 +00001362 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1363 (uint64_t)(-1)/Size) &&
Richard Trieu910f17e2013-05-14 21:59:17 +00001364 "Overflow in array type char size evaluation");
1365 uint64_t Width = EltInfo.first.getQuantity() * Size;
1366 unsigned Align = EltInfo.second.getQuantity();
1367 Width = llvm::RoundUpToAlignment(Width, Align);
1368 return std::make_pair(CharUnits::fromQuantity(Width),
1369 CharUnits::fromQuantity(Align));
1370}
1371
John McCallea1471e2010-05-20 01:18:31 +00001372std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001373ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001374 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1375 return getConstantArrayInfoInChars(*this, CAT);
John McCallea1471e2010-05-20 01:18:31 +00001376 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001377 return std::make_pair(toCharUnitsFromBits(Info.first),
1378 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +00001379}
1380
1381std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001382ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +00001383 return getTypeInfoInChars(T.getTypePtr());
1384}
1385
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001386std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1387 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1388 if (it != MemoizedTypeInfo.end())
1389 return it->second;
1390
1391 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1392 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1393 return Info;
1394}
1395
1396/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1397/// method does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +00001398///
1399/// FIXME: Pointers into different addr spaces could have different sizes and
1400/// alignment requirements: getPointerInfo should take an AddrSpace, this
1401/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001402std::pair<uint64_t, unsigned>
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001403ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +00001404 uint64_t Width=0;
1405 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +00001406 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001407#define TYPE(Class, Base)
1408#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +00001409#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +00001410#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1411#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +00001412 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +00001413
Chris Lattner692233e2007-07-13 22:27:08 +00001414 case Type::FunctionNoProto:
1415 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +00001416 // GCC extension: alignof(function) = 32 bits
1417 Width = 0;
1418 Align = 32;
1419 break;
1420
Douglas Gregor72564e72009-02-26 23:50:07 +00001421 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +00001422 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +00001423 Width = 0;
1424 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1425 break;
1426
Steve Narofffb22d962007-08-30 01:06:46 +00001427 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001428 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001429
Chris Lattner98be4942008-03-05 18:54:05 +00001430 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001431 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001432 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1433 "Overflow in array type bit size evaluation");
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001434 Width = EltInfo.first*Size;
Chris Lattner030d8842007-07-19 22:06:24 +00001435 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +00001436 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +00001437 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +00001438 }
Nate Begeman213541a2008-04-18 23:10:10 +00001439 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +00001440 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001441 const VectorType *VT = cast<VectorType>(T);
1442 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1443 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +00001444 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001445 // If the alignment is not a power of 2, round up to the next power of 2.
1446 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +00001447 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001448 Align = llvm::NextPowerOf2(Align);
1449 Width = llvm::RoundUpToAlignment(Width, Align);
1450 }
Chad Rosierf9e9af72012-07-13 23:57:43 +00001451 // Adjust the alignment based on the target max.
1452 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1453 if (TargetVectorAlign && TargetVectorAlign < Align)
1454 Align = TargetVectorAlign;
Chris Lattner030d8842007-07-19 22:06:24 +00001455 break;
1456 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001457
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001458 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +00001459 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001460 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001461 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +00001462 // GCC extension: alignof(void) = 8 bits.
1463 Width = 0;
1464 Align = 8;
1465 break;
1466
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001467 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001468 Width = Target->getBoolWidth();
1469 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001470 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001471 case BuiltinType::Char_S:
1472 case BuiltinType::Char_U:
1473 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001474 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001475 Width = Target->getCharWidth();
1476 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001477 break;
Chris Lattner3f59c972010-12-25 23:25:43 +00001478 case BuiltinType::WChar_S:
1479 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001480 Width = Target->getWCharWidth();
1481 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001482 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001483 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001484 Width = Target->getChar16Width();
1485 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001486 break;
1487 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001488 Width = Target->getChar32Width();
1489 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001490 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001491 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001492 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001493 Width = Target->getShortWidth();
1494 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001495 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001496 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001497 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001498 Width = Target->getIntWidth();
1499 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001500 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001501 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001502 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001503 Width = Target->getLongWidth();
1504 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001505 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001506 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001507 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001508 Width = Target->getLongLongWidth();
1509 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001510 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +00001511 case BuiltinType::Int128:
1512 case BuiltinType::UInt128:
1513 Width = 128;
1514 Align = 128; // int128_t is 128-bit aligned on all targets.
1515 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001516 case BuiltinType::Half:
1517 Width = Target->getHalfWidth();
1518 Align = Target->getHalfAlign();
1519 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001520 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001521 Width = Target->getFloatWidth();
1522 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001523 break;
1524 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001525 Width = Target->getDoubleWidth();
1526 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001527 break;
1528 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001529 Width = Target->getLongDoubleWidth();
1530 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001531 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001532 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001533 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1534 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +00001535 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001536 case BuiltinType::ObjCId:
1537 case BuiltinType::ObjCClass:
1538 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001539 Width = Target->getPointerWidth(0);
1540 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001541 break;
Guy Benyei21f18c42013-02-07 10:55:47 +00001542 case BuiltinType::OCLSampler:
1543 // Samplers are modeled as integers.
1544 Width = Target->getIntWidth();
1545 Align = Target->getIntAlign();
1546 break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00001547 case BuiltinType::OCLEvent:
Guy Benyeib13621d2012-12-18 14:38:23 +00001548 case BuiltinType::OCLImage1d:
1549 case BuiltinType::OCLImage1dArray:
1550 case BuiltinType::OCLImage1dBuffer:
1551 case BuiltinType::OCLImage2d:
1552 case BuiltinType::OCLImage2dArray:
1553 case BuiltinType::OCLImage3d:
1554 // Currently these types are pointers to opaque types.
1555 Width = Target->getPointerWidth(0);
1556 Align = Target->getPointerAlign(0);
1557 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001558 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +00001559 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001560 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001561 Width = Target->getPointerWidth(0);
1562 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001563 break;
Steve Naroff485eeff2008-09-24 15:05:44 +00001564 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001565 unsigned AS = getTargetAddressSpace(
1566 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001567 Width = Target->getPointerWidth(AS);
1568 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +00001569 break;
1570 }
Sebastian Redl5d484e82009-11-23 17:18:46 +00001571 case Type::LValueReference:
1572 case Type::RValueReference: {
1573 // alignof and sizeof should never enter this code path here, so we go
1574 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001575 unsigned AS = getTargetAddressSpace(
1576 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001577 Width = Target->getPointerWidth(AS);
1578 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +00001579 break;
1580 }
Chris Lattnerf72a4432008-03-08 08:34:58 +00001581 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001582 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001583 Width = Target->getPointerWidth(AS);
1584 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +00001585 break;
1586 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00001587 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +00001588 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Reid Kleckner84e9ab42013-03-28 20:02:56 +00001589 llvm::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001590 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001591 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001592 case Type::Complex: {
1593 // Complex types have the same alignment as their elements, but twice the
1594 // size.
Mike Stump1eb44332009-09-09 15:08:12 +00001595 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +00001596 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001597 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +00001598 Align = EltInfo.second;
1599 break;
1600 }
John McCallc12c5bb2010-05-15 11:32:37 +00001601 case Type::ObjCObject:
1602 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +00001603 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001604 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +00001605 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001606 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001607 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +00001608 break;
1609 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001610 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001611 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001612 const TagType *TT = cast<TagType>(T);
1613
1614 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001615 Width = 8;
1616 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001617 break;
1618 }
Mike Stump1eb44332009-09-09 15:08:12 +00001619
Daniel Dunbar1d751182008-11-08 05:48:37 +00001620 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001621 return getTypeInfo(ET->getDecl()->getIntegerType());
1622
Daniel Dunbar1d751182008-11-08 05:48:37 +00001623 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001624 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001625 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001626 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001627 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001628 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001629
Chris Lattner9fcfe922009-10-22 05:17:15 +00001630 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001631 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1632 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001633
Richard Smith34b41d92011-02-20 03:19:35 +00001634 case Type::Auto: {
1635 const AutoType *A = cast<AutoType>(T);
Richard Smithdc7a4f52013-04-30 13:56:41 +00001636 assert(!A->getDeducedType().isNull() &&
1637 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001638 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001639 }
1640
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001641 case Type::Paren:
1642 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1643
Douglas Gregor18857642009-04-30 17:32:17 +00001644 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001645 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001646 std::pair<uint64_t, unsigned> Info
1647 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001648 // If the typedef has an aligned attribute on it, it overrides any computed
1649 // alignment we have. This violates the GCC documentation (which says that
1650 // attribute(aligned) can only round up) but matches its implementation.
1651 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1652 Align = AttrAlign;
1653 else
1654 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001655 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001656 break;
Chris Lattner71763312008-04-06 22:05:18 +00001657 }
Douglas Gregor18857642009-04-30 17:32:17 +00001658
1659 case Type::TypeOfExpr:
1660 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1661 .getTypePtr());
1662
1663 case Type::TypeOf:
1664 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1665
Anders Carlsson395b4752009-06-24 19:06:50 +00001666 case Type::Decltype:
1667 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1668 .getTypePtr());
1669
Sean Huntca63c202011-05-24 22:41:36 +00001670 case Type::UnaryTransform:
1671 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1672
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001673 case Type::Elaborated:
1674 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001675
John McCall9d156a72011-01-06 01:58:22 +00001676 case Type::Attributed:
1677 return getTypeInfo(
1678 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1679
Richard Smith3e4c6c42011-05-05 21:57:07 +00001680 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00001681 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +00001682 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +00001683 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1684 // A type alias template specialization may refer to a typedef with the
1685 // aligned attribute on it.
1686 if (TST->isTypeAlias())
1687 return getTypeInfo(TST->getAliasedType().getTypePtr());
1688 else
1689 return getTypeInfo(getCanonicalType(T));
1690 }
1691
Eli Friedmanb001de72011-10-06 23:00:33 +00001692 case Type::Atomic: {
John McCall9eda3ab2013-03-07 21:37:17 +00001693 // Start with the base type information.
Eli Friedman2be46072011-10-14 20:59:01 +00001694 std::pair<uint64_t, unsigned> Info
1695 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1696 Width = Info.first;
1697 Align = Info.second;
John McCall9eda3ab2013-03-07 21:37:17 +00001698
1699 // If the size of the type doesn't exceed the platform's max
1700 // atomic promotion width, make the size and alignment more
1701 // favorable to atomic operations:
1702 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1703 // Round the size up to a power of 2.
1704 if (!llvm::isPowerOf2_64(Width))
1705 Width = llvm::NextPowerOf2(Width);
1706
1707 // Set the alignment equal to the size.
Eli Friedman2be46072011-10-14 20:59:01 +00001708 Align = static_cast<unsigned>(Width);
1709 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001710 }
1711
Douglas Gregor18857642009-04-30 17:32:17 +00001712 }
Mike Stump1eb44332009-09-09 15:08:12 +00001713
Eli Friedman2be46072011-10-14 20:59:01 +00001714 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001715 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001716}
1717
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001718/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1719CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1720 return CharUnits::fromQuantity(BitSize / getCharWidth());
1721}
1722
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001723/// toBits - Convert a size in characters to a size in characters.
1724int64_t ASTContext::toBits(CharUnits CharSize) const {
1725 return CharSize.getQuantity() * getCharWidth();
1726}
1727
Ken Dyckbdc601b2009-12-22 14:23:30 +00001728/// getTypeSizeInChars - Return the size of the specified type, in characters.
1729/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001730CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001731 return getTypeInfoInChars(T).first;
Ken Dyckbdc601b2009-12-22 14:23:30 +00001732}
Jay Foad4ba2a172011-01-12 09:06:06 +00001733CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001734 return getTypeInfoInChars(T).first;
Ken Dyckbdc601b2009-12-22 14:23:30 +00001735}
1736
Ken Dyck16e20cc2010-01-26 17:25:18 +00001737/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001738/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001739CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001740 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001741}
Jay Foad4ba2a172011-01-12 09:06:06 +00001742CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001743 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001744}
1745
Chris Lattner34ebde42009-01-27 18:08:34 +00001746/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1747/// type for the current target in bits. This can be different than the ABI
1748/// alignment in cases where it is beneficial for performance to overalign
1749/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001750unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001751 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001752
1753 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001754 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001755 T = CT->getElementType().getTypePtr();
1756 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosiercde7a1d2012-03-21 20:20:47 +00001757 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1758 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman1eed6022009-05-25 21:27:19 +00001759 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1760
Chris Lattner34ebde42009-01-27 18:08:34 +00001761 return ABIAlign;
1762}
1763
Ulrich Weigand6b203512013-05-06 16:23:57 +00001764/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1765/// to a global variable of the specified type.
1766unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1767 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1768}
1769
1770/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1771/// should be given to a global variable of the specified type.
1772CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1773 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1774}
1775
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001776/// DeepCollectObjCIvars -
1777/// This routine first collects all declared, but not synthesized, ivars in
1778/// super class and then collects all ivars, including those synthesized for
1779/// current class. This routine is used for implementation of current class
1780/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001781///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001782void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1783 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001784 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001785 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1786 DeepCollectObjCIvars(SuperClass, false, Ivars);
1787 if (!leafClass) {
1788 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1789 E = OI->ivar_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001790 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001791 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001792 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001793 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001794 Iv= Iv->getNextIvar())
1795 Ivars.push_back(Iv);
1796 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001797}
1798
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001799/// CollectInheritedProtocols - Collect all protocols in current class and
1800/// those inherited by it.
1801void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001802 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001803 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001804 // We can use protocol_iterator here instead of
1805 // all_referenced_protocol_iterator since we are walking all categories.
1806 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1807 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001808 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001809 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001810 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001811 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001812 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001813 CollectInheritedProtocols(*P, Protocols);
1814 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001815 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001816
1817 // Categories of this Interface.
Douglas Gregord3297242013-01-16 23:00:23 +00001818 for (ObjCInterfaceDecl::visible_categories_iterator
1819 Cat = OI->visible_categories_begin(),
1820 CatEnd = OI->visible_categories_end();
1821 Cat != CatEnd; ++Cat) {
1822 CollectInheritedProtocols(*Cat, Protocols);
1823 }
1824
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001825 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1826 while (SD) {
1827 CollectInheritedProtocols(SD, Protocols);
1828 SD = SD->getSuperClass();
1829 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001830 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001831 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001832 PE = OC->protocol_end(); P != PE; ++P) {
1833 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001834 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001835 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1836 PE = Proto->protocol_end(); P != PE; ++P)
1837 CollectInheritedProtocols(*P, Protocols);
1838 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001839 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001840 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1841 PE = OP->protocol_end(); P != PE; ++P) {
1842 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001843 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001844 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1845 PE = Proto->protocol_end(); P != PE; ++P)
1846 CollectInheritedProtocols(*P, Protocols);
1847 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001848 }
1849}
1850
Jay Foad4ba2a172011-01-12 09:06:06 +00001851unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001852 unsigned count = 0;
1853 // Count ivars declared in class extension.
Douglas Gregord3297242013-01-16 23:00:23 +00001854 for (ObjCInterfaceDecl::known_extensions_iterator
1855 Ext = OI->known_extensions_begin(),
1856 ExtEnd = OI->known_extensions_end();
1857 Ext != ExtEnd; ++Ext) {
1858 count += Ext->ivar_size();
1859 }
1860
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001861 // Count ivar defined in this class's implementation. This
1862 // includes synthesized ivars.
1863 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001864 count += ImplDecl->ivar_size();
1865
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001866 return count;
1867}
1868
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +00001869bool ASTContext::isSentinelNullExpr(const Expr *E) {
1870 if (!E)
1871 return false;
1872
1873 // nullptr_t is always treated as null.
1874 if (E->getType()->isNullPtrType()) return true;
1875
1876 if (E->getType()->isAnyPointerType() &&
1877 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1878 Expr::NPC_ValueDependentIsNull))
1879 return true;
1880
1881 // Unfortunately, __null has type 'int'.
1882 if (isa<GNUNullExpr>(E)) return true;
1883
1884 return false;
1885}
1886
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001887/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1888ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1889 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1890 I = ObjCImpls.find(D);
1891 if (I != ObjCImpls.end())
1892 return cast<ObjCImplementationDecl>(I->second);
1893 return 0;
1894}
1895/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1896ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1897 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1898 I = ObjCImpls.find(D);
1899 if (I != ObjCImpls.end())
1900 return cast<ObjCCategoryImplDecl>(I->second);
1901 return 0;
1902}
1903
1904/// \brief Set the implementation of ObjCInterfaceDecl.
1905void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1906 ObjCImplementationDecl *ImplD) {
1907 assert(IFaceD && ImplD && "Passed null params");
1908 ObjCImpls[IFaceD] = ImplD;
1909}
1910/// \brief Set the implementation of ObjCCategoryDecl.
1911void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1912 ObjCCategoryImplDecl *ImplD) {
1913 assert(CatD && ImplD && "Passed null params");
1914 ObjCImpls[CatD] = ImplD;
1915}
1916
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001917const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1918 const NamedDecl *ND) const {
1919 if (const ObjCInterfaceDecl *ID =
1920 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001921 return ID;
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001922 if (const ObjCCategoryDecl *CD =
1923 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001924 return CD->getClassInterface();
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001925 if (const ObjCImplDecl *IMD =
1926 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001927 return IMD->getClassInterface();
1928
1929 return 0;
1930}
1931
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001932/// \brief Get the copy initialization expression of VarDecl,or NULL if
1933/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001934Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001935 assert(VD && "Passed null params");
1936 assert(VD->hasAttr<BlocksAttr>() &&
1937 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001938 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001939 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001940 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1941}
1942
1943/// \brief Set the copy inialization expression of a block var decl.
1944void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1945 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001946 assert(VD->hasAttr<BlocksAttr>() &&
1947 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001948 BlockVarCopyInits[VD] = Init;
1949}
1950
John McCalla93c9342009-12-07 02:54:59 +00001951TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001952 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001953 if (!DataSize)
1954 DataSize = TypeLoc::getFullDataSizeForType(T);
1955 else
1956 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001957 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001958
John McCalla93c9342009-12-07 02:54:59 +00001959 TypeSourceInfo *TInfo =
1960 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1961 new (TInfo) TypeSourceInfo(T);
1962 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001963}
1964
John McCalla93c9342009-12-07 02:54:59 +00001965TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001966 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001967 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001968 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001969 return DI;
1970}
1971
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001972const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001973ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001974 return getObjCLayout(D, 0);
1975}
1976
1977const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001978ASTContext::getASTObjCImplementationLayout(
1979 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001980 return getObjCLayout(D->getClassInterface(), D);
1981}
1982
Chris Lattnera7674d82007-07-13 22:13:22 +00001983//===----------------------------------------------------------------------===//
1984// Type creation/memoization methods
1985//===----------------------------------------------------------------------===//
1986
Jay Foad4ba2a172011-01-12 09:06:06 +00001987QualType
John McCall3b657512011-01-19 10:06:00 +00001988ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1989 unsigned fastQuals = quals.getFastQualifiers();
1990 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001991
1992 // Check if we've already instantiated this type.
1993 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001994 ExtQuals::Profile(ID, baseType, quals);
1995 void *insertPos = 0;
1996 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1997 assert(eq->getQualifiers() == quals);
1998 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001999 }
2000
John McCall3b657512011-01-19 10:06:00 +00002001 // If the base type is not canonical, make the appropriate canonical type.
2002 QualType canon;
2003 if (!baseType->isCanonicalUnqualified()) {
2004 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall200fa532012-02-08 00:46:36 +00002005 canonSplit.Quals.addConsistentQualifiers(quals);
2006 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00002007
2008 // Re-find the insert position.
2009 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2010 }
2011
2012 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2013 ExtQualNodes.InsertNode(eq, insertPos);
2014 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00002015}
2016
Jay Foad4ba2a172011-01-12 09:06:06 +00002017QualType
2018ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002019 QualType CanT = getCanonicalType(T);
2020 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00002021 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00002022
John McCall0953e762009-09-24 19:53:00 +00002023 // If we are composing extended qualifiers together, merge together
2024 // into one ExtQuals node.
2025 QualifierCollector Quals;
2026 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002027
John McCall0953e762009-09-24 19:53:00 +00002028 // If this type already has an address space specified, it cannot get
2029 // another one.
2030 assert(!Quals.hasAddressSpace() &&
2031 "Type cannot be in multiple addr spaces!");
2032 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002033
John McCall0953e762009-09-24 19:53:00 +00002034 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00002035}
2036
Chris Lattnerb7d25532009-02-18 22:53:11 +00002037QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00002038 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002039 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00002040 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002041 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00002042
John McCall7f040a92010-12-24 02:08:15 +00002043 if (const PointerType *ptr = T->getAs<PointerType>()) {
2044 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00002045 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00002046 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2047 return getPointerType(ResultType);
2048 }
2049 }
Mike Stump1eb44332009-09-09 15:08:12 +00002050
John McCall0953e762009-09-24 19:53:00 +00002051 // If we are composing extended qualifiers together, merge together
2052 // into one ExtQuals node.
2053 QualifierCollector Quals;
2054 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002055
John McCall0953e762009-09-24 19:53:00 +00002056 // If this type already has an ObjCGC specified, it cannot get
2057 // another one.
2058 assert(!Quals.hasObjCGCAttr() &&
2059 "Type cannot have multiple ObjCGCs!");
2060 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00002061
John McCall0953e762009-09-24 19:53:00 +00002062 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002063}
Chris Lattnera7674d82007-07-13 22:13:22 +00002064
John McCalle6a365d2010-12-19 02:44:49 +00002065const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2066 FunctionType::ExtInfo Info) {
2067 if (T->getExtInfo() == Info)
2068 return T;
2069
2070 QualType Result;
2071 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2072 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
2073 } else {
2074 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2075 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2076 EPI.ExtInfo = Info;
Reid Kleckner0567a792013-06-10 20:51:09 +00002077 Result = getFunctionType(FPT->getResultType(), FPT->getArgTypes(), EPI);
John McCalle6a365d2010-12-19 02:44:49 +00002078 }
2079
2080 return cast<FunctionType>(Result.getTypePtr());
2081}
2082
Richard Smith60e141e2013-05-04 07:00:32 +00002083void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2084 QualType ResultType) {
Richard Smith9dadfab2013-05-11 05:45:24 +00002085 FD = FD->getMostRecentDecl();
2086 while (true) {
Richard Smith60e141e2013-05-04 07:00:32 +00002087 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2088 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2089 FD->setType(getFunctionType(ResultType, FPT->getArgTypes(), EPI));
Richard Smith9dadfab2013-05-11 05:45:24 +00002090 if (FunctionDecl *Next = FD->getPreviousDecl())
2091 FD = Next;
2092 else
2093 break;
Richard Smith60e141e2013-05-04 07:00:32 +00002094 }
Richard Smith9dadfab2013-05-11 05:45:24 +00002095 if (ASTMutationListener *L = getASTMutationListener())
2096 L->DeducedReturnType(FD, ResultType);
Richard Smith60e141e2013-05-04 07:00:32 +00002097}
2098
Reid Spencer5f016e22007-07-11 17:01:13 +00002099/// getComplexType - Return the uniqued reference to the type for a complex
2100/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002101QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002102 // Unique pointers, to guarantee there is only one pointer of a particular
2103 // structure.
2104 llvm::FoldingSetNodeID ID;
2105 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002106
Reid Spencer5f016e22007-07-11 17:01:13 +00002107 void *InsertPos = 0;
2108 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2109 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002110
Reid Spencer5f016e22007-07-11 17:01:13 +00002111 // If the pointee type isn't canonical, this won't be a canonical type either,
2112 // so fill in the canonical type field.
2113 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002114 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002115 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002116
Reid Spencer5f016e22007-07-11 17:01:13 +00002117 // Get the new insert position for the node we care about.
2118 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002119 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002120 }
John McCall6b304a02009-09-24 23:30:46 +00002121 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002122 Types.push_back(New);
2123 ComplexTypes.InsertNode(New, InsertPos);
2124 return QualType(New, 0);
2125}
2126
Reid Spencer5f016e22007-07-11 17:01:13 +00002127/// getPointerType - Return the uniqued reference to the type for a pointer to
2128/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002129QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002130 // Unique pointers, to guarantee there is only one pointer of a particular
2131 // structure.
2132 llvm::FoldingSetNodeID ID;
2133 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002134
Reid Spencer5f016e22007-07-11 17:01:13 +00002135 void *InsertPos = 0;
2136 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2137 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002138
Reid Spencer5f016e22007-07-11 17:01:13 +00002139 // If the pointee type isn't canonical, this won't be a canonical type either,
2140 // so fill in the canonical type field.
2141 QualType Canonical;
Bob Wilsonc90cc932013-03-15 17:12:43 +00002142 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002143 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002144
Bob Wilsonc90cc932013-03-15 17:12:43 +00002145 // Get the new insert position for the node we care about.
2146 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2147 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2148 }
John McCall6b304a02009-09-24 23:30:46 +00002149 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002150 Types.push_back(New);
2151 PointerTypes.InsertNode(New, InsertPos);
2152 return QualType(New, 0);
2153}
2154
Mike Stump1eb44332009-09-09 15:08:12 +00002155/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00002156/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00002157QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00002158 assert(T->isFunctionType() && "block of function types only");
2159 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00002160 // structure.
2161 llvm::FoldingSetNodeID ID;
2162 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002163
Steve Naroff5618bd42008-08-27 16:04:49 +00002164 void *InsertPos = 0;
2165 if (BlockPointerType *PT =
2166 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2167 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002168
2169 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00002170 // type either so fill in the canonical type field.
2171 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002172 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00002173 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002174
Steve Naroff5618bd42008-08-27 16:04:49 +00002175 // Get the new insert position for the node we care about.
2176 BlockPointerType *NewIP =
2177 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002178 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00002179 }
John McCall6b304a02009-09-24 23:30:46 +00002180 BlockPointerType *New
2181 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00002182 Types.push_back(New);
2183 BlockPointerTypes.InsertNode(New, InsertPos);
2184 return QualType(New, 0);
2185}
2186
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002187/// getLValueReferenceType - Return the uniqued reference to the type for an
2188/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002189QualType
2190ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00002191 assert(getCanonicalType(T) != OverloadTy &&
2192 "Unresolved overloaded function type");
2193
Reid Spencer5f016e22007-07-11 17:01:13 +00002194 // Unique pointers, to guarantee there is only one pointer of a particular
2195 // structure.
2196 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002197 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002198
2199 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002200 if (LValueReferenceType *RT =
2201 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002202 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002203
John McCall54e14c42009-10-22 22:37:11 +00002204 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2205
Reid Spencer5f016e22007-07-11 17:01:13 +00002206 // If the referencee type isn't canonical, this won't be a canonical type
2207 // either, so fill in the canonical type field.
2208 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002209 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2210 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2211 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002212
Reid Spencer5f016e22007-07-11 17:01:13 +00002213 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002214 LValueReferenceType *NewIP =
2215 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002216 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002217 }
2218
John McCall6b304a02009-09-24 23:30:46 +00002219 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00002220 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2221 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002222 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002223 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00002224
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002225 return QualType(New, 0);
2226}
2227
2228/// getRValueReferenceType - Return the uniqued reference to the type for an
2229/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002230QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002231 // Unique pointers, to guarantee there is only one pointer of a particular
2232 // structure.
2233 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002234 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002235
2236 void *InsertPos = 0;
2237 if (RValueReferenceType *RT =
2238 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2239 return QualType(RT, 0);
2240
John McCall54e14c42009-10-22 22:37:11 +00002241 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2242
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002243 // If the referencee type isn't canonical, this won't be a canonical type
2244 // either, so fill in the canonical type field.
2245 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002246 if (InnerRef || !T.isCanonical()) {
2247 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2248 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002249
2250 // Get the new insert position for the node we care about.
2251 RValueReferenceType *NewIP =
2252 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002253 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002254 }
2255
John McCall6b304a02009-09-24 23:30:46 +00002256 RValueReferenceType *New
2257 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002258 Types.push_back(New);
2259 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002260 return QualType(New, 0);
2261}
2262
Sebastian Redlf30208a2009-01-24 21:16:55 +00002263/// getMemberPointerType - Return the uniqued reference to the type for a
2264/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00002265QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002266 // Unique pointers, to guarantee there is only one pointer of a particular
2267 // structure.
2268 llvm::FoldingSetNodeID ID;
2269 MemberPointerType::Profile(ID, T, Cls);
2270
2271 void *InsertPos = 0;
2272 if (MemberPointerType *PT =
2273 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2274 return QualType(PT, 0);
2275
2276 // If the pointee or class type isn't canonical, this won't be a canonical
2277 // type either, so fill in the canonical type field.
2278 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00002279 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002280 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2281
2282 // Get the new insert position for the node we care about.
2283 MemberPointerType *NewIP =
2284 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002285 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00002286 }
John McCall6b304a02009-09-24 23:30:46 +00002287 MemberPointerType *New
2288 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002289 Types.push_back(New);
2290 MemberPointerTypes.InsertNode(New, InsertPos);
2291 return QualType(New, 0);
2292}
2293
Mike Stump1eb44332009-09-09 15:08:12 +00002294/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00002295/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002296QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00002297 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00002298 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002299 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00002300 assert((EltTy->isDependentType() ||
2301 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00002302 "Constant array of VLAs is illegal!");
2303
Chris Lattner38aeec72009-05-13 04:12:56 +00002304 // Convert the array size into a canonical width matching the pointer size for
2305 // the target.
2306 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002307 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002308 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00002309
Reid Spencer5f016e22007-07-11 17:01:13 +00002310 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002311 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00002312
Reid Spencer5f016e22007-07-11 17:01:13 +00002313 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002314 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002315 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002316 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002317
John McCall3b657512011-01-19 10:06:00 +00002318 // If the element type isn't canonical or has qualifiers, this won't
2319 // be a canonical type either, so fill in the canonical type field.
2320 QualType Canon;
2321 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2322 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002323 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002324 ASM, IndexTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002325 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00002326
Reid Spencer5f016e22007-07-11 17:01:13 +00002327 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00002328 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002329 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002330 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002331 }
Mike Stump1eb44332009-09-09 15:08:12 +00002332
John McCall6b304a02009-09-24 23:30:46 +00002333 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002334 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002335 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002336 Types.push_back(New);
2337 return QualType(New, 0);
2338}
2339
John McCallce889032011-01-18 08:40:38 +00002340/// getVariableArrayDecayedType - Turns the given type, which may be
2341/// variably-modified, into the corresponding type with all the known
2342/// sizes replaced with [*].
2343QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2344 // Vastly most common case.
2345 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002346
John McCallce889032011-01-18 08:40:38 +00002347 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002348
John McCallce889032011-01-18 08:40:38 +00002349 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00002350 const Type *ty = split.Ty;
John McCallce889032011-01-18 08:40:38 +00002351 switch (ty->getTypeClass()) {
2352#define TYPE(Class, Base)
2353#define ABSTRACT_TYPE(Class, Base)
2354#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2355#include "clang/AST/TypeNodes.def"
2356 llvm_unreachable("didn't desugar past all non-canonical types?");
2357
2358 // These types should never be variably-modified.
2359 case Type::Builtin:
2360 case Type::Complex:
2361 case Type::Vector:
2362 case Type::ExtVector:
2363 case Type::DependentSizedExtVector:
2364 case Type::ObjCObject:
2365 case Type::ObjCInterface:
2366 case Type::ObjCObjectPointer:
2367 case Type::Record:
2368 case Type::Enum:
2369 case Type::UnresolvedUsing:
2370 case Type::TypeOfExpr:
2371 case Type::TypeOf:
2372 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00002373 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00002374 case Type::DependentName:
2375 case Type::InjectedClassName:
2376 case Type::TemplateSpecialization:
2377 case Type::DependentTemplateSpecialization:
2378 case Type::TemplateTypeParm:
2379 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00002380 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00002381 case Type::PackExpansion:
2382 llvm_unreachable("type should never be variably-modified");
2383
2384 // These types can be variably-modified but should never need to
2385 // further decay.
2386 case Type::FunctionNoProto:
2387 case Type::FunctionProto:
2388 case Type::BlockPointer:
2389 case Type::MemberPointer:
2390 return type;
2391
2392 // These types can be variably-modified. All these modifications
2393 // preserve structure except as noted by comments.
2394 // TODO: if we ever care about optimizing VLAs, there are no-op
2395 // optimizations available here.
2396 case Type::Pointer:
2397 result = getPointerType(getVariableArrayDecayedType(
2398 cast<PointerType>(ty)->getPointeeType()));
2399 break;
2400
2401 case Type::LValueReference: {
2402 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2403 result = getLValueReferenceType(
2404 getVariableArrayDecayedType(lv->getPointeeType()),
2405 lv->isSpelledAsLValue());
2406 break;
2407 }
2408
2409 case Type::RValueReference: {
2410 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2411 result = getRValueReferenceType(
2412 getVariableArrayDecayedType(lv->getPointeeType()));
2413 break;
2414 }
2415
Eli Friedmanb001de72011-10-06 23:00:33 +00002416 case Type::Atomic: {
2417 const AtomicType *at = cast<AtomicType>(ty);
2418 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2419 break;
2420 }
2421
John McCallce889032011-01-18 08:40:38 +00002422 case Type::ConstantArray: {
2423 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2424 result = getConstantArrayType(
2425 getVariableArrayDecayedType(cat->getElementType()),
2426 cat->getSize(),
2427 cat->getSizeModifier(),
2428 cat->getIndexTypeCVRQualifiers());
2429 break;
2430 }
2431
2432 case Type::DependentSizedArray: {
2433 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2434 result = getDependentSizedArrayType(
2435 getVariableArrayDecayedType(dat->getElementType()),
2436 dat->getSizeExpr(),
2437 dat->getSizeModifier(),
2438 dat->getIndexTypeCVRQualifiers(),
2439 dat->getBracketsRange());
2440 break;
2441 }
2442
2443 // Turn incomplete types into [*] types.
2444 case Type::IncompleteArray: {
2445 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2446 result = getVariableArrayType(
2447 getVariableArrayDecayedType(iat->getElementType()),
2448 /*size*/ 0,
2449 ArrayType::Normal,
2450 iat->getIndexTypeCVRQualifiers(),
2451 SourceRange());
2452 break;
2453 }
2454
2455 // Turn VLA types into [*] types.
2456 case Type::VariableArray: {
2457 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2458 result = getVariableArrayType(
2459 getVariableArrayDecayedType(vat->getElementType()),
2460 /*size*/ 0,
2461 ArrayType::Star,
2462 vat->getIndexTypeCVRQualifiers(),
2463 vat->getBracketsRange());
2464 break;
2465 }
2466 }
2467
2468 // Apply the top-level qualifiers from the original.
John McCall200fa532012-02-08 00:46:36 +00002469 return getQualifiedType(result, split.Quals);
John McCallce889032011-01-18 08:40:38 +00002470}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002471
Steve Naroffbdbf7b02007-08-30 18:14:25 +00002472/// getVariableArrayType - Returns a non-unique reference to the type for a
2473/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002474QualType ASTContext::getVariableArrayType(QualType EltTy,
2475 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00002476 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002477 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00002478 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002479 // Since we don't unique expressions, it isn't possible to unique VLA's
2480 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00002481 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00002482
John McCall3b657512011-01-19 10:06:00 +00002483 // Be sure to pull qualifiers off the element type.
2484 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2485 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002486 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002487 IndexTypeQuals, Brackets);
John McCall200fa532012-02-08 00:46:36 +00002488 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor715e9c82010-05-23 16:10:32 +00002489 }
2490
John McCall6b304a02009-09-24 23:30:46 +00002491 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002492 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002493
2494 VariableArrayTypes.push_back(New);
2495 Types.push_back(New);
2496 return QualType(New, 0);
2497}
2498
Douglas Gregor898574e2008-12-05 23:32:09 +00002499/// getDependentSizedArrayType - Returns a non-unique reference to
2500/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00002501/// type.
John McCall3b657512011-01-19 10:06:00 +00002502QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2503 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00002504 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002505 unsigned elementTypeQuals,
2506 SourceRange brackets) const {
2507 assert((!numElements || numElements->isTypeDependent() ||
2508 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00002509 "Size must be type- or value-dependent!");
2510
John McCall3b657512011-01-19 10:06:00 +00002511 // Dependently-sized array types that do not have a specified number
2512 // of elements will have their sizes deduced from a dependent
2513 // initializer. We do no canonicalization here at all, which is okay
2514 // because they can't be used in most locations.
2515 if (!numElements) {
2516 DependentSizedArrayType *newType
2517 = new (*this, TypeAlignment)
2518 DependentSizedArrayType(*this, elementType, QualType(),
2519 numElements, ASM, elementTypeQuals,
2520 brackets);
2521 Types.push_back(newType);
2522 return QualType(newType, 0);
2523 }
2524
2525 // Otherwise, we actually build a new type every time, but we
2526 // also build a canonical type.
2527
2528 SplitQualType canonElementType = getCanonicalType(elementType).split();
2529
2530 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00002531 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002532 DependentSizedArrayType::Profile(ID, *this,
John McCall200fa532012-02-08 00:46:36 +00002533 QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002534 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002535
John McCall3b657512011-01-19 10:06:00 +00002536 // Look for an existing type with these properties.
2537 DependentSizedArrayType *canonTy =
2538 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002539
John McCall3b657512011-01-19 10:06:00 +00002540 // If we don't have one, build one.
2541 if (!canonTy) {
2542 canonTy = new (*this, TypeAlignment)
John McCall200fa532012-02-08 00:46:36 +00002543 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002544 QualType(), numElements, ASM, elementTypeQuals,
2545 brackets);
2546 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2547 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002548 }
2549
John McCall3b657512011-01-19 10:06:00 +00002550 // Apply qualifiers from the element type to the array.
2551 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall200fa532012-02-08 00:46:36 +00002552 canonElementType.Quals);
Mike Stump1eb44332009-09-09 15:08:12 +00002553
John McCall3b657512011-01-19 10:06:00 +00002554 // If we didn't need extra canonicalization for the element type,
2555 // then just use that as our result.
John McCall200fa532012-02-08 00:46:36 +00002556 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall3b657512011-01-19 10:06:00 +00002557 return canon;
2558
2559 // Otherwise, we need to build a type which follows the spelling
2560 // of the element type.
2561 DependentSizedArrayType *sugaredType
2562 = new (*this, TypeAlignment)
2563 DependentSizedArrayType(*this, elementType, canon, numElements,
2564 ASM, elementTypeQuals, brackets);
2565 Types.push_back(sugaredType);
2566 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00002567}
2568
John McCall3b657512011-01-19 10:06:00 +00002569QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00002570 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002571 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002572 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002573 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002574
John McCall3b657512011-01-19 10:06:00 +00002575 void *insertPos = 0;
2576 if (IncompleteArrayType *iat =
2577 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2578 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002579
2580 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00002581 // either, so fill in the canonical type field. We also have to pull
2582 // qualifiers off the element type.
2583 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00002584
John McCall3b657512011-01-19 10:06:00 +00002585 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2586 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall200fa532012-02-08 00:46:36 +00002587 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002588 ASM, elementTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002589 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002590
2591 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00002592 IncompleteArrayType *existing =
2593 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2594 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00002595 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00002596
John McCall3b657512011-01-19 10:06:00 +00002597 IncompleteArrayType *newType = new (*this, TypeAlignment)
2598 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002599
John McCall3b657512011-01-19 10:06:00 +00002600 IncompleteArrayTypes.InsertNode(newType, insertPos);
2601 Types.push_back(newType);
2602 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00002603}
2604
Steve Naroff73322922007-07-18 18:00:27 +00002605/// getVectorType - Return the unique reference to a vector type of
2606/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00002607QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00002608 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00002609 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00002610
Reid Spencer5f016e22007-07-11 17:01:13 +00002611 // Check if we've already instantiated a vector of this type.
2612 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00002613 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00002614
Reid Spencer5f016e22007-07-11 17:01:13 +00002615 void *InsertPos = 0;
2616 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2617 return QualType(VTP, 0);
2618
2619 // If the element type isn't canonical, this won't be a canonical type either,
2620 // so fill in the canonical type field.
2621 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00002622 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00002623 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002624
Reid Spencer5f016e22007-07-11 17:01:13 +00002625 // Get the new insert position for the node we care about.
2626 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002627 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002628 }
John McCall6b304a02009-09-24 23:30:46 +00002629 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00002630 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002631 VectorTypes.InsertNode(New, InsertPos);
2632 Types.push_back(New);
2633 return QualType(New, 0);
2634}
2635
Nate Begeman213541a2008-04-18 23:10:10 +00002636/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00002637/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002638QualType
2639ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00002640 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00002641
Steve Naroff73322922007-07-18 18:00:27 +00002642 // Check if we've already instantiated a vector of this type.
2643 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00002644 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002645 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00002646 void *InsertPos = 0;
2647 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2648 return QualType(VTP, 0);
2649
2650 // If the element type isn't canonical, this won't be a canonical type either,
2651 // so fill in the canonical type field.
2652 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002653 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002654 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00002655
Steve Naroff73322922007-07-18 18:00:27 +00002656 // Get the new insert position for the node we care about.
2657 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002658 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00002659 }
John McCall6b304a02009-09-24 23:30:46 +00002660 ExtVectorType *New = new (*this, TypeAlignment)
2661 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00002662 VectorTypes.InsertNode(New, InsertPos);
2663 Types.push_back(New);
2664 return QualType(New, 0);
2665}
2666
Jay Foad4ba2a172011-01-12 09:06:06 +00002667QualType
2668ASTContext::getDependentSizedExtVectorType(QualType vecType,
2669 Expr *SizeExpr,
2670 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002671 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002672 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002673 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002674
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002675 void *InsertPos = 0;
2676 DependentSizedExtVectorType *Canon
2677 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2678 DependentSizedExtVectorType *New;
2679 if (Canon) {
2680 // We already have a canonical version of this array type; use it as
2681 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002682 New = new (*this, TypeAlignment)
2683 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2684 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002685 } else {
2686 QualType CanonVecTy = getCanonicalType(vecType);
2687 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002688 New = new (*this, TypeAlignment)
2689 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2690 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002691
2692 DependentSizedExtVectorType *CanonCheck
2693 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2694 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2695 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002696 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2697 } else {
2698 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2699 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002700 New = new (*this, TypeAlignment)
2701 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002702 }
2703 }
Mike Stump1eb44332009-09-09 15:08:12 +00002704
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002705 Types.push_back(New);
2706 return QualType(New, 0);
2707}
2708
Douglas Gregor72564e72009-02-26 23:50:07 +00002709/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002710///
Jay Foad4ba2a172011-01-12 09:06:06 +00002711QualType
2712ASTContext::getFunctionNoProtoType(QualType ResultTy,
2713 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00002714 const CallingConv DefaultCC = Info.getCC();
2715 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2716 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00002717 // Unique functions, to guarantee there is only one function of a particular
2718 // structure.
2719 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002720 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002721
Reid Spencer5f016e22007-07-11 17:01:13 +00002722 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002723 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002724 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002725 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002726
Reid Spencer5f016e22007-07-11 17:01:13 +00002727 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00002728 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00002729 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00002730 Canonical =
2731 getFunctionNoProtoType(getCanonicalType(ResultTy),
2732 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00002733
Reid Spencer5f016e22007-07-11 17:01:13 +00002734 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002735 FunctionNoProtoType *NewIP =
2736 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002737 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002738 }
Mike Stump1eb44332009-09-09 15:08:12 +00002739
Roman Divackycfe9af22011-03-01 17:40:53 +00002740 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002741 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002742 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002743 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002744 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002745 return QualType(New, 0);
2746}
2747
Douglas Gregor02dd7982013-01-17 23:36:45 +00002748/// \brief Determine whether \p T is canonical as the result type of a function.
2749static bool isCanonicalResultType(QualType T) {
2750 return T.isCanonical() &&
2751 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2752 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2753}
2754
Reid Spencer5f016e22007-07-11 17:01:13 +00002755/// getFunctionType - Return a normal function type with a typed argument
2756/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002757QualType
Jordan Rosebea522f2013-03-08 21:51:21 +00002758ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad4ba2a172011-01-12 09:06:06 +00002759 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rosebea522f2013-03-08 21:51:21 +00002760 size_t NumArgs = ArgArray.size();
2761
Reid Spencer5f016e22007-07-11 17:01:13 +00002762 // Unique functions, to guarantee there is only one function of a particular
2763 // structure.
2764 llvm::FoldingSetNodeID ID;
Jordan Rosebea522f2013-03-08 21:51:21 +00002765 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2766 *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002767
2768 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002769 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002770 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002771 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002772
2773 // Determine whether the type being created is already canonical or not.
Richard Smitheefb3d52012-02-10 09:58:53 +00002774 bool isCanonical =
Douglas Gregor02dd7982013-01-17 23:36:45 +00002775 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smitheefb3d52012-02-10 09:58:53 +00002776 !EPI.HasTrailingReturn;
Reid Spencer5f016e22007-07-11 17:01:13 +00002777 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002778 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002779 isCanonical = false;
2780
Roman Divackycfe9af22011-03-01 17:40:53 +00002781 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2782 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2783 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002784
Reid Spencer5f016e22007-07-11 17:01:13 +00002785 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002786 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002787 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002788 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002789 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002790 CanonicalArgs.reserve(NumArgs);
2791 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002792 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002793
John McCalle23cf432010-12-14 08:05:40 +00002794 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +00002795 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002796 CanonicalEPI.ExceptionSpecType = EST_None;
2797 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002798 CanonicalEPI.ExtInfo
2799 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2800
Douglas Gregor02dd7982013-01-17 23:36:45 +00002801 // Result types do not have ARC lifetime qualifiers.
2802 QualType CanResultTy = getCanonicalType(ResultTy);
2803 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2804 Qualifiers Qs = CanResultTy.getQualifiers();
2805 Qs.removeObjCLifetime();
2806 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2807 }
2808
Jordan Rosebea522f2013-03-08 21:51:21 +00002809 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002810
Reid Spencer5f016e22007-07-11 17:01:13 +00002811 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002812 FunctionProtoType *NewIP =
2813 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002814 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002815 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002816
John McCallf85e1932011-06-15 23:02:42 +00002817 // FunctionProtoType objects are allocated with extra bytes after
2818 // them for three variable size arrays at the end:
2819 // - parameter types
2820 // - exception types
2821 // - consumed-arguments flags
2822 // Instead of the exception types, there could be a noexcept
Richard Smithb9d0b762012-07-27 04:22:15 +00002823 // expression, or information used to resolve the exception
2824 // specification.
John McCalle23cf432010-12-14 08:05:40 +00002825 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002826 NumArgs * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002827 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00002828 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002829 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002830 Size += sizeof(Expr*);
Richard Smithe6975e92012-04-17 00:58:00 +00002831 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smith13bffc52012-04-19 00:08:28 +00002832 Size += 2 * sizeof(FunctionDecl*);
Richard Smithb9d0b762012-07-27 04:22:15 +00002833 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2834 Size += sizeof(FunctionDecl*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002835 }
John McCallf85e1932011-06-15 23:02:42 +00002836 if (EPI.ConsumedArguments)
2837 Size += NumArgs * sizeof(bool);
2838
John McCalle23cf432010-12-14 08:05:40 +00002839 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002840 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2841 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Jordan Rosebea522f2013-03-08 21:51:21 +00002842 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002843 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002844 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002845 return QualType(FTP, 0);
2846}
2847
John McCall3cb0ebd2010-03-10 03:28:59 +00002848#ifndef NDEBUG
2849static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2850 if (!isa<CXXRecordDecl>(D)) return false;
2851 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2852 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2853 return true;
2854 if (RD->getDescribedClassTemplate() &&
2855 !isa<ClassTemplateSpecializationDecl>(RD))
2856 return true;
2857 return false;
2858}
2859#endif
2860
2861/// getInjectedClassNameType - Return the unique reference to the
2862/// injected class name type for the specified templated declaration.
2863QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002864 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002865 assert(NeedsInjectedClassNameType(Decl));
2866 if (Decl->TypeForDecl) {
2867 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregoref96ee02012-01-14 16:38:05 +00002868 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002869 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2870 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2871 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2872 } else {
John McCallf4c73712011-01-19 06:33:43 +00002873 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002874 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002875 Decl->TypeForDecl = newType;
2876 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002877 }
2878 return QualType(Decl->TypeForDecl, 0);
2879}
2880
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002881/// getTypeDeclType - Return the unique reference to the type for the
2882/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002883QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002884 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002885 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002886
Richard Smith162e1c12011-04-15 14:24:37 +00002887 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002888 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002889
John McCallbecb8d52010-03-10 06:48:02 +00002890 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2891 "Template type parameter types are always available.");
2892
John McCall19c85762010-02-16 03:57:14 +00002893 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002894 assert(!Record->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002895 "struct/union has previous declaration");
2896 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002897 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002898 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002899 assert(!Enum->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002900 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002901 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002902 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002903 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002904 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2905 Decl->TypeForDecl = newType;
2906 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002907 } else
John McCallbecb8d52010-03-10 06:48:02 +00002908 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002909
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002910 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002911}
2912
Reid Spencer5f016e22007-07-11 17:01:13 +00002913/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002914/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002915QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002916ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2917 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002918 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002919
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002920 if (Canonical.isNull())
2921 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002922 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002923 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002924 Decl->TypeForDecl = newType;
2925 Types.push_back(newType);
2926 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002927}
2928
Jay Foad4ba2a172011-01-12 09:06:06 +00002929QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002930 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2931
Douglas Gregoref96ee02012-01-14 16:38:05 +00002932 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002933 if (PrevDecl->TypeForDecl)
2934 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2935
John McCallf4c73712011-01-19 06:33:43 +00002936 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2937 Decl->TypeForDecl = newType;
2938 Types.push_back(newType);
2939 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002940}
2941
Jay Foad4ba2a172011-01-12 09:06:06 +00002942QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002943 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2944
Douglas Gregoref96ee02012-01-14 16:38:05 +00002945 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002946 if (PrevDecl->TypeForDecl)
2947 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2948
John McCallf4c73712011-01-19 06:33:43 +00002949 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2950 Decl->TypeForDecl = newType;
2951 Types.push_back(newType);
2952 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002953}
2954
John McCall9d156a72011-01-06 01:58:22 +00002955QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2956 QualType modifiedType,
2957 QualType equivalentType) {
2958 llvm::FoldingSetNodeID id;
2959 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2960
2961 void *insertPos = 0;
2962 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2963 if (type) return QualType(type, 0);
2964
2965 QualType canon = getCanonicalType(equivalentType);
2966 type = new (*this, TypeAlignment)
2967 AttributedType(canon, attrKind, modifiedType, equivalentType);
2968
2969 Types.push_back(type);
2970 AttributedTypes.InsertNode(type, insertPos);
2971
2972 return QualType(type, 0);
2973}
2974
2975
John McCall49a832b2009-10-18 09:09:24 +00002976/// \brief Retrieve a substitution-result type.
2977QualType
2978ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002979 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002980 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002981 && "replacement types must always be canonical");
2982
2983 llvm::FoldingSetNodeID ID;
2984 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2985 void *InsertPos = 0;
2986 SubstTemplateTypeParmType *SubstParm
2987 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2988
2989 if (!SubstParm) {
2990 SubstParm = new (*this, TypeAlignment)
2991 SubstTemplateTypeParmType(Parm, Replacement);
2992 Types.push_back(SubstParm);
2993 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2994 }
2995
2996 return QualType(SubstParm, 0);
2997}
2998
Douglas Gregorc3069d62011-01-14 02:55:32 +00002999/// \brief Retrieve a
3000QualType ASTContext::getSubstTemplateTypeParmPackType(
3001 const TemplateTypeParmType *Parm,
3002 const TemplateArgument &ArgPack) {
3003#ifndef NDEBUG
3004 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
3005 PEnd = ArgPack.pack_end();
3006 P != PEnd; ++P) {
3007 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3008 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
3009 }
3010#endif
3011
3012 llvm::FoldingSetNodeID ID;
3013 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3014 void *InsertPos = 0;
3015 if (SubstTemplateTypeParmPackType *SubstParm
3016 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3017 return QualType(SubstParm, 0);
3018
3019 QualType Canon;
3020 if (!Parm->isCanonicalUnqualified()) {
3021 Canon = getCanonicalType(QualType(Parm, 0));
3022 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3023 ArgPack);
3024 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3025 }
3026
3027 SubstTemplateTypeParmPackType *SubstParm
3028 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3029 ArgPack);
3030 Types.push_back(SubstParm);
3031 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3032 return QualType(SubstParm, 0);
3033}
3034
Douglas Gregorfab9d672009-02-05 23:33:38 +00003035/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00003036/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003037/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00003038QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003039 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003040 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00003041 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003042 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00003043 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003044 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00003045 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3046
3047 if (TypeParm)
3048 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003049
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003050 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003051 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003052 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003053
3054 TemplateTypeParmType *TypeCheck
3055 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3056 assert(!TypeCheck && "Template type parameter canonical type broken");
3057 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003058 } else
John McCall6b304a02009-09-24 23:30:46 +00003059 TypeParm = new (*this, TypeAlignment)
3060 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00003061
3062 Types.push_back(TypeParm);
3063 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3064
3065 return QualType(TypeParm, 0);
3066}
3067
John McCall3cb0ebd2010-03-10 03:28:59 +00003068TypeSourceInfo *
3069ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3070 SourceLocation NameLoc,
3071 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003072 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003073 assert(!Name.getAsDependentTemplateName() &&
3074 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00003075 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00003076
3077 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie39e6ab42013-02-18 22:06:02 +00003078 TemplateSpecializationTypeLoc TL =
3079 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara55d23c92012-02-06 14:41:24 +00003080 TL.setTemplateKeywordLoc(SourceLocation());
John McCall3cb0ebd2010-03-10 03:28:59 +00003081 TL.setTemplateNameLoc(NameLoc);
3082 TL.setLAngleLoc(Args.getLAngleLoc());
3083 TL.setRAngleLoc(Args.getRAngleLoc());
3084 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3085 TL.setArgLocInfo(i, Args[i].getLocInfo());
3086 return DI;
3087}
3088
Mike Stump1eb44332009-09-09 15:08:12 +00003089QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00003090ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00003091 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003092 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003093 assert(!Template.getAsDependentTemplateName() &&
3094 "No dependent template names here!");
3095
John McCalld5532b62009-11-23 01:53:49 +00003096 unsigned NumArgs = Args.size();
3097
Chris Lattner5f9e2722011-07-23 10:55:15 +00003098 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00003099 ArgVec.reserve(NumArgs);
3100 for (unsigned i = 0; i != NumArgs; ++i)
3101 ArgVec.push_back(Args[i].getArgument());
3102
John McCall31f17ec2010-04-27 00:57:59 +00003103 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003104 Underlying);
John McCall833ca992009-10-29 08:12:44 +00003105}
3106
Douglas Gregorb70126a2012-02-03 17:16:23 +00003107#ifndef NDEBUG
3108static bool hasAnyPackExpansions(const TemplateArgument *Args,
3109 unsigned NumArgs) {
3110 for (unsigned I = 0; I != NumArgs; ++I)
3111 if (Args[I].isPackExpansion())
3112 return true;
3113
3114 return true;
3115}
3116#endif
3117
John McCall833ca992009-10-29 08:12:44 +00003118QualType
3119ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003120 const TemplateArgument *Args,
3121 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003122 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003123 assert(!Template.getAsDependentTemplateName() &&
3124 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003125 // Look through qualified template names.
3126 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3127 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003128
Douglas Gregorb70126a2012-02-03 17:16:23 +00003129 bool IsTypeAlias =
Richard Smith3e4c6c42011-05-05 21:57:07 +00003130 Template.getAsTemplateDecl() &&
3131 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00003132 QualType CanonType;
3133 if (!Underlying.isNull())
3134 CanonType = getCanonicalType(Underlying);
3135 else {
Douglas Gregorb70126a2012-02-03 17:16:23 +00003136 // We can get here with an alias template when the specialization contains
3137 // a pack expansion that does not match up with a parameter pack.
3138 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3139 "Caller must compute aliased type");
3140 IsTypeAlias = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00003141 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3142 NumArgs);
3143 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00003144
Douglas Gregor1275ae02009-07-28 23:00:59 +00003145 // Allocate the (non-canonical) template specialization type, but don't
3146 // try to unique it: these types typically have location information that
3147 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00003148 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3149 sizeof(TemplateArgument) * NumArgs +
Douglas Gregorb70126a2012-02-03 17:16:23 +00003150 (IsTypeAlias? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00003151 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00003152 TemplateSpecializationType *Spec
Douglas Gregorb70126a2012-02-03 17:16:23 +00003153 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3154 IsTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00003155
Douglas Gregor55f6b142009-02-09 18:46:07 +00003156 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00003157 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00003158}
3159
Mike Stump1eb44332009-09-09 15:08:12 +00003160QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003161ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3162 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00003163 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003164 assert(!Template.getAsDependentTemplateName() &&
3165 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00003166
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003167 // Look through qualified template names.
3168 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3169 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003170
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003171 // Build the canonical template specialization type.
3172 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003173 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003174 CanonArgs.reserve(NumArgs);
3175 for (unsigned I = 0; I != NumArgs; ++I)
3176 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3177
3178 // Determine whether this canonical template specialization type already
3179 // exists.
3180 llvm::FoldingSetNodeID ID;
3181 TemplateSpecializationType::Profile(ID, CanonTemplate,
3182 CanonArgs.data(), NumArgs, *this);
3183
3184 void *InsertPos = 0;
3185 TemplateSpecializationType *Spec
3186 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3187
3188 if (!Spec) {
3189 // Allocate a new canonical template specialization type.
3190 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3191 sizeof(TemplateArgument) * NumArgs),
3192 TypeAlignment);
3193 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3194 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003195 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003196 Types.push_back(Spec);
3197 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3198 }
3199
3200 assert(Spec->isDependentType() &&
3201 "Non-dependent template-id type must have a canonical type");
3202 return QualType(Spec, 0);
3203}
3204
3205QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003206ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3207 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00003208 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00003209 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003210 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003211
3212 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003213 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003214 if (T)
3215 return QualType(T, 0);
3216
Douglas Gregor789b1f62010-02-04 18:10:26 +00003217 QualType Canon = NamedType;
3218 if (!Canon.isCanonical()) {
3219 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003220 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3221 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00003222 (void)CheckT;
3223 }
3224
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003225 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003226 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003227 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003228 return QualType(T, 0);
3229}
3230
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003231QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00003232ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003233 llvm::FoldingSetNodeID ID;
3234 ParenType::Profile(ID, InnerType);
3235
3236 void *InsertPos = 0;
3237 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3238 if (T)
3239 return QualType(T, 0);
3240
3241 QualType Canon = InnerType;
3242 if (!Canon.isCanonical()) {
3243 Canon = getCanonicalType(InnerType);
3244 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3245 assert(!CheckT && "Paren canonical type broken");
3246 (void)CheckT;
3247 }
3248
3249 T = new (*this) ParenType(InnerType, Canon);
3250 Types.push_back(T);
3251 ParenTypes.InsertNode(T, InsertPos);
3252 return QualType(T, 0);
3253}
3254
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003255QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3256 NestedNameSpecifier *NNS,
3257 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003258 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00003259 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3260
3261 if (Canon.isNull()) {
3262 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003263 ElaboratedTypeKeyword CanonKeyword = Keyword;
3264 if (Keyword == ETK_None)
3265 CanonKeyword = ETK_Typename;
3266
3267 if (CanonNNS != NNS || CanonKeyword != Keyword)
3268 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003269 }
3270
3271 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003272 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003273
3274 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00003275 DependentNameType *T
3276 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00003277 if (T)
3278 return QualType(T, 0);
3279
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003280 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00003281 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00003282 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003283 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00003284}
3285
Mike Stump1eb44332009-09-09 15:08:12 +00003286QualType
John McCall33500952010-06-11 00:33:02 +00003287ASTContext::getDependentTemplateSpecializationType(
3288 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003289 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00003290 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003291 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00003292 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00003293 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00003294 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3295 ArgCopy.push_back(Args[I].getArgument());
3296 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3297 ArgCopy.size(),
3298 ArgCopy.data());
3299}
3300
3301QualType
3302ASTContext::getDependentTemplateSpecializationType(
3303 ElaboratedTypeKeyword Keyword,
3304 NestedNameSpecifier *NNS,
3305 const IdentifierInfo *Name,
3306 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00003307 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003308 assert((!NNS || NNS->isDependent()) &&
3309 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00003310
Douglas Gregor789b1f62010-02-04 18:10:26 +00003311 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00003312 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3313 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003314
3315 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00003316 DependentTemplateSpecializationType *T
3317 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003318 if (T)
3319 return QualType(T, 0);
3320
John McCall33500952010-06-11 00:33:02 +00003321 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003322
John McCall33500952010-06-11 00:33:02 +00003323 ElaboratedTypeKeyword CanonKeyword = Keyword;
3324 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3325
3326 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003327 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00003328 for (unsigned I = 0; I != NumArgs; ++I) {
3329 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3330 if (!CanonArgs[I].structurallyEquals(Args[I]))
3331 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00003332 }
3333
John McCall33500952010-06-11 00:33:02 +00003334 QualType Canon;
3335 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3336 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3337 Name, NumArgs,
3338 CanonArgs.data());
3339
3340 // Find the insert position again.
3341 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3342 }
3343
3344 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3345 sizeof(TemplateArgument) * NumArgs),
3346 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00003347 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00003348 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00003349 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00003350 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003351 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00003352}
3353
Douglas Gregorcded4f62011-01-14 17:04:44 +00003354QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikiedc84cd52013-02-20 22:23:23 +00003355 Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00003356 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00003357 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003358
3359 assert(Pattern->containsUnexpandedParameterPack() &&
3360 "Pack expansions must expand one or more parameter packs");
3361 void *InsertPos = 0;
3362 PackExpansionType *T
3363 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3364 if (T)
3365 return QualType(T, 0);
3366
3367 QualType Canon;
3368 if (!Pattern.isCanonical()) {
Richard Smithd8672ef2012-07-16 00:20:35 +00003369 Canon = getCanonicalType(Pattern);
3370 // The canonical type might not contain an unexpanded parameter pack, if it
3371 // contains an alias template specialization which ignores one of its
3372 // parameters.
3373 if (Canon->containsUnexpandedParameterPack()) {
3374 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003375
Richard Smithd8672ef2012-07-16 00:20:35 +00003376 // Find the insert position again, in case we inserted an element into
3377 // PackExpansionTypes and invalidated our insert position.
3378 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3379 }
Douglas Gregor7536dd52010-12-20 02:24:11 +00003380 }
3381
Douglas Gregorcded4f62011-01-14 17:04:44 +00003382 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003383 Types.push_back(T);
3384 PackExpansionTypes.InsertNode(T, InsertPos);
3385 return QualType(T, 0);
3386}
3387
Chris Lattner88cb27a2008-04-07 04:56:42 +00003388/// CmpProtocolNames - Comparison predicate for sorting protocols
3389/// alphabetically.
3390static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3391 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003392 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00003393}
3394
John McCallc12c5bb2010-05-15 11:32:37 +00003395static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00003396 unsigned NumProtocols) {
3397 if (NumProtocols == 0) return true;
3398
Douglas Gregor61cc2962012-01-02 02:00:30 +00003399 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3400 return false;
3401
John McCall54e14c42009-10-22 22:37:11 +00003402 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregor61cc2962012-01-02 02:00:30 +00003403 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3404 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCall54e14c42009-10-22 22:37:11 +00003405 return false;
3406 return true;
3407}
3408
3409static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00003410 unsigned &NumProtocols) {
3411 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00003412
Chris Lattner88cb27a2008-04-07 04:56:42 +00003413 // Sort protocols, keyed by name.
3414 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3415
Douglas Gregor61cc2962012-01-02 02:00:30 +00003416 // Canonicalize.
3417 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3418 Protocols[I] = Protocols[I]->getCanonicalDecl();
3419
Chris Lattner88cb27a2008-04-07 04:56:42 +00003420 // Remove duplicates.
3421 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3422 NumProtocols = ProtocolsEnd-Protocols;
3423}
3424
John McCallc12c5bb2010-05-15 11:32:37 +00003425QualType ASTContext::getObjCObjectType(QualType BaseType,
3426 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00003427 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003428 // If the base type is an interface and there aren't any protocols
3429 // to add, then the interface type will do just fine.
3430 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3431 return BaseType;
3432
3433 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003434 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00003435 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003436 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00003437 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3438 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003439
John McCallc12c5bb2010-05-15 11:32:37 +00003440 // Build the canonical type, which has the canonical base type and
3441 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00003442 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00003443 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3444 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3445 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003446 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00003447 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003448 unsigned UniqueCount = NumProtocols;
3449
John McCall54e14c42009-10-22 22:37:11 +00003450 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00003451 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3452 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00003453 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00003454 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3455 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003456 }
3457
3458 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00003459 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3460 }
3461
3462 unsigned Size = sizeof(ObjCObjectTypeImpl);
3463 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3464 void *Mem = Allocate(Size, TypeAlignment);
3465 ObjCObjectTypeImpl *T =
3466 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3467
3468 Types.push_back(T);
3469 ObjCObjectTypes.InsertNode(T, InsertPos);
3470 return QualType(T, 0);
3471}
3472
3473/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3474/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003475QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003476 llvm::FoldingSetNodeID ID;
3477 ObjCObjectPointerType::Profile(ID, ObjectT);
3478
3479 void *InsertPos = 0;
3480 if (ObjCObjectPointerType *QT =
3481 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3482 return QualType(QT, 0);
3483
3484 // Find the canonical object type.
3485 QualType Canonical;
3486 if (!ObjectT.isCanonical()) {
3487 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3488
3489 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00003490 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3491 }
3492
Douglas Gregorfd6a0882010-02-08 22:59:26 +00003493 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00003494 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3495 ObjCObjectPointerType *QType =
3496 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00003497
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003498 Types.push_back(QType);
3499 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00003500 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003501}
Chris Lattner88cb27a2008-04-07 04:56:42 +00003502
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003503/// getObjCInterfaceType - Return the unique reference to the type for the
3504/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00003505QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3506 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003507 if (Decl->TypeForDecl)
3508 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003509
Douglas Gregor0af55012011-12-16 03:12:41 +00003510 if (PrevDecl) {
3511 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3512 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3513 return QualType(PrevDecl->TypeForDecl, 0);
3514 }
3515
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00003516 // Prefer the definition, if there is one.
3517 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3518 Decl = Def;
3519
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003520 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3521 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3522 Decl->TypeForDecl = T;
3523 Types.push_back(T);
3524 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00003525}
3526
Douglas Gregor72564e72009-02-26 23:50:07 +00003527/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3528/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00003529/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00003530/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003531/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003532QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003533 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00003534 if (tofExpr->isTypeDependent()) {
3535 llvm::FoldingSetNodeID ID;
3536 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00003537
Douglas Gregorb1975722009-07-30 23:18:24 +00003538 void *InsertPos = 0;
3539 DependentTypeOfExprType *Canon
3540 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3541 if (Canon) {
3542 // We already have a "canonical" version of an identical, dependent
3543 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00003544 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00003545 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003546 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00003547 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003548 Canon
3549 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00003550 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3551 toe = Canon;
3552 }
3553 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003554 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00003555 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00003556 }
Steve Naroff9752f252007-08-01 18:02:17 +00003557 Types.push_back(toe);
3558 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003559}
3560
Steve Naroff9752f252007-08-01 18:02:17 +00003561/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3562/// TypeOfType AST's. The only motivation to unique these nodes would be
3563/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003564/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003565/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003566QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00003567 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00003568 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00003569 Types.push_back(tot);
3570 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003571}
3572
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00003573
Anders Carlsson395b4752009-06-24 19:06:50 +00003574/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3575/// DecltypeType AST's. The only motivation to unique these nodes would be
3576/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003577/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00003578/// on canonical types (which are always unique).
Douglas Gregorf8af9822012-02-12 18:42:33 +00003579QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003580 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00003581
3582 // C++0x [temp.type]p2:
3583 // If an expression e involves a template parameter, decltype(e) denotes a
3584 // unique dependent type. Two such decltype-specifiers refer to the same
3585 // type only if their expressions are equivalent (14.5.6.1).
3586 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003587 llvm::FoldingSetNodeID ID;
3588 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00003589
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003590 void *InsertPos = 0;
3591 DependentDecltypeType *Canon
3592 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3593 if (Canon) {
3594 // We already have a "canonical" version of an equivalent, dependent
3595 // decltype type. Use that as our canonical type.
Richard Smith0d729102012-08-13 20:08:14 +00003596 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003597 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003598 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003599 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003600 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003601 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3602 dt = Canon;
3603 }
3604 } else {
Douglas Gregorf8af9822012-02-12 18:42:33 +00003605 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3606 getCanonicalType(UnderlyingType));
Douglas Gregordd0257c2009-07-08 00:03:05 +00003607 }
Anders Carlsson395b4752009-06-24 19:06:50 +00003608 Types.push_back(dt);
3609 return QualType(dt, 0);
3610}
3611
Sean Huntca63c202011-05-24 22:41:36 +00003612/// getUnaryTransformationType - We don't unique these, since the memory
3613/// savings are minimal and these are rare.
3614QualType ASTContext::getUnaryTransformType(QualType BaseType,
3615 QualType UnderlyingType,
3616 UnaryTransformType::UTTKind Kind)
3617 const {
3618 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00003619 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3620 Kind,
3621 UnderlyingType->isDependentType() ?
Peter Collingbourne12fc4b02012-03-05 16:02:06 +00003622 QualType() : getCanonicalType(UnderlyingType));
Sean Huntca63c202011-05-24 22:41:36 +00003623 Types.push_back(Ty);
3624 return QualType(Ty, 0);
3625}
3626
Richard Smith60e141e2013-05-04 07:00:32 +00003627/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3628/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3629/// canonical deduced-but-dependent 'auto' type.
3630QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Richard Smithdc7a4f52013-04-30 13:56:41 +00003631 bool IsDependent) const {
Richard Smith60e141e2013-05-04 07:00:32 +00003632 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
3633 return getAutoDeductType();
3634
3635 // Look in the folding set for an existing type.
Richard Smith483b9f32011-02-21 20:05:19 +00003636 void *InsertPos = 0;
Richard Smith60e141e2013-05-04 07:00:32 +00003637 llvm::FoldingSetNodeID ID;
3638 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
3639 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3640 return QualType(AT, 0);
Richard Smith483b9f32011-02-21 20:05:19 +00003641
Richard Smitha2c36462013-04-26 16:15:35 +00003642 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithdc7a4f52013-04-30 13:56:41 +00003643 IsDecltypeAuto,
3644 IsDependent);
Richard Smith483b9f32011-02-21 20:05:19 +00003645 Types.push_back(AT);
3646 if (InsertPos)
3647 AutoTypes.InsertNode(AT, InsertPos);
3648 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00003649}
3650
Eli Friedmanb001de72011-10-06 23:00:33 +00003651/// getAtomicType - Return the uniqued reference to the atomic type for
3652/// the given value type.
3653QualType ASTContext::getAtomicType(QualType T) const {
3654 // Unique pointers, to guarantee there is only one pointer of a particular
3655 // structure.
3656 llvm::FoldingSetNodeID ID;
3657 AtomicType::Profile(ID, T);
3658
3659 void *InsertPos = 0;
3660 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3661 return QualType(AT, 0);
3662
3663 // If the atomic value type isn't canonical, this won't be a canonical type
3664 // either, so fill in the canonical type field.
3665 QualType Canonical;
3666 if (!T.isCanonical()) {
3667 Canonical = getAtomicType(getCanonicalType(T));
3668
3669 // Get the new insert position for the node we care about.
3670 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3671 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3672 }
3673 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3674 Types.push_back(New);
3675 AtomicTypes.InsertNode(New, InsertPos);
3676 return QualType(New, 0);
3677}
3678
Richard Smithad762fc2011-04-14 22:09:26 +00003679/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3680QualType ASTContext::getAutoDeductType() const {
3681 if (AutoDeductTy.isNull())
Richard Smith60e141e2013-05-04 07:00:32 +00003682 AutoDeductTy = QualType(
3683 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
3684 /*dependent*/false),
3685 0);
Richard Smithad762fc2011-04-14 22:09:26 +00003686 return AutoDeductTy;
3687}
3688
3689/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3690QualType ASTContext::getAutoRRefDeductType() const {
3691 if (AutoRRefDeductTy.isNull())
3692 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3693 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3694 return AutoRRefDeductTy;
3695}
3696
Reid Spencer5f016e22007-07-11 17:01:13 +00003697/// getTagDeclType - Return the unique reference to the type for the
3698/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003699QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003700 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003701 // FIXME: What is the design on getTagDeclType when it requires casting
3702 // away const? mutable?
3703 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003704}
3705
Mike Stump1eb44332009-09-09 15:08:12 +00003706/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3707/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3708/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003709CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003710 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003711}
3712
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003713/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3714CanQualType ASTContext::getIntMaxType() const {
3715 return getFromTargetType(Target->getIntMaxType());
3716}
3717
3718/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3719CanQualType ASTContext::getUIntMaxType() const {
3720 return getFromTargetType(Target->getUIntMaxType());
3721}
3722
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003723/// getSignedWCharType - Return the type of "signed wchar_t".
3724/// Used when in C++, as a GCC extension.
3725QualType ASTContext::getSignedWCharType() const {
3726 // FIXME: derive from "Target" ?
3727 return WCharTy;
3728}
3729
3730/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3731/// Used when in C++, as a GCC extension.
3732QualType ASTContext::getUnsignedWCharType() const {
3733 // FIXME: derive from "Target" ?
3734 return UnsignedIntTy;
3735}
3736
Enea Zaffanella9677eb82013-01-26 17:08:37 +00003737QualType ASTContext::getIntPtrType() const {
3738 return getFromTargetType(Target->getIntPtrType());
3739}
3740
3741QualType ASTContext::getUIntPtrType() const {
3742 return getCorrespondingUnsignedType(getIntPtrType());
3743}
3744
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003745/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003746/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3747QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003748 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003749}
3750
Eli Friedman6902e412012-11-27 02:58:24 +00003751/// \brief Return the unique type for "pid_t" defined in
3752/// <sys/types.h>. We need this to compute the correct type for vfork().
3753QualType ASTContext::getProcessIDType() const {
3754 return getFromTargetType(Target->getProcessIDType());
3755}
3756
Chris Lattnere6327742008-04-02 05:18:44 +00003757//===----------------------------------------------------------------------===//
3758// Type Operators
3759//===----------------------------------------------------------------------===//
3760
Jay Foad4ba2a172011-01-12 09:06:06 +00003761CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003762 // Push qualifiers into arrays, and then discard any remaining
3763 // qualifiers.
3764 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003765 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003766 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003767 QualType Result;
3768 if (isa<ArrayType>(Ty)) {
3769 Result = getArrayDecayedType(QualType(Ty,0));
3770 } else if (isa<FunctionType>(Ty)) {
3771 Result = getPointerType(QualType(Ty, 0));
3772 } else {
3773 Result = QualType(Ty, 0);
3774 }
3775
3776 return CanQualType::CreateUnsafe(Result);
3777}
3778
John McCall62c28c82011-01-18 07:41:22 +00003779QualType ASTContext::getUnqualifiedArrayType(QualType type,
3780 Qualifiers &quals) {
3781 SplitQualType splitType = type.getSplitUnqualifiedType();
3782
3783 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3784 // the unqualified desugared type and then drops it on the floor.
3785 // We then have to strip that sugar back off with
3786 // getUnqualifiedDesugaredType(), which is silly.
3787 const ArrayType *AT =
John McCall200fa532012-02-08 00:46:36 +00003788 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall62c28c82011-01-18 07:41:22 +00003789
3790 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003791 if (!AT) {
John McCall200fa532012-02-08 00:46:36 +00003792 quals = splitType.Quals;
3793 return QualType(splitType.Ty, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003794 }
3795
John McCall62c28c82011-01-18 07:41:22 +00003796 // Otherwise, recurse on the array's element type.
3797 QualType elementType = AT->getElementType();
3798 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3799
3800 // If that didn't change the element type, AT has no qualifiers, so we
3801 // can just use the results in splitType.
3802 if (elementType == unqualElementType) {
3803 assert(quals.empty()); // from the recursive call
John McCall200fa532012-02-08 00:46:36 +00003804 quals = splitType.Quals;
3805 return QualType(splitType.Ty, 0);
John McCall62c28c82011-01-18 07:41:22 +00003806 }
3807
3808 // Otherwise, add in the qualifiers from the outermost type, then
3809 // build the type back up.
John McCall200fa532012-02-08 00:46:36 +00003810 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003811
Douglas Gregor9dadd942010-05-17 18:45:21 +00003812 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003813 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003814 CAT->getSizeModifier(), 0);
3815 }
3816
Douglas Gregor9dadd942010-05-17 18:45:21 +00003817 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003818 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003819 }
3820
Douglas Gregor9dadd942010-05-17 18:45:21 +00003821 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003822 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003823 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003824 VAT->getSizeModifier(),
3825 VAT->getIndexTypeCVRQualifiers(),
3826 VAT->getBracketsRange());
3827 }
3828
3829 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003830 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003831 DSAT->getSizeModifier(), 0,
3832 SourceRange());
3833}
3834
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003835/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3836/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3837/// they point to and return true. If T1 and T2 aren't pointer types
3838/// or pointer-to-member types, or if they are not similar at this
3839/// level, returns false and leaves T1 and T2 unchanged. Top-level
3840/// qualifiers on T1 and T2 are ignored. This function will typically
3841/// be called in a loop that successively "unwraps" pointer and
3842/// pointer-to-member types to compare them at each level.
3843bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3844 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3845 *T2PtrType = T2->getAs<PointerType>();
3846 if (T1PtrType && T2PtrType) {
3847 T1 = T1PtrType->getPointeeType();
3848 T2 = T2PtrType->getPointeeType();
3849 return true;
3850 }
3851
3852 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3853 *T2MPType = T2->getAs<MemberPointerType>();
3854 if (T1MPType && T2MPType &&
3855 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3856 QualType(T2MPType->getClass(), 0))) {
3857 T1 = T1MPType->getPointeeType();
3858 T2 = T2MPType->getPointeeType();
3859 return true;
3860 }
3861
David Blaikie4e4d0842012-03-11 07:00:24 +00003862 if (getLangOpts().ObjC1) {
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003863 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3864 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3865 if (T1OPType && T2OPType) {
3866 T1 = T1OPType->getPointeeType();
3867 T2 = T2OPType->getPointeeType();
3868 return true;
3869 }
3870 }
3871
3872 // FIXME: Block pointers, too?
3873
3874 return false;
3875}
3876
Jay Foad4ba2a172011-01-12 09:06:06 +00003877DeclarationNameInfo
3878ASTContext::getNameForTemplate(TemplateName Name,
3879 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003880 switch (Name.getKind()) {
3881 case TemplateName::QualifiedTemplate:
3882 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003883 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003884 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3885 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003886
John McCall14606042011-06-30 08:33:18 +00003887 case TemplateName::OverloadedTemplate: {
3888 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3889 // DNInfo work in progress: CHECKME: what about DNLoc?
3890 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3891 }
3892
3893 case TemplateName::DependentTemplate: {
3894 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003895 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003896 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003897 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3898 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003899 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003900 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3901 // DNInfo work in progress: FIXME: source locations?
3902 DeclarationNameLoc DNLoc;
3903 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3904 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3905 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003906 }
3907 }
3908
John McCall14606042011-06-30 08:33:18 +00003909 case TemplateName::SubstTemplateTemplateParm: {
3910 SubstTemplateTemplateParmStorage *subst
3911 = Name.getAsSubstTemplateTemplateParm();
3912 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3913 NameLoc);
3914 }
3915
3916 case TemplateName::SubstTemplateTemplateParmPack: {
3917 SubstTemplateTemplateParmPackStorage *subst
3918 = Name.getAsSubstTemplateTemplateParmPack();
3919 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3920 NameLoc);
3921 }
3922 }
3923
3924 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003925}
3926
Jay Foad4ba2a172011-01-12 09:06:06 +00003927TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003928 switch (Name.getKind()) {
3929 case TemplateName::QualifiedTemplate:
3930 case TemplateName::Template: {
3931 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003932 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003933 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003934 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3935
3936 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003937 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003938 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003939
John McCall14606042011-06-30 08:33:18 +00003940 case TemplateName::OverloadedTemplate:
3941 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003942
John McCall14606042011-06-30 08:33:18 +00003943 case TemplateName::DependentTemplate: {
3944 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3945 assert(DTN && "Non-dependent template names must refer to template decls.");
3946 return DTN->CanonicalTemplateName;
3947 }
3948
3949 case TemplateName::SubstTemplateTemplateParm: {
3950 SubstTemplateTemplateParmStorage *subst
3951 = Name.getAsSubstTemplateTemplateParm();
3952 return getCanonicalTemplateName(subst->getReplacement());
3953 }
3954
3955 case TemplateName::SubstTemplateTemplateParmPack: {
3956 SubstTemplateTemplateParmPackStorage *subst
3957 = Name.getAsSubstTemplateTemplateParmPack();
3958 TemplateTemplateParmDecl *canonParameter
3959 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3960 TemplateArgument canonArgPack
3961 = getCanonicalTemplateArgument(subst->getArgumentPack());
3962 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3963 }
3964 }
3965
3966 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003967}
3968
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003969bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3970 X = getCanonicalTemplateName(X);
3971 Y = getCanonicalTemplateName(Y);
3972 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3973}
3974
Mike Stump1eb44332009-09-09 15:08:12 +00003975TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003976ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003977 switch (Arg.getKind()) {
3978 case TemplateArgument::Null:
3979 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003980
Douglas Gregor1275ae02009-07-28 23:00:59 +00003981 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003982 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003983
Douglas Gregord2008e22012-04-06 22:40:38 +00003984 case TemplateArgument::Declaration: {
Eli Friedmand7a6b162012-09-26 02:36:12 +00003985 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
3986 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregord2008e22012-04-06 22:40:38 +00003987 }
Mike Stump1eb44332009-09-09 15:08:12 +00003988
Eli Friedmand7a6b162012-09-26 02:36:12 +00003989 case TemplateArgument::NullPtr:
3990 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
3991 /*isNullPtr*/true);
3992
Douglas Gregor788cd062009-11-11 01:00:40 +00003993 case TemplateArgument::Template:
3994 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003995
3996 case TemplateArgument::TemplateExpansion:
3997 return TemplateArgument(getCanonicalTemplateName(
3998 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00003999 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00004000
Douglas Gregor1275ae02009-07-28 23:00:59 +00004001 case TemplateArgument::Integral:
Benjamin Kramer85524372012-06-07 15:09:51 +00004002 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00004003
Douglas Gregor1275ae02009-07-28 23:00:59 +00004004 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00004005 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00004006
Douglas Gregor1275ae02009-07-28 23:00:59 +00004007 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00004008 if (Arg.pack_size() == 0)
4009 return Arg;
4010
Douglas Gregor910f8002010-11-07 23:05:16 +00004011 TemplateArgument *CanonArgs
4012 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00004013 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004014 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00004015 AEnd = Arg.pack_end();
4016 A != AEnd; (void)++A, ++Idx)
4017 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00004018
Douglas Gregor910f8002010-11-07 23:05:16 +00004019 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00004020 }
4021 }
4022
4023 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00004024 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00004025}
4026
Douglas Gregord57959a2009-03-27 23:10:48 +00004027NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00004028ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004029 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00004030 return 0;
4031
4032 switch (NNS->getKind()) {
4033 case NestedNameSpecifier::Identifier:
4034 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00004035 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00004036 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4037 NNS->getAsIdentifier());
4038
4039 case NestedNameSpecifier::Namespace:
4040 // A namespace is canonical; build a nested-name-specifier with
4041 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00004042 return NestedNameSpecifier::Create(*this, 0,
4043 NNS->getAsNamespace()->getOriginalNamespace());
4044
4045 case NestedNameSpecifier::NamespaceAlias:
4046 // A namespace is canonical; build a nested-name-specifier with
4047 // this namespace and no prefix.
4048 return NestedNameSpecifier::Create(*this, 0,
4049 NNS->getAsNamespaceAlias()->getNamespace()
4050 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00004051
4052 case NestedNameSpecifier::TypeSpec:
4053 case NestedNameSpecifier::TypeSpecWithTemplate: {
4054 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00004055
4056 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4057 // break it apart into its prefix and identifier, then reconsititute those
4058 // as the canonical nested-name-specifier. This is required to canonicalize
4059 // a dependent nested-name-specifier involving typedefs of dependent-name
4060 // types, e.g.,
4061 // typedef typename T::type T1;
4062 // typedef typename T1::type T2;
Eli Friedman16412ef2012-03-03 04:09:56 +00004063 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4064 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor264bf662010-11-04 00:09:33 +00004065 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor264bf662010-11-04 00:09:33 +00004066
Eli Friedman16412ef2012-03-03 04:09:56 +00004067 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4068 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4069 // first place?
John McCall3b657512011-01-19 10:06:00 +00004070 return NestedNameSpecifier::Create(*this, 0, false,
4071 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00004072 }
4073
4074 case NestedNameSpecifier::Global:
4075 // The global specifier is canonical and unique.
4076 return NNS;
4077 }
4078
David Blaikie7530c032012-01-17 06:56:22 +00004079 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregord57959a2009-03-27 23:10:48 +00004080}
4081
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004082
Jay Foad4ba2a172011-01-12 09:06:06 +00004083const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004084 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004085 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004086 // Handle the common positive case fast.
4087 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4088 return AT;
4089 }
Mike Stump1eb44332009-09-09 15:08:12 +00004090
John McCall0953e762009-09-24 19:53:00 +00004091 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00004092 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004093 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004094
John McCall0953e762009-09-24 19:53:00 +00004095 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004096 // implements C99 6.7.3p8: "If the specification of an array type includes
4097 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00004098
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004099 // If we get here, we either have type qualifiers on the type, or we have
4100 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00004101 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00004102
John McCall3b657512011-01-19 10:06:00 +00004103 SplitQualType split = T.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004104 Qualifiers qs = split.Quals;
Mike Stump1eb44332009-09-09 15:08:12 +00004105
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004106 // If we have a simple case, just return now.
John McCall200fa532012-02-08 00:46:36 +00004107 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall3b657512011-01-19 10:06:00 +00004108 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004109 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00004110
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004111 // Otherwise, we have an array and we have qualifiers on it. Push the
4112 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00004113 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00004114
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004115 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4116 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4117 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004118 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004119 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4120 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4121 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004122 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00004123
Mike Stump1eb44332009-09-09 15:08:12 +00004124 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00004125 = dyn_cast<DependentSizedArrayType>(ATy))
4126 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00004127 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00004128 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00004129 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004130 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004131 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00004132
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004133 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004134 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00004135 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004136 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004137 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004138 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00004139}
4140
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004141QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004142 // C99 6.7.5.3p7:
4143 // A declaration of a parameter as "array of type" shall be
4144 // adjusted to "qualified pointer to type", where the type
4145 // qualifiers (if any) are those specified within the [ and ] of
4146 // the array type derivation.
4147 if (T->isArrayType())
4148 return getArrayDecayedType(T);
4149
4150 // C99 6.7.5.3p8:
4151 // A declaration of a parameter as "function returning type"
4152 // shall be adjusted to "pointer to function returning type", as
4153 // in 6.3.2.1.
4154 if (T->isFunctionType())
4155 return getPointerType(T);
4156
4157 return T;
4158}
4159
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004160QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004161 T = getVariableArrayDecayedType(T);
4162 T = getAdjustedParameterType(T);
4163 return T.getUnqualifiedType();
4164}
4165
Chris Lattnere6327742008-04-02 05:18:44 +00004166/// getArrayDecayedType - Return the properly qualified result of decaying the
4167/// specified array type to a pointer. This operation is non-trivial when
4168/// handling typedefs etc. The canonical type of "T" must be an array type,
4169/// this returns a pointer to a properly qualified element of the array.
4170///
4171/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00004172QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004173 // Get the element type with 'getAsArrayType' so that we don't lose any
4174 // typedefs in the element type of the array. This also handles propagation
4175 // of type qualifiers from the array type into the element type if present
4176 // (C99 6.7.3p8).
4177 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4178 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00004179
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004180 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00004181
4182 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00004183 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00004184}
4185
John McCall3b657512011-01-19 10:06:00 +00004186QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4187 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00004188}
4189
John McCall3b657512011-01-19 10:06:00 +00004190QualType ASTContext::getBaseElementType(QualType type) const {
4191 Qualifiers qs;
4192 while (true) {
4193 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004194 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall3b657512011-01-19 10:06:00 +00004195 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00004196
John McCall3b657512011-01-19 10:06:00 +00004197 type = array->getElementType();
John McCall200fa532012-02-08 00:46:36 +00004198 qs.addConsistentQualifiers(split.Quals);
John McCall3b657512011-01-19 10:06:00 +00004199 }
Mike Stump1eb44332009-09-09 15:08:12 +00004200
John McCall3b657512011-01-19 10:06:00 +00004201 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00004202}
4203
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004204/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00004205uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004206ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4207 uint64_t ElementCount = 1;
4208 do {
4209 ElementCount *= CA->getSize().getZExtValue();
Richard Smithd5e83942012-12-06 03:04:50 +00004210 CA = dyn_cast_or_null<ConstantArrayType>(
4211 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004212 } while (CA);
4213 return ElementCount;
4214}
4215
Reid Spencer5f016e22007-07-11 17:01:13 +00004216/// getFloatingRank - Return a relative rank for floating point types.
4217/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00004218static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00004219 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00004220 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00004221
John McCall183700f2009-09-21 23:43:11 +00004222 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4223 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004224 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00004225 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00004226 case BuiltinType::Float: return FloatRank;
4227 case BuiltinType::Double: return DoubleRank;
4228 case BuiltinType::LongDouble: return LongDoubleRank;
4229 }
4230}
4231
Mike Stump1eb44332009-09-09 15:08:12 +00004232/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4233/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00004234/// 'typeDomain' is a real floating point or complex type.
4235/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00004236QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4237 QualType Domain) const {
4238 FloatingRank EltRank = getFloatingRank(Size);
4239 if (Domain->isComplexType()) {
4240 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00004241 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Narofff1448a02007-08-27 01:27:54 +00004242 case FloatRank: return FloatComplexTy;
4243 case DoubleRank: return DoubleComplexTy;
4244 case LongDoubleRank: return LongDoubleComplexTy;
4245 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004246 }
Chris Lattner1361b112008-04-06 23:58:54 +00004247
4248 assert(Domain->isRealFloatingType() && "Unknown domain!");
4249 switch (EltRank) {
Joey Gouly19dbb202013-01-23 11:56:20 +00004250 case HalfRank: return HalfTy;
Chris Lattner1361b112008-04-06 23:58:54 +00004251 case FloatRank: return FloatTy;
4252 case DoubleRank: return DoubleTy;
4253 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00004254 }
David Blaikie561d3ab2012-01-17 02:30:50 +00004255 llvm_unreachable("getFloatingRank(): illegal value for rank");
Reid Spencer5f016e22007-07-11 17:01:13 +00004256}
4257
Chris Lattner7cfeb082008-04-06 23:55:33 +00004258/// getFloatingTypeOrder - Compare the rank of the two specified floating
4259/// point types, ignoring the domain of the type (i.e. 'double' ==
4260/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004261/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004262int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00004263 FloatingRank LHSR = getFloatingRank(LHS);
4264 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004265
Chris Lattnera75cea32008-04-06 23:38:49 +00004266 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004267 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00004268 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004269 return 1;
4270 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004271}
4272
Chris Lattnerf52ab252008-04-06 22:59:24 +00004273/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4274/// routine will assert if passed a built-in type that isn't an integer or enum,
4275/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00004276unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00004277 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00004278
Chris Lattnerf52ab252008-04-06 22:59:24 +00004279 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004280 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00004281 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004282 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004283 case BuiltinType::Char_S:
4284 case BuiltinType::Char_U:
4285 case BuiltinType::SChar:
4286 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004287 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004288 case BuiltinType::Short:
4289 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004290 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004291 case BuiltinType::Int:
4292 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004293 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004294 case BuiltinType::Long:
4295 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004296 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004297 case BuiltinType::LongLong:
4298 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004299 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00004300 case BuiltinType::Int128:
4301 case BuiltinType::UInt128:
4302 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00004303 }
4304}
4305
Eli Friedman04e83572009-08-20 04:21:42 +00004306/// \brief Whether this is a promotable bitfield reference according
4307/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4308///
4309/// \returns the type this bit-field will promote to, or NULL if no
4310/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00004311QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00004312 if (E->isTypeDependent() || E->isValueDependent())
4313 return QualType();
4314
John McCall993f43f2013-05-06 21:39:12 +00004315 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman04e83572009-08-20 04:21:42 +00004316 if (!Field)
4317 return QualType();
4318
4319 QualType FT = Field->getType();
4320
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004321 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00004322 uint64_t IntSize = getTypeSize(IntTy);
4323 // GCC extension compatibility: if the bit-field size is less than or equal
4324 // to the size of int, it gets promoted no matter what its type is.
4325 // For instance, unsigned long bf : 4 gets promoted to signed int.
4326 if (BitWidth < IntSize)
4327 return IntTy;
4328
4329 if (BitWidth == IntSize)
4330 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4331
4332 // Types bigger than int are not subject to promotions, and therefore act
4333 // like the base type.
4334 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4335 // is ridiculous.
4336 return QualType();
4337}
4338
Eli Friedmana95d7572009-08-19 07:44:53 +00004339/// getPromotedIntegerType - Returns the type that Promotable will
4340/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4341/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00004342QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00004343 assert(!Promotable.isNull());
4344 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00004345 if (const EnumType *ET = Promotable->getAs<EnumType>())
4346 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00004347
4348 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4349 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4350 // (3.9.1) can be converted to a prvalue of the first of the following
4351 // types that can represent all the values of its underlying type:
4352 // int, unsigned int, long int, unsigned long int, long long int, or
4353 // unsigned long long int [...]
4354 // FIXME: Is there some better way to compute this?
4355 if (BT->getKind() == BuiltinType::WChar_S ||
4356 BT->getKind() == BuiltinType::WChar_U ||
4357 BT->getKind() == BuiltinType::Char16 ||
4358 BT->getKind() == BuiltinType::Char32) {
4359 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4360 uint64_t FromSize = getTypeSize(BT);
4361 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4362 LongLongTy, UnsignedLongLongTy };
4363 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4364 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4365 if (FromSize < ToSize ||
4366 (FromSize == ToSize &&
4367 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4368 return PromoteTypes[Idx];
4369 }
4370 llvm_unreachable("char type should fit into long long");
4371 }
4372 }
4373
4374 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00004375 if (Promotable->isSignedIntegerType())
4376 return IntTy;
Eli Friedman5b64e772012-11-15 01:21:59 +00004377 uint64_t PromotableSize = getIntWidth(Promotable);
4378 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedmana95d7572009-08-19 07:44:53 +00004379 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4380 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4381}
4382
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004383/// \brief Recurses in pointer/array types until it finds an objc retainable
4384/// type and returns its ownership.
4385Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4386 while (!T.isNull()) {
4387 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4388 return T.getObjCLifetime();
4389 if (T->isArrayType())
4390 T = getBaseElementType(T);
4391 else if (const PointerType *PT = T->getAs<PointerType>())
4392 T = PT->getPointeeType();
4393 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00004394 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004395 else
4396 break;
4397 }
4398
4399 return Qualifiers::OCL_None;
4400}
4401
Mike Stump1eb44332009-09-09 15:08:12 +00004402/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00004403/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004404/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004405int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00004406 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4407 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00004408 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004409
Chris Lattnerf52ab252008-04-06 22:59:24 +00004410 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4411 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00004412
Chris Lattner7cfeb082008-04-06 23:55:33 +00004413 unsigned LHSRank = getIntegerRank(LHSC);
4414 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00004415
Chris Lattner7cfeb082008-04-06 23:55:33 +00004416 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4417 if (LHSRank == RHSRank) return 0;
4418 return LHSRank > RHSRank ? 1 : -1;
4419 }
Mike Stump1eb44332009-09-09 15:08:12 +00004420
Chris Lattner7cfeb082008-04-06 23:55:33 +00004421 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4422 if (LHSUnsigned) {
4423 // If the unsigned [LHS] type is larger, return it.
4424 if (LHSRank >= RHSRank)
4425 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004426
Chris Lattner7cfeb082008-04-06 23:55:33 +00004427 // If the signed type can represent all values of the unsigned type, it
4428 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004429 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004430 return -1;
4431 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00004432
Chris Lattner7cfeb082008-04-06 23:55:33 +00004433 // If the unsigned [RHS] type is larger, return it.
4434 if (RHSRank >= LHSRank)
4435 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00004436
Chris Lattner7cfeb082008-04-06 23:55:33 +00004437 // If the signed type can represent all values of the unsigned type, it
4438 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004439 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004440 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004441}
Anders Carlsson71993dd2007-08-17 05:31:46 +00004442
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004443static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004444CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4445 DeclContext *DC, IdentifierInfo *Id) {
4446 SourceLocation Loc;
David Blaikie4e4d0842012-03-11 07:00:24 +00004447 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004448 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004449 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004450 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004451}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004452
Mike Stump1eb44332009-09-09 15:08:12 +00004453// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00004454QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00004455 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004456 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004457 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004458 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00004459 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004460
Anders Carlssonf06273f2007-11-19 00:25:30 +00004461 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00004462
Anders Carlsson71993dd2007-08-17 05:31:46 +00004463 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00004464 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00004465 // int flags;
4466 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00004467 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00004468 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00004469 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00004470 FieldTypes[3] = LongTy;
4471
Anders Carlsson71993dd2007-08-17 05:31:46 +00004472 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00004473 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00004474 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004475 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00004476 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00004477 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00004478 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004479 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004480 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004481 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004482 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00004483 }
4484
Douglas Gregor838db382010-02-11 01:19:42 +00004485 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00004486 }
Mike Stump1eb44332009-09-09 15:08:12 +00004487
Anders Carlsson71993dd2007-08-17 05:31:46 +00004488 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00004489}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004490
Fariborz Jahanianf7992132013-01-04 18:45:40 +00004491QualType ASTContext::getObjCSuperType() const {
4492 if (ObjCSuperType.isNull()) {
4493 RecordDecl *ObjCSuperTypeDecl =
4494 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4495 TUDecl->addDecl(ObjCSuperTypeDecl);
4496 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4497 }
4498 return ObjCSuperType;
4499}
4500
Douglas Gregor319ac892009-04-23 22:29:11 +00004501void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004502 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00004503 assert(Rec && "Invalid CFConstantStringType");
4504 CFConstantStringTypeDecl = Rec->getDecl();
4505}
4506
Jay Foad4ba2a172011-01-12 09:06:06 +00004507QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00004508 if (BlockDescriptorType)
4509 return getTagDeclType(BlockDescriptorType);
4510
4511 RecordDecl *T;
4512 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004513 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004514 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00004515 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004516
4517 QualType FieldTypes[] = {
4518 UnsignedLongTy,
4519 UnsignedLongTy,
4520 };
4521
4522 const char *FieldNames[] = {
4523 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00004524 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00004525 };
4526
4527 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004528 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00004529 SourceLocation(),
4530 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004531 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00004532 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004533 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004534 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004535 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00004536 T->addDecl(Field);
4537 }
4538
Douglas Gregor838db382010-02-11 01:19:42 +00004539 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004540
4541 BlockDescriptorType = T;
4542
4543 return getTagDeclType(BlockDescriptorType);
4544}
4545
Jay Foad4ba2a172011-01-12 09:06:06 +00004546QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00004547 if (BlockDescriptorExtendedType)
4548 return getTagDeclType(BlockDescriptorExtendedType);
4549
4550 RecordDecl *T;
4551 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004552 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004553 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00004554 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004555
4556 QualType FieldTypes[] = {
4557 UnsignedLongTy,
4558 UnsignedLongTy,
4559 getPointerType(VoidPtrTy),
4560 getPointerType(VoidPtrTy)
4561 };
4562
4563 const char *FieldNames[] = {
4564 "reserved",
4565 "Size",
4566 "CopyFuncPtr",
4567 "DestroyFuncPtr"
4568 };
4569
4570 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004571 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00004572 SourceLocation(),
4573 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004574 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00004575 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004576 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004577 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004578 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00004579 T->addDecl(Field);
4580 }
4581
Douglas Gregor838db382010-02-11 01:19:42 +00004582 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004583
4584 BlockDescriptorExtendedType = T;
4585
4586 return getTagDeclType(BlockDescriptorExtendedType);
4587}
4588
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004589/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4590/// requires copy/dispose. Note that this must match the logic
4591/// in buildByrefHelpers.
4592bool ASTContext::BlockRequiresCopying(QualType Ty,
4593 const VarDecl *D) {
4594 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4595 const Expr *copyExpr = getBlockVarCopyInits(D);
4596 if (!copyExpr && record->hasTrivialDestructor()) return false;
4597
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004598 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00004599 }
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004600
4601 if (!Ty->isObjCRetainableType()) return false;
4602
4603 Qualifiers qs = Ty.getQualifiers();
4604
4605 // If we have lifetime, that dominates.
4606 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4607 assert(getLangOpts().ObjCAutoRefCount);
4608
4609 switch (lifetime) {
4610 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4611
4612 // These are just bits as far as the runtime is concerned.
4613 case Qualifiers::OCL_ExplicitNone:
4614 case Qualifiers::OCL_Autoreleasing:
4615 return false;
4616
4617 // Tell the runtime that this is ARC __weak, called by the
4618 // byref routines.
4619 case Qualifiers::OCL_Weak:
4620 // ARC __strong __block variables need to be retained.
4621 case Qualifiers::OCL_Strong:
4622 return true;
4623 }
4624 llvm_unreachable("fell out of lifetime switch!");
4625 }
4626 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4627 Ty->isObjCObjectPointerType());
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004628}
4629
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004630bool ASTContext::getByrefLifetime(QualType Ty,
4631 Qualifiers::ObjCLifetime &LifeTime,
4632 bool &HasByrefExtendedLayout) const {
4633
4634 if (!getLangOpts().ObjC1 ||
4635 getLangOpts().getGC() != LangOptions::NonGC)
4636 return false;
4637
4638 HasByrefExtendedLayout = false;
Fariborz Jahanian34db84f2012-12-11 19:58:01 +00004639 if (Ty->isRecordType()) {
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004640 HasByrefExtendedLayout = true;
4641 LifeTime = Qualifiers::OCL_None;
4642 }
4643 else if (getLangOpts().ObjCAutoRefCount)
4644 LifeTime = Ty.getObjCLifetime();
4645 // MRR.
4646 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4647 LifeTime = Qualifiers::OCL_ExplicitNone;
4648 else
4649 LifeTime = Qualifiers::OCL_None;
4650 return true;
4651}
4652
Douglas Gregore97179c2011-09-08 01:46:34 +00004653TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4654 if (!ObjCInstanceTypeDecl)
4655 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4656 getTranslationUnitDecl(),
4657 SourceLocation(),
4658 SourceLocation(),
4659 &Idents.get("instancetype"),
4660 getTrivialTypeSourceInfo(getObjCIdType()));
4661 return ObjCInstanceTypeDecl;
4662}
4663
Anders Carlssone8c49532007-10-29 06:33:42 +00004664// This returns true if a type has been typedefed to BOOL:
4665// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00004666static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00004667 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00004668 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4669 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00004670
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004671 return false;
4672}
4673
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004674/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004675/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00004676CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00004677 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4678 return CharUnits::Zero();
4679
Ken Dyck199c3d62010-01-11 17:06:35 +00004680 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004681
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004682 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004683 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004684 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004685 // Treat arrays as pointers, since that's how they're passed in.
4686 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004687 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004688 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004689}
4690
4691static inline
4692std::string charUnitsToString(const CharUnits &CU) {
4693 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004694}
4695
John McCall6b5a61b2011-02-07 10:33:21 +00004696/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004697/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004698std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4699 std::string S;
4700
David Chisnall5e530af2009-11-17 19:33:30 +00004701 const BlockDecl *Decl = Expr->getBlockDecl();
4702 QualType BlockTy =
4703 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4704 // Encode result type.
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004705 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004706 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4707 BlockTy->getAs<FunctionType>()->getResultType(),
4708 S, true /*Extended*/);
4709 else
4710 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4711 S);
David Chisnall5e530af2009-11-17 19:33:30 +00004712 // Compute size of all parameters.
4713 // Start with computing size of a pointer in number of bytes.
4714 // FIXME: There might(should) be a better way of doing this computation!
4715 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004716 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4717 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004718 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004719 E = Decl->param_end(); PI != E; ++PI) {
4720 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004721 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahanian075a5432012-06-30 00:48:59 +00004722 if (sz.isZero())
4723 continue;
Ken Dyck199c3d62010-01-11 17:06:35 +00004724 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004725 ParmOffset += sz;
4726 }
4727 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004728 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004729 // Block pointer and offset.
4730 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004731
4732 // Argument types.
4733 ParmOffset = PtrSize;
4734 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4735 Decl->param_end(); PI != E; ++PI) {
4736 ParmVarDecl *PVDecl = *PI;
4737 QualType PType = PVDecl->getOriginalType();
4738 if (const ArrayType *AT =
4739 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4740 // Use array's original type only if it has known number of
4741 // elements.
4742 if (!isa<ConstantArrayType>(AT))
4743 PType = PVDecl->getType();
4744 } else if (PType->isFunctionType())
4745 PType = PVDecl->getType();
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004746 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004747 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4748 S, true /*Extended*/);
4749 else
4750 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004751 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004752 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004753 }
John McCall6b5a61b2011-02-07 10:33:21 +00004754
4755 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004756}
4757
Douglas Gregorf968d832011-05-27 01:19:52 +00004758bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004759 std::string& S) {
4760 // Encode result type.
4761 getObjCEncodingForType(Decl->getResultType(), S);
4762 CharUnits ParmOffset;
4763 // Compute size of all parameters.
4764 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4765 E = Decl->param_end(); PI != E; ++PI) {
4766 QualType PType = (*PI)->getType();
4767 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004768 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004769 continue;
4770
David Chisnall5389f482010-12-30 14:05:53 +00004771 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004772 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004773 ParmOffset += sz;
4774 }
4775 S += charUnitsToString(ParmOffset);
4776 ParmOffset = CharUnits::Zero();
4777
4778 // Argument types.
4779 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4780 E = Decl->param_end(); PI != E; ++PI) {
4781 ParmVarDecl *PVDecl = *PI;
4782 QualType PType = PVDecl->getOriginalType();
4783 if (const ArrayType *AT =
4784 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4785 // Use array's original type only if it has known number of
4786 // elements.
4787 if (!isa<ConstantArrayType>(AT))
4788 PType = PVDecl->getType();
4789 } else if (PType->isFunctionType())
4790 PType = PVDecl->getType();
4791 getObjCEncodingForType(PType, S);
4792 S += charUnitsToString(ParmOffset);
4793 ParmOffset += getObjCEncodingTypeSize(PType);
4794 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004795
4796 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004797}
4798
Bob Wilsondc8dab62011-11-30 01:57:58 +00004799/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4800/// method parameter or return type. If Extended, include class names and
4801/// block object types.
4802void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4803 QualType T, std::string& S,
4804 bool Extended) const {
4805 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4806 getObjCEncodingForTypeQualifier(QT, S);
4807 // Encode parameter type.
4808 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4809 true /*OutermostType*/,
4810 false /*EncodingProperty*/,
4811 false /*StructField*/,
4812 Extended /*EncodeBlockParameters*/,
4813 Extended /*EncodeClassNames*/);
4814}
4815
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004816/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004817/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004818bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004819 std::string& S,
4820 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004821 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004822 // Encode return type.
4823 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4824 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004825 // Compute size of all parameters.
4826 // Start with computing size of a pointer in number of bytes.
4827 // FIXME: There might(should) be a better way of doing this computation!
4828 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004829 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004830 // The first two arguments (self and _cmd) are pointers; account for
4831 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004832 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004833 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004834 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004835 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004836 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004837 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004838 continue;
4839
Ken Dyck199c3d62010-01-11 17:06:35 +00004840 assert (sz.isPositive() &&
4841 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004842 ParmOffset += sz;
4843 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004844 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004845 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004846 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004847
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004848 // Argument types.
4849 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004850 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004851 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004852 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004853 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004854 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004855 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4856 // Use array's original type only if it has known number of
4857 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004858 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004859 PType = PVDecl->getType();
4860 } else if (PType->isFunctionType())
4861 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004862 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4863 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004864 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004865 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004866 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004867
4868 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004869}
4870
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004871/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004872/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004873/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4874/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004875/// Property attributes are stored as a comma-delimited C string. The simple
4876/// attributes readonly and bycopy are encoded as single characters. The
4877/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4878/// encoded as single characters, followed by an identifier. Property types
4879/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004880/// these attributes are defined by the following enumeration:
4881/// @code
4882/// enum PropertyAttributes {
4883/// kPropertyReadOnly = 'R', // property is read-only.
4884/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4885/// kPropertyByref = '&', // property is a reference to the value last assigned
4886/// kPropertyDynamic = 'D', // property is dynamic
4887/// kPropertyGetter = 'G', // followed by getter selector name
4888/// kPropertySetter = 'S', // followed by setter selector name
4889/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson0d4cb852012-03-22 17:48:02 +00004890/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004891/// kPropertyWeak = 'W' // 'weak' property
4892/// kPropertyStrong = 'P' // property GC'able
4893/// kPropertyNonAtomic = 'N' // property non-atomic
4894/// };
4895/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004896void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004897 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004898 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004899 // Collect information from the property implementation decl(s).
4900 bool Dynamic = false;
4901 ObjCPropertyImplDecl *SynthesizePID = 0;
4902
4903 // FIXME: Duplicated code due to poor abstraction.
4904 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004905 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004906 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4907 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004908 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004909 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004910 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004911 if (PID->getPropertyDecl() == PD) {
4912 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4913 Dynamic = true;
4914 } else {
4915 SynthesizePID = PID;
4916 }
4917 }
4918 }
4919 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004920 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004921 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004922 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004923 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004924 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004925 if (PID->getPropertyDecl() == PD) {
4926 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4927 Dynamic = true;
4928 } else {
4929 SynthesizePID = PID;
4930 }
4931 }
Mike Stump1eb44332009-09-09 15:08:12 +00004932 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004933 }
4934 }
4935
4936 // FIXME: This is not very efficient.
4937 S = "T";
4938
4939 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004940 // GCC has some special rules regarding encoding of properties which
4941 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004942 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004943 true /* outermost type */,
4944 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004945
4946 if (PD->isReadOnly()) {
4947 S += ",R";
Nico Weberd7ceab32013-05-08 23:47:40 +00004948 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
4949 S += ",C";
4950 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
4951 S += ",&";
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004952 } else {
4953 switch (PD->getSetterKind()) {
4954 case ObjCPropertyDecl::Assign: break;
4955 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004956 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004957 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004958 }
4959 }
4960
4961 // It really isn't clear at all what this means, since properties
4962 // are "dynamic by default".
4963 if (Dynamic)
4964 S += ",D";
4965
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004966 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4967 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004968
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004969 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4970 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004971 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004972 }
4973
4974 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4975 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004976 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004977 }
4978
4979 if (SynthesizePID) {
4980 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4981 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004982 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004983 }
4984
4985 // FIXME: OBJCGC: weak & strong
4986}
4987
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004988/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004989/// Another legacy compatibility encoding: 32-bit longs are encoded as
4990/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004991/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4992///
4993void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004994 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004995 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004996 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004997 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004998 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004999 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005000 PointeeTy = IntTy;
5001 }
5002 }
5003}
5004
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005005void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00005006 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005007 // We follow the behavior of gcc, expanding structures which are
5008 // directly pointed to, and expanding embedded structures. Note that
5009 // these rules are sufficient to prevent recursive encoding of the
5010 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00005011 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00005012 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005013}
5014
John McCall3624e9e2012-12-20 02:45:14 +00005015static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5016 BuiltinType::Kind kind) {
5017 switch (kind) {
David Chisnall64fd7e82010-06-04 01:10:52 +00005018 case BuiltinType::Void: return 'v';
5019 case BuiltinType::Bool: return 'B';
5020 case BuiltinType::Char_U:
5021 case BuiltinType::UChar: return 'C';
John McCall3624e9e2012-12-20 02:45:14 +00005022 case BuiltinType::Char16:
David Chisnall64fd7e82010-06-04 01:10:52 +00005023 case BuiltinType::UShort: return 'S';
John McCall3624e9e2012-12-20 02:45:14 +00005024 case BuiltinType::Char32:
David Chisnall64fd7e82010-06-04 01:10:52 +00005025 case BuiltinType::UInt: return 'I';
5026 case BuiltinType::ULong:
John McCall3624e9e2012-12-20 02:45:14 +00005027 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00005028 case BuiltinType::UInt128: return 'T';
5029 case BuiltinType::ULongLong: return 'Q';
5030 case BuiltinType::Char_S:
5031 case BuiltinType::SChar: return 'c';
5032 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00005033 case BuiltinType::WChar_S:
5034 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00005035 case BuiltinType::Int: return 'i';
5036 case BuiltinType::Long:
John McCall3624e9e2012-12-20 02:45:14 +00005037 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00005038 case BuiltinType::LongLong: return 'q';
5039 case BuiltinType::Int128: return 't';
5040 case BuiltinType::Float: return 'f';
5041 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00005042 case BuiltinType::LongDouble: return 'D';
John McCall3624e9e2012-12-20 02:45:14 +00005043 case BuiltinType::NullPtr: return '*'; // like char*
5044
5045 case BuiltinType::Half:
5046 // FIXME: potentially need @encodes for these!
5047 return ' ';
5048
5049 case BuiltinType::ObjCId:
5050 case BuiltinType::ObjCClass:
5051 case BuiltinType::ObjCSel:
5052 llvm_unreachable("@encoding ObjC primitive type");
5053
5054 // OpenCL and placeholder types don't need @encodings.
5055 case BuiltinType::OCLImage1d:
5056 case BuiltinType::OCLImage1dArray:
5057 case BuiltinType::OCLImage1dBuffer:
5058 case BuiltinType::OCLImage2d:
5059 case BuiltinType::OCLImage2dArray:
5060 case BuiltinType::OCLImage3d:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005061 case BuiltinType::OCLEvent:
Guy Benyei21f18c42013-02-07 10:55:47 +00005062 case BuiltinType::OCLSampler:
John McCall3624e9e2012-12-20 02:45:14 +00005063 case BuiltinType::Dependent:
5064#define BUILTIN_TYPE(KIND, ID)
5065#define PLACEHOLDER_TYPE(KIND, ID) \
5066 case BuiltinType::KIND:
5067#include "clang/AST/BuiltinTypes.def"
5068 llvm_unreachable("invalid builtin type for @encode");
David Chisnall64fd7e82010-06-04 01:10:52 +00005069 }
David Blaikie719e53f2013-01-09 17:48:41 +00005070 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnall64fd7e82010-06-04 01:10:52 +00005071}
5072
Douglas Gregor5471bc82011-09-08 17:18:35 +00005073static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5074 EnumDecl *Enum = ET->getDecl();
5075
5076 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5077 if (!Enum->isFixed())
5078 return 'i';
5079
5080 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall3624e9e2012-12-20 02:45:14 +00005081 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5082 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor5471bc82011-09-08 17:18:35 +00005083}
5084
Jay Foad4ba2a172011-01-12 09:06:06 +00005085static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00005086 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005087 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00005088 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00005089 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5090 // The GNU runtime requires more information; bitfields are encoded as b,
5091 // then the offset (in bits) of the first element, then the type of the
5092 // bitfield, then the size in bits. For example, in this structure:
5093 //
5094 // struct
5095 // {
5096 // int integer;
5097 // int flags:2;
5098 // };
5099 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5100 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5101 // information is not especially sensible, but we're stuck with it for
5102 // compatibility with GCC, although providing it breaks anything that
5103 // actually uses runtime introspection and wants to work on both runtimes...
John McCall260611a2012-06-20 06:18:46 +00005104 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnall64fd7e82010-06-04 01:10:52 +00005105 const RecordDecl *RD = FD->getParent();
5106 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00005107 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00005108 if (const EnumType *ET = T->getAs<EnumType>())
5109 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall3624e9e2012-12-20 02:45:14 +00005110 else {
5111 const BuiltinType *BT = T->castAs<BuiltinType>();
5112 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5113 }
David Chisnall64fd7e82010-06-04 01:10:52 +00005114 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005115 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00005116}
5117
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00005118// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005119void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5120 bool ExpandPointedToStructures,
5121 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00005122 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00005123 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005124 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00005125 bool StructField,
5126 bool EncodeBlockParameters,
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005127 bool EncodeClassNames,
5128 bool EncodePointerToObjCTypedef) const {
John McCall3624e9e2012-12-20 02:45:14 +00005129 CanQualType CT = getCanonicalType(T);
5130 switch (CT->getTypeClass()) {
5131 case Type::Builtin:
5132 case Type::Enum:
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005133 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00005134 return EncodeBitField(this, S, T, FD);
John McCall3624e9e2012-12-20 02:45:14 +00005135 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5136 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5137 else
5138 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005139 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005140
John McCall3624e9e2012-12-20 02:45:14 +00005141 case Type::Complex: {
5142 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005143 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00005144 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005145 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005146 return;
5147 }
John McCall3624e9e2012-12-20 02:45:14 +00005148
5149 case Type::Atomic: {
5150 const AtomicType *AT = T->castAs<AtomicType>();
5151 S += 'A';
5152 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5153 false, false);
5154 return;
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00005155 }
John McCall3624e9e2012-12-20 02:45:14 +00005156
5157 // encoding for pointer or reference types.
5158 case Type::Pointer:
5159 case Type::LValueReference:
5160 case Type::RValueReference: {
5161 QualType PointeeTy;
5162 if (isa<PointerType>(CT)) {
5163 const PointerType *PT = T->castAs<PointerType>();
5164 if (PT->isObjCSelType()) {
5165 S += ':';
5166 return;
5167 }
5168 PointeeTy = PT->getPointeeType();
5169 } else {
5170 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5171 }
5172
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005173 bool isReadOnly = false;
5174 // For historical/compatibility reasons, the read-only qualifier of the
5175 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5176 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00005177 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00005178 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005179 if (OutermostType && T.isConstQualified()) {
5180 isReadOnly = true;
5181 S += 'r';
5182 }
Mike Stump9fdbab32009-07-31 02:02:20 +00005183 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005184 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00005185 while (P->getAs<PointerType>())
5186 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005187 if (P.isConstQualified()) {
5188 isReadOnly = true;
5189 S += 'r';
5190 }
5191 }
5192 if (isReadOnly) {
5193 // Another legacy compatibility encoding. Some ObjC qualifier and type
5194 // combinations need to be rearranged.
5195 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00005196 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00005197 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005198 }
Mike Stump1eb44332009-09-09 15:08:12 +00005199
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005200 if (PointeeTy->isCharType()) {
5201 // char pointer types should be encoded as '*' unless it is a
5202 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00005203 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005204 S += '*';
5205 return;
5206 }
Ted Kremenek6217b802009-07-29 21:53:49 +00005207 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00005208 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5209 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5210 S += '#';
5211 return;
5212 }
5213 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5214 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5215 S += '@';
5216 return;
5217 }
5218 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005219 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005220 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005221 getLegacyIntegralTypeEncoding(PointeeTy);
5222
Mike Stump1eb44332009-09-09 15:08:12 +00005223 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005224 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005225 return;
5226 }
John McCall3624e9e2012-12-20 02:45:14 +00005227
5228 case Type::ConstantArray:
5229 case Type::IncompleteArray:
5230 case Type::VariableArray: {
5231 const ArrayType *AT = cast<ArrayType>(CT);
5232
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005233 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00005234 // Incomplete arrays are encoded as a pointer to the array element.
5235 S += '^';
5236
Mike Stump1eb44332009-09-09 15:08:12 +00005237 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005238 false, ExpandStructures, FD);
5239 } else {
5240 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00005241
Fariborz Jahanian48eff6c2013-06-04 16:04:37 +00005242 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5243 S += llvm::utostr(CAT->getSize().getZExtValue());
5244 else {
Anders Carlsson559a8332009-02-22 01:38:57 +00005245 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005246 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5247 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00005248 S += '0';
5249 }
Mike Stump1eb44332009-09-09 15:08:12 +00005250
5251 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005252 false, ExpandStructures, FD);
5253 S += ']';
5254 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005255 return;
5256 }
Mike Stump1eb44332009-09-09 15:08:12 +00005257
John McCall3624e9e2012-12-20 02:45:14 +00005258 case Type::FunctionNoProto:
5259 case Type::FunctionProto:
Anders Carlssonc0a87b72007-10-30 00:06:20 +00005260 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005261 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005262
John McCall3624e9e2012-12-20 02:45:14 +00005263 case Type::Record: {
5264 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005265 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005266 // Anonymous structures print as '?'
5267 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5268 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005269 if (ClassTemplateSpecializationDecl *Spec
5270 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5271 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer5eada842013-02-22 15:46:01 +00005272 llvm::raw_string_ostream OS(S);
5273 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor910f8002010-11-07 23:05:16 +00005274 TemplateArgs.data(),
5275 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00005276 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005277 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005278 } else {
5279 S += '?';
5280 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00005281 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005282 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005283 if (!RDecl->isUnion()) {
5284 getObjCEncodingForStructureImpl(RDecl, S, FD);
5285 } else {
5286 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5287 FieldEnd = RDecl->field_end();
5288 Field != FieldEnd; ++Field) {
5289 if (FD) {
5290 S += '"';
5291 S += Field->getNameAsString();
5292 S += '"';
5293 }
Mike Stump1eb44332009-09-09 15:08:12 +00005294
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005295 // Special case bit-fields.
5296 if (Field->isBitField()) {
5297 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie581deb32012-06-06 20:45:41 +00005298 *Field);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005299 } else {
5300 QualType qt = Field->getType();
5301 getLegacyIntegralTypeEncoding(qt);
5302 getObjCEncodingForTypeImpl(qt, S, false, true,
5303 FD, /*OutermostType*/false,
5304 /*EncodingProperty*/false,
5305 /*StructField*/true);
5306 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005307 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005308 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00005309 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005310 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005311 return;
5312 }
Mike Stump1eb44332009-09-09 15:08:12 +00005313
John McCall3624e9e2012-12-20 02:45:14 +00005314 case Type::BlockPointer: {
5315 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff21a98b12009-02-02 18:24:29 +00005316 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00005317 if (EncodeBlockParameters) {
John McCall3624e9e2012-12-20 02:45:14 +00005318 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilsondc8dab62011-11-30 01:57:58 +00005319
5320 S += '<';
5321 // Block return type
5322 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5323 ExpandPointedToStructures, ExpandStructures,
5324 FD,
5325 false /* OutermostType */,
5326 EncodingProperty,
5327 false /* StructField */,
5328 EncodeBlockParameters,
5329 EncodeClassNames);
5330 // Block self
5331 S += "@?";
5332 // Block parameters
5333 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5334 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5335 E = FPT->arg_type_end(); I && (I != E); ++I) {
5336 getObjCEncodingForTypeImpl(*I, S,
5337 ExpandPointedToStructures,
5338 ExpandStructures,
5339 FD,
5340 false /* OutermostType */,
5341 EncodingProperty,
5342 false /* StructField */,
5343 EncodeBlockParameters,
5344 EncodeClassNames);
5345 }
5346 }
5347 S += '>';
5348 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005349 return;
5350 }
Mike Stump1eb44332009-09-09 15:08:12 +00005351
John McCall3624e9e2012-12-20 02:45:14 +00005352 case Type::ObjCObject:
5353 case Type::ObjCInterface: {
5354 // Ignore protocol qualifiers when mangling at this level.
5355 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCallc12c5bb2010-05-15 11:32:37 +00005356
John McCall3624e9e2012-12-20 02:45:14 +00005357 // The assumption seems to be that this assert will succeed
5358 // because nested levels will have filtered out 'id' and 'Class'.
5359 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005360 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00005361 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005362 S += '{';
5363 const IdentifierInfo *II = OI->getIdentifier();
5364 S += II->getName();
5365 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00005366 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005367 DeepCollectObjCIvars(OI, true, Ivars);
5368 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00005369 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005370 if (Field->isBitField())
5371 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005372 else
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005373 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5374 false, false, false, false, false,
5375 EncodePointerToObjCTypedef);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005376 }
5377 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005378 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005379 }
Mike Stump1eb44332009-09-09 15:08:12 +00005380
John McCall3624e9e2012-12-20 02:45:14 +00005381 case Type::ObjCObjectPointer: {
5382 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00005383 if (OPT->isObjCIdType()) {
5384 S += '@';
5385 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005386 }
Mike Stump1eb44332009-09-09 15:08:12 +00005387
Steve Naroff27d20a22009-10-28 22:03:49 +00005388 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5389 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5390 // Since this is a binary compatibility issue, need to consult with runtime
5391 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00005392 S += '#';
5393 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005394 }
Mike Stump1eb44332009-09-09 15:08:12 +00005395
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005396 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005397 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00005398 ExpandPointedToStructures,
5399 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00005400 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00005401 // Note that we do extended encoding of protocol qualifer list
5402 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00005403 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005404 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5405 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00005406 S += '<';
5407 S += (*I)->getNameAsString();
5408 S += '>';
5409 }
5410 S += '"';
5411 }
5412 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005413 }
Mike Stump1eb44332009-09-09 15:08:12 +00005414
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005415 QualType PointeeTy = OPT->getPointeeType();
5416 if (!EncodingProperty &&
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005417 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5418 !EncodePointerToObjCTypedef) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005419 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00005420 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005421 // {...};
5422 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00005423 getObjCEncodingForTypeImpl(PointeeTy, S,
5424 false, ExpandPointedToStructures,
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005425 NULL,
5426 false, false, false, false, false,
5427 /*EncodePointerToObjCTypedef*/true);
Steve Naroff14108da2009-07-10 23:34:53 +00005428 return;
5429 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005430
5431 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00005432 if (OPT->getInterfaceDecl() &&
5433 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005434 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00005435 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005436 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5437 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005438 S += '<';
5439 S += (*I)->getNameAsString();
5440 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00005441 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005442 S += '"';
5443 }
5444 return;
5445 }
Mike Stump1eb44332009-09-09 15:08:12 +00005446
John McCall532ec7b2010-05-17 23:56:34 +00005447 // gcc just blithely ignores member pointers.
John McCall3624e9e2012-12-20 02:45:14 +00005448 // FIXME: we shoul do better than that. 'M' is available.
5449 case Type::MemberPointer:
John McCall532ec7b2010-05-17 23:56:34 +00005450 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005451
John McCall3624e9e2012-12-20 02:45:14 +00005452 case Type::Vector:
5453 case Type::ExtVector:
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005454 // This matches gcc's encoding, even though technically it is
5455 // insufficient.
5456 // FIXME. We should do a better job than gcc.
5457 return;
John McCall3624e9e2012-12-20 02:45:14 +00005458
Richard Smithdc7a4f52013-04-30 13:56:41 +00005459 case Type::Auto:
5460 // We could see an undeduced auto type here during error recovery.
5461 // Just ignore it.
5462 return;
5463
John McCall3624e9e2012-12-20 02:45:14 +00005464#define ABSTRACT_TYPE(KIND, BASE)
5465#define TYPE(KIND, BASE)
5466#define DEPENDENT_TYPE(KIND, BASE) \
5467 case Type::KIND:
5468#define NON_CANONICAL_TYPE(KIND, BASE) \
5469 case Type::KIND:
5470#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5471 case Type::KIND:
5472#include "clang/AST/TypeNodes.def"
5473 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005474 }
John McCall3624e9e2012-12-20 02:45:14 +00005475 llvm_unreachable("bad type kind!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005476}
5477
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005478void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5479 std::string &S,
5480 const FieldDecl *FD,
5481 bool includeVBases) const {
5482 assert(RDecl && "Expected non-null RecordDecl");
5483 assert(!RDecl->isUnion() && "Should not be called for unions");
5484 if (!RDecl->getDefinition())
5485 return;
5486
5487 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5488 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5489 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5490
5491 if (CXXRec) {
5492 for (CXXRecordDecl::base_class_iterator
5493 BI = CXXRec->bases_begin(),
5494 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5495 if (!BI->isVirtual()) {
5496 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005497 if (base->isEmpty())
5498 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005499 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005500 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5501 std::make_pair(offs, base));
5502 }
5503 }
5504 }
5505
5506 unsigned i = 0;
5507 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5508 FieldEnd = RDecl->field_end();
5509 Field != FieldEnd; ++Field, ++i) {
5510 uint64_t offs = layout.getFieldOffset(i);
5511 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie581deb32012-06-06 20:45:41 +00005512 std::make_pair(offs, *Field));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005513 }
5514
5515 if (CXXRec && includeVBases) {
5516 for (CXXRecordDecl::base_class_iterator
5517 BI = CXXRec->vbases_begin(),
5518 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5519 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005520 if (base->isEmpty())
5521 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005522 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00005523 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5524 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5525 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005526 }
5527 }
5528
5529 CharUnits size;
5530 if (CXXRec) {
5531 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5532 } else {
5533 size = layout.getSize();
5534 }
5535
5536 uint64_t CurOffs = 0;
5537 std::multimap<uint64_t, NamedDecl *>::iterator
5538 CurLayObj = FieldOrBaseOffsets.begin();
5539
Douglas Gregor58db7a52012-04-27 22:30:01 +00005540 if (CXXRec && CXXRec->isDynamicClass() &&
5541 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005542 if (FD) {
5543 S += "\"_vptr$";
5544 std::string recname = CXXRec->getNameAsString();
5545 if (recname.empty()) recname = "?";
5546 S += recname;
5547 S += '"';
5548 }
5549 S += "^^?";
5550 CurOffs += getTypeSize(VoidPtrTy);
5551 }
5552
5553 if (!RDecl->hasFlexibleArrayMember()) {
5554 // Mark the end of the structure.
5555 uint64_t offs = toBits(size);
5556 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5557 std::make_pair(offs, (NamedDecl*)0));
5558 }
5559
5560 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5561 assert(CurOffs <= CurLayObj->first);
5562
5563 if (CurOffs < CurLayObj->first) {
5564 uint64_t padding = CurLayObj->first - CurOffs;
5565 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5566 // packing/alignment of members is different that normal, in which case
5567 // the encoding will be out-of-sync with the real layout.
5568 // If the runtime switches to just consider the size of types without
5569 // taking into account alignment, we could make padding explicit in the
5570 // encoding (e.g. using arrays of chars). The encoding strings would be
5571 // longer then though.
5572 CurOffs += padding;
5573 }
5574
5575 NamedDecl *dcl = CurLayObj->second;
5576 if (dcl == 0)
5577 break; // reached end of structure.
5578
5579 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5580 // We expand the bases without their virtual bases since those are going
5581 // in the initial structure. Note that this differs from gcc which
5582 // expands virtual bases each time one is encountered in the hierarchy,
5583 // making the encoding type bigger than it really is.
5584 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005585 assert(!base->isEmpty());
5586 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005587 } else {
5588 FieldDecl *field = cast<FieldDecl>(dcl);
5589 if (FD) {
5590 S += '"';
5591 S += field->getNameAsString();
5592 S += '"';
5593 }
5594
5595 if (field->isBitField()) {
5596 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005597 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005598 } else {
5599 QualType qt = field->getType();
5600 getLegacyIntegralTypeEncoding(qt);
5601 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5602 /*OutermostType*/false,
5603 /*EncodingProperty*/false,
5604 /*StructField*/true);
5605 CurOffs += getTypeSize(field->getType());
5606 }
5607 }
5608 }
5609}
5610
Mike Stump1eb44332009-09-09 15:08:12 +00005611void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00005612 std::string& S) const {
5613 if (QT & Decl::OBJC_TQ_In)
5614 S += 'n';
5615 if (QT & Decl::OBJC_TQ_Inout)
5616 S += 'N';
5617 if (QT & Decl::OBJC_TQ_Out)
5618 S += 'o';
5619 if (QT & Decl::OBJC_TQ_Bycopy)
5620 S += 'O';
5621 if (QT & Decl::OBJC_TQ_Byref)
5622 S += 'R';
5623 if (QT & Decl::OBJC_TQ_Oneway)
5624 S += 'V';
5625}
5626
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00005627TypedefDecl *ASTContext::getObjCIdDecl() const {
5628 if (!ObjCIdDecl) {
5629 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5630 T = getObjCObjectPointerType(T);
5631 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5632 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5633 getTranslationUnitDecl(),
5634 SourceLocation(), SourceLocation(),
5635 &Idents.get("id"), IdInfo);
5636 }
5637
5638 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00005639}
5640
Douglas Gregor7a27ea52011-08-12 06:17:30 +00005641TypedefDecl *ASTContext::getObjCSelDecl() const {
5642 if (!ObjCSelDecl) {
5643 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5644 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5645 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5646 getTranslationUnitDecl(),
5647 SourceLocation(), SourceLocation(),
5648 &Idents.get("SEL"), SelInfo);
5649 }
5650 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00005651}
5652
Douglas Gregor79d67262011-08-12 05:59:41 +00005653TypedefDecl *ASTContext::getObjCClassDecl() const {
5654 if (!ObjCClassDecl) {
5655 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5656 T = getObjCObjectPointerType(T);
5657 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5658 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5659 getTranslationUnitDecl(),
5660 SourceLocation(), SourceLocation(),
5661 &Idents.get("Class"), ClassInfo);
5662 }
5663
5664 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00005665}
5666
Douglas Gregora6ea10e2012-01-17 18:09:05 +00005667ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5668 if (!ObjCProtocolClassDecl) {
5669 ObjCProtocolClassDecl
5670 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5671 SourceLocation(),
5672 &Idents.get("Protocol"),
5673 /*PrevDecl=*/0,
5674 SourceLocation(), true);
5675 }
5676
5677 return ObjCProtocolClassDecl;
5678}
5679
Meador Ingec5613b22012-06-16 03:34:49 +00005680//===----------------------------------------------------------------------===//
5681// __builtin_va_list Construction Functions
5682//===----------------------------------------------------------------------===//
5683
5684static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5685 // typedef char* __builtin_va_list;
5686 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5687 TypeSourceInfo *TInfo
5688 = Context->getTrivialTypeSourceInfo(CharPtrType);
5689
5690 TypedefDecl *VaListTypeDecl
5691 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5692 Context->getTranslationUnitDecl(),
5693 SourceLocation(), SourceLocation(),
5694 &Context->Idents.get("__builtin_va_list"),
5695 TInfo);
5696 return VaListTypeDecl;
5697}
5698
5699static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5700 // typedef void* __builtin_va_list;
5701 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5702 TypeSourceInfo *TInfo
5703 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5704
5705 TypedefDecl *VaListTypeDecl
5706 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5707 Context->getTranslationUnitDecl(),
5708 SourceLocation(), SourceLocation(),
5709 &Context->Idents.get("__builtin_va_list"),
5710 TInfo);
5711 return VaListTypeDecl;
5712}
5713
Tim Northoverc264e162013-01-31 12:13:10 +00005714static TypedefDecl *
5715CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5716 RecordDecl *VaListTagDecl;
5717 if (Context->getLangOpts().CPlusPlus) {
5718 // namespace std { struct __va_list {
5719 NamespaceDecl *NS;
5720 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5721 Context->getTranslationUnitDecl(),
5722 /*Inline*/false, SourceLocation(),
5723 SourceLocation(), &Context->Idents.get("std"),
5724 /*PrevDecl*/0);
5725
5726 VaListTagDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5727 Context->getTranslationUnitDecl(),
5728 SourceLocation(), SourceLocation(),
5729 &Context->Idents.get("__va_list"));
5730 VaListTagDecl->setDeclContext(NS);
5731 } else {
5732 // struct __va_list
5733 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5734 Context->getTranslationUnitDecl(),
5735 &Context->Idents.get("__va_list"));
5736 }
5737
5738 VaListTagDecl->startDefinition();
5739
5740 const size_t NumFields = 5;
5741 QualType FieldTypes[NumFields];
5742 const char *FieldNames[NumFields];
5743
5744 // void *__stack;
5745 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5746 FieldNames[0] = "__stack";
5747
5748 // void *__gr_top;
5749 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5750 FieldNames[1] = "__gr_top";
5751
5752 // void *__vr_top;
5753 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5754 FieldNames[2] = "__vr_top";
5755
5756 // int __gr_offs;
5757 FieldTypes[3] = Context->IntTy;
5758 FieldNames[3] = "__gr_offs";
5759
5760 // int __vr_offs;
5761 FieldTypes[4] = Context->IntTy;
5762 FieldNames[4] = "__vr_offs";
5763
5764 // Create fields
5765 for (unsigned i = 0; i < NumFields; ++i) {
5766 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5767 VaListTagDecl,
5768 SourceLocation(),
5769 SourceLocation(),
5770 &Context->Idents.get(FieldNames[i]),
5771 FieldTypes[i], /*TInfo=*/0,
5772 /*BitWidth=*/0,
5773 /*Mutable=*/false,
5774 ICIS_NoInit);
5775 Field->setAccess(AS_public);
5776 VaListTagDecl->addDecl(Field);
5777 }
5778 VaListTagDecl->completeDefinition();
5779 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5780 Context->VaListTagTy = VaListTagType;
5781
5782 // } __builtin_va_list;
5783 TypedefDecl *VaListTypedefDecl
5784 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5785 Context->getTranslationUnitDecl(),
5786 SourceLocation(), SourceLocation(),
5787 &Context->Idents.get("__builtin_va_list"),
5788 Context->getTrivialTypeSourceInfo(VaListTagType));
5789
5790 return VaListTypedefDecl;
5791}
5792
Meador Ingec5613b22012-06-16 03:34:49 +00005793static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5794 // typedef struct __va_list_tag {
5795 RecordDecl *VaListTagDecl;
5796
5797 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5798 Context->getTranslationUnitDecl(),
5799 &Context->Idents.get("__va_list_tag"));
5800 VaListTagDecl->startDefinition();
5801
5802 const size_t NumFields = 5;
5803 QualType FieldTypes[NumFields];
5804 const char *FieldNames[NumFields];
5805
5806 // unsigned char gpr;
5807 FieldTypes[0] = Context->UnsignedCharTy;
5808 FieldNames[0] = "gpr";
5809
5810 // unsigned char fpr;
5811 FieldTypes[1] = Context->UnsignedCharTy;
5812 FieldNames[1] = "fpr";
5813
5814 // unsigned short reserved;
5815 FieldTypes[2] = Context->UnsignedShortTy;
5816 FieldNames[2] = "reserved";
5817
5818 // void* overflow_arg_area;
5819 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5820 FieldNames[3] = "overflow_arg_area";
5821
5822 // void* reg_save_area;
5823 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5824 FieldNames[4] = "reg_save_area";
5825
5826 // Create fields
5827 for (unsigned i = 0; i < NumFields; ++i) {
5828 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5829 SourceLocation(),
5830 SourceLocation(),
5831 &Context->Idents.get(FieldNames[i]),
5832 FieldTypes[i], /*TInfo=*/0,
5833 /*BitWidth=*/0,
5834 /*Mutable=*/false,
5835 ICIS_NoInit);
5836 Field->setAccess(AS_public);
5837 VaListTagDecl->addDecl(Field);
5838 }
5839 VaListTagDecl->completeDefinition();
5840 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005841 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005842
5843 // } __va_list_tag;
5844 TypedefDecl *VaListTagTypedefDecl
5845 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5846 Context->getTranslationUnitDecl(),
5847 SourceLocation(), SourceLocation(),
5848 &Context->Idents.get("__va_list_tag"),
5849 Context->getTrivialTypeSourceInfo(VaListTagType));
5850 QualType VaListTagTypedefType =
5851 Context->getTypedefType(VaListTagTypedefDecl);
5852
5853 // typedef __va_list_tag __builtin_va_list[1];
5854 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5855 QualType VaListTagArrayType
5856 = Context->getConstantArrayType(VaListTagTypedefType,
5857 Size, ArrayType::Normal, 0);
5858 TypeSourceInfo *TInfo
5859 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5860 TypedefDecl *VaListTypedefDecl
5861 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5862 Context->getTranslationUnitDecl(),
5863 SourceLocation(), SourceLocation(),
5864 &Context->Idents.get("__builtin_va_list"),
5865 TInfo);
5866
5867 return VaListTypedefDecl;
5868}
5869
5870static TypedefDecl *
5871CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5872 // typedef struct __va_list_tag {
5873 RecordDecl *VaListTagDecl;
5874 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5875 Context->getTranslationUnitDecl(),
5876 &Context->Idents.get("__va_list_tag"));
5877 VaListTagDecl->startDefinition();
5878
5879 const size_t NumFields = 4;
5880 QualType FieldTypes[NumFields];
5881 const char *FieldNames[NumFields];
5882
5883 // unsigned gp_offset;
5884 FieldTypes[0] = Context->UnsignedIntTy;
5885 FieldNames[0] = "gp_offset";
5886
5887 // unsigned fp_offset;
5888 FieldTypes[1] = Context->UnsignedIntTy;
5889 FieldNames[1] = "fp_offset";
5890
5891 // void* overflow_arg_area;
5892 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5893 FieldNames[2] = "overflow_arg_area";
5894
5895 // void* reg_save_area;
5896 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5897 FieldNames[3] = "reg_save_area";
5898
5899 // Create fields
5900 for (unsigned i = 0; i < NumFields; ++i) {
5901 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5902 VaListTagDecl,
5903 SourceLocation(),
5904 SourceLocation(),
5905 &Context->Idents.get(FieldNames[i]),
5906 FieldTypes[i], /*TInfo=*/0,
5907 /*BitWidth=*/0,
5908 /*Mutable=*/false,
5909 ICIS_NoInit);
5910 Field->setAccess(AS_public);
5911 VaListTagDecl->addDecl(Field);
5912 }
5913 VaListTagDecl->completeDefinition();
5914 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005915 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005916
5917 // } __va_list_tag;
5918 TypedefDecl *VaListTagTypedefDecl
5919 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5920 Context->getTranslationUnitDecl(),
5921 SourceLocation(), SourceLocation(),
5922 &Context->Idents.get("__va_list_tag"),
5923 Context->getTrivialTypeSourceInfo(VaListTagType));
5924 QualType VaListTagTypedefType =
5925 Context->getTypedefType(VaListTagTypedefDecl);
5926
5927 // typedef __va_list_tag __builtin_va_list[1];
5928 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5929 QualType VaListTagArrayType
5930 = Context->getConstantArrayType(VaListTagTypedefType,
5931 Size, ArrayType::Normal,0);
5932 TypeSourceInfo *TInfo
5933 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5934 TypedefDecl *VaListTypedefDecl
5935 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5936 Context->getTranslationUnitDecl(),
5937 SourceLocation(), SourceLocation(),
5938 &Context->Idents.get("__builtin_va_list"),
5939 TInfo);
5940
5941 return VaListTypedefDecl;
5942}
5943
5944static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5945 // typedef int __builtin_va_list[4];
5946 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5947 QualType IntArrayType
5948 = Context->getConstantArrayType(Context->IntTy,
5949 Size, ArrayType::Normal, 0);
5950 TypedefDecl *VaListTypedefDecl
5951 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5952 Context->getTranslationUnitDecl(),
5953 SourceLocation(), SourceLocation(),
5954 &Context->Idents.get("__builtin_va_list"),
5955 Context->getTrivialTypeSourceInfo(IntArrayType));
5956
5957 return VaListTypedefDecl;
5958}
5959
Logan Chieneae5a8202012-10-10 06:56:20 +00005960static TypedefDecl *
5961CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5962 RecordDecl *VaListDecl;
5963 if (Context->getLangOpts().CPlusPlus) {
5964 // namespace std { struct __va_list {
5965 NamespaceDecl *NS;
5966 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5967 Context->getTranslationUnitDecl(),
5968 /*Inline*/false, SourceLocation(),
5969 SourceLocation(), &Context->Idents.get("std"),
5970 /*PrevDecl*/0);
5971
5972 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5973 Context->getTranslationUnitDecl(),
5974 SourceLocation(), SourceLocation(),
5975 &Context->Idents.get("__va_list"));
5976
5977 VaListDecl->setDeclContext(NS);
5978
5979 } else {
5980 // struct __va_list {
5981 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
5982 Context->getTranslationUnitDecl(),
5983 &Context->Idents.get("__va_list"));
5984 }
5985
5986 VaListDecl->startDefinition();
5987
5988 // void * __ap;
5989 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5990 VaListDecl,
5991 SourceLocation(),
5992 SourceLocation(),
5993 &Context->Idents.get("__ap"),
5994 Context->getPointerType(Context->VoidTy),
5995 /*TInfo=*/0,
5996 /*BitWidth=*/0,
5997 /*Mutable=*/false,
5998 ICIS_NoInit);
5999 Field->setAccess(AS_public);
6000 VaListDecl->addDecl(Field);
6001
6002 // };
6003 VaListDecl->completeDefinition();
6004
6005 // typedef struct __va_list __builtin_va_list;
6006 TypeSourceInfo *TInfo
6007 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
6008
6009 TypedefDecl *VaListTypeDecl
6010 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6011 Context->getTranslationUnitDecl(),
6012 SourceLocation(), SourceLocation(),
6013 &Context->Idents.get("__builtin_va_list"),
6014 TInfo);
6015
6016 return VaListTypeDecl;
6017}
6018
Ulrich Weigandb8409212013-05-06 16:26:41 +00006019static TypedefDecl *
6020CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6021 // typedef struct __va_list_tag {
6022 RecordDecl *VaListTagDecl;
6023 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
6024 Context->getTranslationUnitDecl(),
6025 &Context->Idents.get("__va_list_tag"));
6026 VaListTagDecl->startDefinition();
6027
6028 const size_t NumFields = 4;
6029 QualType FieldTypes[NumFields];
6030 const char *FieldNames[NumFields];
6031
6032 // long __gpr;
6033 FieldTypes[0] = Context->LongTy;
6034 FieldNames[0] = "__gpr";
6035
6036 // long __fpr;
6037 FieldTypes[1] = Context->LongTy;
6038 FieldNames[1] = "__fpr";
6039
6040 // void *__overflow_arg_area;
6041 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6042 FieldNames[2] = "__overflow_arg_area";
6043
6044 // void *__reg_save_area;
6045 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6046 FieldNames[3] = "__reg_save_area";
6047
6048 // Create fields
6049 for (unsigned i = 0; i < NumFields; ++i) {
6050 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6051 VaListTagDecl,
6052 SourceLocation(),
6053 SourceLocation(),
6054 &Context->Idents.get(FieldNames[i]),
6055 FieldTypes[i], /*TInfo=*/0,
6056 /*BitWidth=*/0,
6057 /*Mutable=*/false,
6058 ICIS_NoInit);
6059 Field->setAccess(AS_public);
6060 VaListTagDecl->addDecl(Field);
6061 }
6062 VaListTagDecl->completeDefinition();
6063 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6064 Context->VaListTagTy = VaListTagType;
6065
6066 // } __va_list_tag;
6067 TypedefDecl *VaListTagTypedefDecl
6068 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6069 Context->getTranslationUnitDecl(),
6070 SourceLocation(), SourceLocation(),
6071 &Context->Idents.get("__va_list_tag"),
6072 Context->getTrivialTypeSourceInfo(VaListTagType));
6073 QualType VaListTagTypedefType =
6074 Context->getTypedefType(VaListTagTypedefDecl);
6075
6076 // typedef __va_list_tag __builtin_va_list[1];
6077 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6078 QualType VaListTagArrayType
6079 = Context->getConstantArrayType(VaListTagTypedefType,
6080 Size, ArrayType::Normal,0);
6081 TypeSourceInfo *TInfo
6082 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
6083 TypedefDecl *VaListTypedefDecl
6084 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6085 Context->getTranslationUnitDecl(),
6086 SourceLocation(), SourceLocation(),
6087 &Context->Idents.get("__builtin_va_list"),
6088 TInfo);
6089
6090 return VaListTypedefDecl;
6091}
6092
Meador Ingec5613b22012-06-16 03:34:49 +00006093static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6094 TargetInfo::BuiltinVaListKind Kind) {
6095 switch (Kind) {
6096 case TargetInfo::CharPtrBuiltinVaList:
6097 return CreateCharPtrBuiltinVaListDecl(Context);
6098 case TargetInfo::VoidPtrBuiltinVaList:
6099 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northoverc264e162013-01-31 12:13:10 +00006100 case TargetInfo::AArch64ABIBuiltinVaList:
6101 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00006102 case TargetInfo::PowerABIBuiltinVaList:
6103 return CreatePowerABIBuiltinVaListDecl(Context);
6104 case TargetInfo::X86_64ABIBuiltinVaList:
6105 return CreateX86_64ABIBuiltinVaListDecl(Context);
6106 case TargetInfo::PNaClABIBuiltinVaList:
6107 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chieneae5a8202012-10-10 06:56:20 +00006108 case TargetInfo::AAPCSABIBuiltinVaList:
6109 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigandb8409212013-05-06 16:26:41 +00006110 case TargetInfo::SystemZBuiltinVaList:
6111 return CreateSystemZBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00006112 }
6113
6114 llvm_unreachable("Unhandled __builtin_va_list type kind");
6115}
6116
6117TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6118 if (!BuiltinVaListDecl)
6119 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6120
6121 return BuiltinVaListDecl;
6122}
6123
Meador Ingefb40e3f2012-07-01 15:57:25 +00006124QualType ASTContext::getVaListTagType() const {
6125 // Force the creation of VaListTagTy by building the __builtin_va_list
6126 // declaration.
6127 if (VaListTagTy.isNull())
6128 (void) getBuiltinVaListDecl();
6129
6130 return VaListTagTy;
6131}
6132
Ted Kremeneka526c5c2008-01-07 19:49:32 +00006133void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00006134 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00006135 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00006136
Ted Kremeneka526c5c2008-01-07 19:49:32 +00006137 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00006138}
6139
John McCall0bd6feb2009-12-02 08:04:21 +00006140/// \brief Retrieve the template name that corresponds to a non-empty
6141/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00006142TemplateName
6143ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6144 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00006145 unsigned size = End - Begin;
6146 assert(size > 1 && "set is not overloaded!");
6147
6148 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6149 size * sizeof(FunctionTemplateDecl*));
6150 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6151
6152 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00006153 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00006154 NamedDecl *D = *I;
6155 assert(isa<FunctionTemplateDecl>(D) ||
6156 (isa<UsingShadowDecl>(D) &&
6157 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6158 *Storage++ = D;
6159 }
6160
6161 return TemplateName(OT);
6162}
6163
Douglas Gregor7532dc62009-03-30 22:58:21 +00006164/// \brief Retrieve the template name that represents a qualified
6165/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00006166TemplateName
6167ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6168 bool TemplateKeyword,
6169 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00006170 assert(NNS && "Missing nested-name-specifier in qualified template name");
6171
Douglas Gregor789b1f62010-02-04 18:10:26 +00006172 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00006173 llvm::FoldingSetNodeID ID;
6174 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6175
6176 void *InsertPos = 0;
6177 QualifiedTemplateName *QTN =
6178 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6179 if (!QTN) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006180 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6181 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregor7532dc62009-03-30 22:58:21 +00006182 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6183 }
6184
6185 return TemplateName(QTN);
6186}
6187
6188/// \brief Retrieve the template name that represents a dependent
6189/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00006190TemplateName
6191ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6192 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00006193 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00006194 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00006195
6196 llvm::FoldingSetNodeID ID;
6197 DependentTemplateName::Profile(ID, NNS, Name);
6198
6199 void *InsertPos = 0;
6200 DependentTemplateName *QTN =
6201 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6202
6203 if (QTN)
6204 return TemplateName(QTN);
6205
6206 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6207 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006208 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6209 DependentTemplateName(NNS, Name);
Douglas Gregor7532dc62009-03-30 22:58:21 +00006210 } else {
6211 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smith2f47cab2012-08-16 01:19:31 +00006212 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6213 DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00006214 DependentTemplateName *CheckQTN =
6215 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6216 assert(!CheckQTN && "Dependent type name canonicalization broken");
6217 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00006218 }
6219
6220 DependentTemplateNames.InsertNode(QTN, InsertPos);
6221 return TemplateName(QTN);
6222}
6223
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006224/// \brief Retrieve the template name that represents a dependent
6225/// template name such as \c MetaFun::template operator+.
6226TemplateName
6227ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00006228 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006229 assert((!NNS || NNS->isDependent()) &&
6230 "Nested name specifier must be dependent");
6231
6232 llvm::FoldingSetNodeID ID;
6233 DependentTemplateName::Profile(ID, NNS, Operator);
6234
6235 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00006236 DependentTemplateName *QTN
6237 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006238
6239 if (QTN)
6240 return TemplateName(QTN);
6241
6242 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6243 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006244 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6245 DependentTemplateName(NNS, Operator);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006246 } else {
6247 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smith2f47cab2012-08-16 01:19:31 +00006248 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6249 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00006250
6251 DependentTemplateName *CheckQTN
6252 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6253 assert(!CheckQTN && "Dependent template name canonicalization broken");
6254 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006255 }
6256
6257 DependentTemplateNames.InsertNode(QTN, InsertPos);
6258 return TemplateName(QTN);
6259}
6260
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006261TemplateName
John McCall14606042011-06-30 08:33:18 +00006262ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6263 TemplateName replacement) const {
6264 llvm::FoldingSetNodeID ID;
6265 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6266
6267 void *insertPos = 0;
6268 SubstTemplateTemplateParmStorage *subst
6269 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6270
6271 if (!subst) {
6272 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6273 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6274 }
6275
6276 return TemplateName(subst);
6277}
6278
6279TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006280ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6281 const TemplateArgument &ArgPack) const {
6282 ASTContext &Self = const_cast<ASTContext &>(*this);
6283 llvm::FoldingSetNodeID ID;
6284 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6285
6286 void *InsertPos = 0;
6287 SubstTemplateTemplateParmPackStorage *Subst
6288 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6289
6290 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00006291 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006292 ArgPack.pack_size(),
6293 ArgPack.pack_begin());
6294 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6295 }
6296
6297 return TemplateName(Subst);
6298}
6299
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006300/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00006301/// TargetInfo, produce the corresponding type. The unsigned @p Type
6302/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00006303CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006304 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00006305 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006306 case TargetInfo::SignedShort: return ShortTy;
6307 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6308 case TargetInfo::SignedInt: return IntTy;
6309 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6310 case TargetInfo::SignedLong: return LongTy;
6311 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6312 case TargetInfo::SignedLongLong: return LongLongTy;
6313 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6314 }
6315
David Blaikieb219cfc2011-09-23 05:06:16 +00006316 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006317}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00006318
6319//===----------------------------------------------------------------------===//
6320// Type Predicates.
6321//===----------------------------------------------------------------------===//
6322
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006323/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6324/// garbage collection attribute.
6325///
John McCallae278a32011-01-12 00:34:59 +00006326Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006327 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00006328 return Qualifiers::GCNone;
6329
David Blaikie4e4d0842012-03-11 07:00:24 +00006330 assert(getLangOpts().ObjC1);
John McCallae278a32011-01-12 00:34:59 +00006331 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6332
6333 // Default behaviour under objective-C's gc is for ObjC pointers
6334 // (or pointers to them) be treated as though they were declared
6335 // as __strong.
6336 if (GCAttrs == Qualifiers::GCNone) {
6337 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6338 return Qualifiers::Strong;
6339 else if (Ty->isPointerType())
6340 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6341 } else {
6342 // It's not valid to set GC attributes on anything that isn't a
6343 // pointer.
6344#ifndef NDEBUG
6345 QualType CT = Ty->getCanonicalTypeInternal();
6346 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6347 CT = AT->getElementType();
6348 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6349#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006350 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00006351 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006352}
6353
Chris Lattner6ac46a42008-04-07 06:51:04 +00006354//===----------------------------------------------------------------------===//
6355// Type Compatibility Testing
6356//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00006357
Mike Stump1eb44332009-09-09 15:08:12 +00006358/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006359/// compatible.
6360static bool areCompatVectorTypes(const VectorType *LHS,
6361 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00006362 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00006363 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00006364 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00006365}
6366
Douglas Gregor255210e2010-08-06 10:14:59 +00006367bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6368 QualType SecondVec) {
6369 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6370 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6371
6372 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6373 return true;
6374
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006375 // Treat Neon vector types and most AltiVec vector types as if they are the
6376 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00006377 const VectorType *First = FirstVec->getAs<VectorType>();
6378 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006379 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00006380 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006381 First->getVectorKind() != VectorType::AltiVecPixel &&
6382 First->getVectorKind() != VectorType::AltiVecBool &&
6383 Second->getVectorKind() != VectorType::AltiVecPixel &&
6384 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00006385 return true;
6386
6387 return false;
6388}
6389
Steve Naroff4084c302009-07-23 01:01:38 +00006390//===----------------------------------------------------------------------===//
6391// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6392//===----------------------------------------------------------------------===//
6393
6394/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6395/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00006396bool
6397ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6398 ObjCProtocolDecl *rProto) const {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00006399 if (declaresSameEntity(lProto, rProto))
Steve Naroff4084c302009-07-23 01:01:38 +00006400 return true;
6401 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6402 E = rProto->protocol_end(); PI != E; ++PI)
6403 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6404 return true;
6405 return false;
6406}
6407
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00006408/// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
Steve Naroff4084c302009-07-23 01:01:38 +00006409/// return true if lhs's protocols conform to rhs's protocol; false
6410/// otherwise.
6411bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
6412 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
6413 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
6414 return false;
6415}
6416
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00006417/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6418/// Class<pr1, ...>.
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006419bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6420 QualType rhs) {
6421 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6422 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6423 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6424
6425 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6426 E = lhsQID->qual_end(); I != E; ++I) {
6427 bool match = false;
6428 ObjCProtocolDecl *lhsProto = *I;
6429 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6430 E = rhsOPT->qual_end(); J != E; ++J) {
6431 ObjCProtocolDecl *rhsProto = *J;
6432 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6433 match = true;
6434 break;
6435 }
6436 }
6437 if (!match)
6438 return false;
6439 }
6440 return true;
6441}
6442
Steve Naroff4084c302009-07-23 01:01:38 +00006443/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6444/// ObjCQualifiedIDType.
6445bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6446 bool compare) {
6447 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00006448 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006449 lhs->isObjCIdType() || lhs->isObjCClassType())
6450 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006451 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006452 rhs->isObjCIdType() || rhs->isObjCClassType())
6453 return true;
6454
6455 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00006456 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006457
Steve Naroff4084c302009-07-23 01:01:38 +00006458 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006459
Steve Naroff4084c302009-07-23 01:01:38 +00006460 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006461 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00006462 // make sure we check the class hierarchy.
6463 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6464 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6465 E = lhsQID->qual_end(); I != E; ++I) {
6466 // when comparing an id<P> on lhs with a static type on rhs,
6467 // see if static class implements all of id's protocols, directly or
6468 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006469 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00006470 return false;
6471 }
6472 }
6473 // If there are no qualifiers and no interface, we have an 'id'.
6474 return true;
6475 }
Mike Stump1eb44332009-09-09 15:08:12 +00006476 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006477 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6478 E = lhsQID->qual_end(); I != E; ++I) {
6479 ObjCProtocolDecl *lhsProto = *I;
6480 bool match = false;
6481
6482 // when comparing an id<P> on lhs with a static type on rhs,
6483 // see if static class implements all of id's protocols, directly or
6484 // through its super class and categories.
6485 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6486 E = rhsOPT->qual_end(); J != E; ++J) {
6487 ObjCProtocolDecl *rhsProto = *J;
6488 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6489 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6490 match = true;
6491 break;
6492 }
6493 }
Mike Stump1eb44332009-09-09 15:08:12 +00006494 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00006495 // make sure we check the class hierarchy.
6496 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6497 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6498 E = lhsQID->qual_end(); I != E; ++I) {
6499 // when comparing an id<P> on lhs with a static type on rhs,
6500 // see if static class implements all of id's protocols, directly or
6501 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006502 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00006503 match = true;
6504 break;
6505 }
6506 }
6507 }
6508 if (!match)
6509 return false;
6510 }
Mike Stump1eb44332009-09-09 15:08:12 +00006511
Steve Naroff4084c302009-07-23 01:01:38 +00006512 return true;
6513 }
Mike Stump1eb44332009-09-09 15:08:12 +00006514
Steve Naroff4084c302009-07-23 01:01:38 +00006515 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6516 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6517
Mike Stump1eb44332009-09-09 15:08:12 +00006518 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00006519 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006520 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006521 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6522 E = lhsOPT->qual_end(); I != E; ++I) {
6523 ObjCProtocolDecl *lhsProto = *I;
6524 bool match = false;
6525
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006526 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00006527 // see if static class implements all of id's protocols, directly or
6528 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006529 // First, lhs protocols in the qualifier list must be found, direct
6530 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00006531 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6532 E = rhsQID->qual_end(); J != E; ++J) {
6533 ObjCProtocolDecl *rhsProto = *J;
6534 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6535 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6536 match = true;
6537 break;
6538 }
6539 }
6540 if (!match)
6541 return false;
6542 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006543
6544 // Static class's protocols, or its super class or category protocols
6545 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6546 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6547 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6548 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6549 // This is rather dubious but matches gcc's behavior. If lhs has
6550 // no type qualifier and its class has no static protocol(s)
6551 // assume that it is mismatch.
6552 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6553 return false;
6554 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6555 LHSInheritedProtocols.begin(),
6556 E = LHSInheritedProtocols.end(); I != E; ++I) {
6557 bool match = false;
6558 ObjCProtocolDecl *lhsProto = (*I);
6559 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6560 E = rhsQID->qual_end(); J != E; ++J) {
6561 ObjCProtocolDecl *rhsProto = *J;
6562 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6563 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6564 match = true;
6565 break;
6566 }
6567 }
6568 if (!match)
6569 return false;
6570 }
6571 }
Steve Naroff4084c302009-07-23 01:01:38 +00006572 return true;
6573 }
6574 return false;
6575}
6576
Eli Friedman3d815e72008-08-22 00:56:42 +00006577/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006578/// compatible for assignment from RHS to LHS. This handles validation of any
6579/// protocol qualifiers on the LHS or RHS.
6580///
Steve Naroff14108da2009-07-10 23:34:53 +00006581bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6582 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00006583 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6584 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6585
Steve Naroffde2e22d2009-07-15 18:40:39 +00006586 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00006587 if (LHS->isObjCUnqualifiedIdOrClass() ||
6588 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00006589 return true;
6590
John McCallc12c5bb2010-05-15 11:32:37 +00006591 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00006592 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6593 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00006594 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006595
6596 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6597 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6598 QualType(RHSOPT,0));
6599
John McCallc12c5bb2010-05-15 11:32:37 +00006600 // If we have 2 user-defined types, fall into that path.
6601 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00006602 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006603
Steve Naroff4084c302009-07-23 01:01:38 +00006604 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006605}
6606
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006607/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00006608/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006609/// arguments in block literals. When passed as arguments, passing 'A*' where
6610/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6611/// not OK. For the return type, the opposite is not OK.
6612bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6613 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006614 const ObjCObjectPointerType *RHSOPT,
6615 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006616 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006617 return true;
6618
6619 if (LHSOPT->isObjCBuiltinType()) {
6620 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6621 }
6622
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006623 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006624 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6625 QualType(RHSOPT,0),
6626 false);
6627
6628 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6629 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6630 if (LHS && RHS) { // We have 2 user-defined types.
6631 if (LHS != RHS) {
6632 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006633 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006634 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006635 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006636 }
6637 else
6638 return true;
6639 }
6640 return false;
6641}
6642
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006643/// getIntersectionOfProtocols - This routine finds the intersection of set
6644/// of protocols inherited from two distinct objective-c pointer objects.
6645/// It is used to build composite qualifier list of the composite type of
6646/// the conditional expression involving two objective-c pointer objects.
6647static
6648void getIntersectionOfProtocols(ASTContext &Context,
6649 const ObjCObjectPointerType *LHSOPT,
6650 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006651 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006652
John McCallc12c5bb2010-05-15 11:32:37 +00006653 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6654 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6655 assert(LHS->getInterface() && "LHS must have an interface base");
6656 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006657
6658 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6659 unsigned LHSNumProtocols = LHS->getNumProtocols();
6660 if (LHSNumProtocols > 0)
6661 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6662 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006663 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006664 Context.CollectInheritedProtocols(LHS->getInterface(),
6665 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006666 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6667 LHSInheritedProtocols.end());
6668 }
6669
6670 unsigned RHSNumProtocols = RHS->getNumProtocols();
6671 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00006672 ObjCProtocolDecl **RHSProtocols =
6673 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006674 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6675 if (InheritedProtocolSet.count(RHSProtocols[i]))
6676 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00006677 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006678 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006679 Context.CollectInheritedProtocols(RHS->getInterface(),
6680 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006681 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6682 RHSInheritedProtocols.begin(),
6683 E = RHSInheritedProtocols.end(); I != E; ++I)
6684 if (InheritedProtocolSet.count((*I)))
6685 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006686 }
6687}
6688
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006689/// areCommonBaseCompatible - Returns common base class of the two classes if
6690/// one found. Note that this is O'2 algorithm. But it will be called as the
6691/// last type comparison in a ?-exp of ObjC pointer types before a
6692/// warning is issued. So, its invokation is extremely rare.
6693QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00006694 const ObjCObjectPointerType *Lptr,
6695 const ObjCObjectPointerType *Rptr) {
6696 const ObjCObjectType *LHS = Lptr->getObjectType();
6697 const ObjCObjectType *RHS = Rptr->getObjectType();
6698 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6699 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor60ef3082011-12-15 00:29:59 +00006700 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006701 return QualType();
6702
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006703 do {
John McCallc12c5bb2010-05-15 11:32:37 +00006704 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006705 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006706 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006707 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6708
6709 QualType Result = QualType(LHS, 0);
6710 if (!Protocols.empty())
6711 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6712 Result = getObjCObjectPointerType(Result);
6713 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006714 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006715 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006716
6717 return QualType();
6718}
6719
John McCallc12c5bb2010-05-15 11:32:37 +00006720bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6721 const ObjCObjectType *RHS) {
6722 assert(LHS->getInterface() && "LHS is not an interface type");
6723 assert(RHS->getInterface() && "RHS is not an interface type");
6724
Chris Lattner6ac46a42008-04-07 06:51:04 +00006725 // Verify that the base decls are compatible: the RHS must be a subclass of
6726 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00006727 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00006728 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006729
Chris Lattner6ac46a42008-04-07 06:51:04 +00006730 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6731 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00006732 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00006733 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006734
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006735 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6736 // more detailed analysis is required.
6737 if (RHS->getNumProtocols() == 0) {
6738 // OK, if LHS is a superclass of RHS *and*
6739 // this superclass is assignment compatible with LHS.
6740 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006741 bool IsSuperClass =
6742 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6743 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006744 // OK if conversion of LHS to SuperClass results in narrowing of types
6745 // ; i.e., SuperClass may implement at least one of the protocols
6746 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6747 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6748 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006749 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006750 // If super class has no protocols, it is not a match.
6751 if (SuperClassInheritedProtocols.empty())
6752 return false;
6753
6754 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6755 LHSPE = LHS->qual_end();
6756 LHSPI != LHSPE; LHSPI++) {
6757 bool SuperImplementsProtocol = false;
6758 ObjCProtocolDecl *LHSProto = (*LHSPI);
6759
6760 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6761 SuperClassInheritedProtocols.begin(),
6762 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6763 ObjCProtocolDecl *SuperClassProto = (*I);
6764 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6765 SuperImplementsProtocol = true;
6766 break;
6767 }
6768 }
6769 if (!SuperImplementsProtocol)
6770 return false;
6771 }
6772 return true;
6773 }
6774 return false;
6775 }
Mike Stump1eb44332009-09-09 15:08:12 +00006776
John McCallc12c5bb2010-05-15 11:32:37 +00006777 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6778 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006779 LHSPI != LHSPE; LHSPI++) {
6780 bool RHSImplementsProtocol = false;
6781
6782 // If the RHS doesn't implement the protocol on the left, the types
6783 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00006784 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6785 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00006786 RHSPI != RHSPE; RHSPI++) {
6787 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006788 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00006789 break;
6790 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006791 }
6792 // FIXME: For better diagnostics, consider passing back the protocol name.
6793 if (!RHSImplementsProtocol)
6794 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006795 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006796 // The RHS implements all protocols listed on the LHS.
6797 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006798}
6799
Steve Naroff389bf462009-02-12 17:52:19 +00006800bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6801 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00006802 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6803 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006804
Steve Naroff14108da2009-07-10 23:34:53 +00006805 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00006806 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006807
6808 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6809 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00006810}
6811
Douglas Gregor569c3162010-08-07 11:51:51 +00006812bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6813 return canAssignObjCInterfaces(
6814 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6815 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6816}
6817
Mike Stump1eb44332009-09-09 15:08:12 +00006818/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00006819/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00006820/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00006821/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00006822bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6823 bool CompareUnqualified) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006824 if (getLangOpts().CPlusPlus)
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006825 return hasSameType(LHS, RHS);
6826
Douglas Gregor447234d2010-07-29 15:18:02 +00006827 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00006828}
6829
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006830bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00006831 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006832}
6833
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006834bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6835 return !mergeTypes(LHS, RHS, true).isNull();
6836}
6837
Peter Collingbourne48466752010-10-24 18:30:18 +00006838/// mergeTransparentUnionType - if T is a transparent union type and a member
6839/// of T is compatible with SubType, return the merged type, else return
6840/// QualType()
6841QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6842 bool OfBlockPointer,
6843 bool Unqualified) {
6844 if (const RecordType *UT = T->getAsUnionType()) {
6845 RecordDecl *UD = UT->getDecl();
6846 if (UD->hasAttr<TransparentUnionAttr>()) {
6847 for (RecordDecl::field_iterator it = UD->field_begin(),
6848 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00006849 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006850 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6851 if (!MT.isNull())
6852 return MT;
6853 }
6854 }
6855 }
6856
6857 return QualType();
6858}
6859
6860/// mergeFunctionArgumentTypes - merge two types which appear as function
6861/// argument types
6862QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6863 bool OfBlockPointer,
6864 bool Unqualified) {
6865 // GNU extension: two types are compatible if they appear as a function
6866 // argument, one of the types is a transparent union type and the other
6867 // type is compatible with a union member
6868 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6869 Unqualified);
6870 if (!lmerge.isNull())
6871 return lmerge;
6872
6873 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6874 Unqualified);
6875 if (!rmerge.isNull())
6876 return rmerge;
6877
6878 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6879}
6880
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006881QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00006882 bool OfBlockPointer,
6883 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00006884 const FunctionType *lbase = lhs->getAs<FunctionType>();
6885 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00006886 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6887 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00006888 bool allLTypes = true;
6889 bool allRTypes = true;
6890
6891 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006892 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006893 if (OfBlockPointer) {
6894 QualType RHS = rbase->getResultType();
6895 QualType LHS = lbase->getResultType();
6896 bool UnqualifiedResult = Unqualified;
6897 if (!UnqualifiedResult)
6898 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006899 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006900 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006901 else
John McCall8cc246c2010-12-15 01:06:38 +00006902 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6903 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006904 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006905
6906 if (Unqualified)
6907 retType = retType.getUnqualifiedType();
6908
6909 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6910 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6911 if (Unqualified) {
6912 LRetType = LRetType.getUnqualifiedType();
6913 RRetType = RRetType.getUnqualifiedType();
6914 }
6915
6916 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006917 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00006918 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006919 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00006920
Daniel Dunbar6a15c852010-04-28 16:20:58 +00006921 // FIXME: double check this
6922 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6923 // rbase->getRegParmAttr() != 0 &&
6924 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00006925 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6926 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00006927
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006928 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00006929 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006930 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006931
John McCall8cc246c2010-12-15 01:06:38 +00006932 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00006933 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6934 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00006935 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6936 return QualType();
6937
John McCallf85e1932011-06-15 23:02:42 +00006938 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6939 return QualType();
6940
John McCall8cc246c2010-12-15 01:06:38 +00006941 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6942 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00006943
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00006944 if (lbaseInfo.getNoReturn() != NoReturn)
6945 allLTypes = false;
6946 if (rbaseInfo.getNoReturn() != NoReturn)
6947 allRTypes = false;
6948
John McCallf85e1932011-06-15 23:02:42 +00006949 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00006950
Eli Friedman3d815e72008-08-22 00:56:42 +00006951 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00006952 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6953 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006954 unsigned lproto_nargs = lproto->getNumArgs();
6955 unsigned rproto_nargs = rproto->getNumArgs();
6956
6957 // Compatible functions must have the same number of arguments
6958 if (lproto_nargs != rproto_nargs)
6959 return QualType();
6960
6961 // Variadic and non-variadic functions aren't compatible
6962 if (lproto->isVariadic() != rproto->isVariadic())
6963 return QualType();
6964
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00006965 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6966 return QualType();
6967
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006968 if (LangOpts.ObjCAutoRefCount &&
6969 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6970 return QualType();
6971
Eli Friedman3d815e72008-08-22 00:56:42 +00006972 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00006973 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00006974 for (unsigned i = 0; i < lproto_nargs; i++) {
6975 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6976 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006977 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6978 OfBlockPointer,
6979 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006980 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006981
6982 if (Unqualified)
6983 argtype = argtype.getUnqualifiedType();
6984
Eli Friedman3d815e72008-08-22 00:56:42 +00006985 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00006986 if (Unqualified) {
6987 largtype = largtype.getUnqualifiedType();
6988 rargtype = rargtype.getUnqualifiedType();
6989 }
6990
Chris Lattner61710852008-10-05 17:34:18 +00006991 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6992 allLTypes = false;
6993 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6994 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00006995 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006996
Eli Friedman3d815e72008-08-22 00:56:42 +00006997 if (allLTypes) return lhs;
6998 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00006999
7000 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7001 EPI.ExtInfo = einfo;
Jordan Rosebea522f2013-03-08 21:51:21 +00007002 return getFunctionType(retType, types, EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00007003 }
7004
7005 if (lproto) allRTypes = false;
7006 if (rproto) allLTypes = false;
7007
Douglas Gregor72564e72009-02-26 23:50:07 +00007008 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00007009 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00007010 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00007011 if (proto->isVariadic()) return QualType();
7012 // Check that the types are compatible with the types that
7013 // would result from default argument promotions (C99 6.7.5.3p15).
7014 // The only types actually affected are promotable integer
7015 // types and floats, which would be passed as a different
7016 // type depending on whether the prototype is visible.
7017 unsigned proto_nargs = proto->getNumArgs();
7018 for (unsigned i = 0; i < proto_nargs; ++i) {
7019 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007020
Eli Friedmanc586d5d2012-08-30 00:44:15 +00007021 // Look at the converted type of enum types, since that is the type used
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007022 // to pass enum values.
Eli Friedmanc586d5d2012-08-30 00:44:15 +00007023 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
7024 argTy = Enum->getDecl()->getIntegerType();
7025 if (argTy.isNull())
7026 return QualType();
7027 }
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007028
Eli Friedman3d815e72008-08-22 00:56:42 +00007029 if (argTy->isPromotableIntegerType() ||
7030 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
7031 return QualType();
7032 }
7033
7034 if (allLTypes) return lhs;
7035 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00007036
7037 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7038 EPI.ExtInfo = einfo;
Reid Kleckner0567a792013-06-10 20:51:09 +00007039 return getFunctionType(retType, proto->getArgTypes(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00007040 }
7041
7042 if (allLTypes) return lhs;
7043 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00007044 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00007045}
7046
John McCallb9da7132013-03-21 00:10:07 +00007047/// Given that we have an enum type and a non-enum type, try to merge them.
7048static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7049 QualType other, bool isBlockReturnType) {
7050 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7051 // a signed integer type, or an unsigned integer type.
7052 // Compatibility is based on the underlying type, not the promotion
7053 // type.
7054 QualType underlyingType = ET->getDecl()->getIntegerType();
7055 if (underlyingType.isNull()) return QualType();
7056 if (Context.hasSameType(underlyingType, other))
7057 return other;
7058
7059 // In block return types, we're more permissive and accept any
7060 // integral type of the same size.
7061 if (isBlockReturnType && other->isIntegerType() &&
7062 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7063 return other;
7064
7065 return QualType();
7066}
7067
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007068QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00007069 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00007070 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00007071 // C++ [expr]: If an expression initially has the type "reference to T", the
7072 // type is adjusted to "T" prior to any further analysis, the expression
7073 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00007074 // expression is an lvalue unless the reference is an rvalue reference and
7075 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00007076 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7077 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00007078
7079 if (Unqualified) {
7080 LHS = LHS.getUnqualifiedType();
7081 RHS = RHS.getUnqualifiedType();
7082 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00007083
Eli Friedman3d815e72008-08-22 00:56:42 +00007084 QualType LHSCan = getCanonicalType(LHS),
7085 RHSCan = getCanonicalType(RHS);
7086
7087 // If two types are identical, they are compatible.
7088 if (LHSCan == RHSCan)
7089 return LHS;
7090
John McCall0953e762009-09-24 19:53:00 +00007091 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00007092 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7093 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00007094 if (LQuals != RQuals) {
7095 // If any of these qualifiers are different, we have a type
7096 // mismatch.
7097 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00007098 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7099 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00007100 return QualType();
7101
7102 // Exactly one GC qualifier difference is allowed: __strong is
7103 // okay if the other type has no GC qualifier but is an Objective
7104 // C object pointer (i.e. implicitly strong by default). We fix
7105 // this by pretending that the unqualified type was actually
7106 // qualified __strong.
7107 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7108 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7109 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7110
7111 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7112 return QualType();
7113
7114 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7115 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7116 }
7117 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7118 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7119 }
Eli Friedman3d815e72008-08-22 00:56:42 +00007120 return QualType();
John McCall0953e762009-09-24 19:53:00 +00007121 }
7122
7123 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00007124
Eli Friedman852d63b2009-06-01 01:22:52 +00007125 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7126 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00007127
Chris Lattner1adb8832008-01-14 05:45:46 +00007128 // We want to consider the two function types to be the same for these
7129 // comparisons, just force one to the other.
7130 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7131 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00007132
7133 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00007134 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7135 LHSClass = Type::ConstantArray;
7136 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7137 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00007138
John McCallc12c5bb2010-05-15 11:32:37 +00007139 // ObjCInterfaces are just specialized ObjCObjects.
7140 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7141 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7142
Nate Begeman213541a2008-04-18 23:10:10 +00007143 // Canonicalize ExtVector -> Vector.
7144 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7145 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00007146
Chris Lattnera36a61f2008-04-07 05:43:21 +00007147 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00007148 if (LHSClass != RHSClass) {
John McCallb9da7132013-03-21 00:10:07 +00007149 // Note that we only have special rules for turning block enum
7150 // returns into block int returns, not vice-versa.
John McCall183700f2009-09-21 23:43:11 +00007151 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCallb9da7132013-03-21 00:10:07 +00007152 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmanbab96962008-02-12 08:46:17 +00007153 }
John McCall183700f2009-09-21 23:43:11 +00007154 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCallb9da7132013-03-21 00:10:07 +00007155 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmanbab96962008-02-12 08:46:17 +00007156 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00007157 // allow block pointer type to match an 'id' type.
Fariborz Jahanian41963632012-01-26 17:08:50 +00007158 if (OfBlockPointer && !BlockReturnType) {
7159 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7160 return LHS;
7161 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7162 return RHS;
7163 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00007164
Eli Friedman3d815e72008-08-22 00:56:42 +00007165 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00007166 }
Eli Friedman3d815e72008-08-22 00:56:42 +00007167
Steve Naroff4a746782008-01-09 22:43:08 +00007168 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00007169 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00007170#define TYPE(Class, Base)
7171#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00007172#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00007173#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7174#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7175#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00007176 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00007177
Richard Smithdc7a4f52013-04-30 13:56:41 +00007178 case Type::Auto:
Sebastian Redl7c80bd62009-03-16 23:22:08 +00007179 case Type::LValueReference:
7180 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00007181 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00007182 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00007183
John McCallc12c5bb2010-05-15 11:32:37 +00007184 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00007185 case Type::IncompleteArray:
7186 case Type::VariableArray:
7187 case Type::FunctionProto:
7188 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00007189 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00007190
Chris Lattner1adb8832008-01-14 05:45:46 +00007191 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00007192 {
7193 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00007194 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7195 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007196 if (Unqualified) {
7197 LHSPointee = LHSPointee.getUnqualifiedType();
7198 RHSPointee = RHSPointee.getUnqualifiedType();
7199 }
7200 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7201 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00007202 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00007203 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00007204 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00007205 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00007206 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00007207 return getPointerType(ResultType);
7208 }
Steve Naroffc0febd52008-12-10 17:49:55 +00007209 case Type::BlockPointer:
7210 {
7211 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00007212 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7213 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007214 if (Unqualified) {
7215 LHSPointee = LHSPointee.getUnqualifiedType();
7216 RHSPointee = RHSPointee.getUnqualifiedType();
7217 }
7218 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7219 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00007220 if (ResultType.isNull()) return QualType();
7221 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7222 return LHS;
7223 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7224 return RHS;
7225 return getBlockPointerType(ResultType);
7226 }
Eli Friedmanb001de72011-10-06 23:00:33 +00007227 case Type::Atomic:
7228 {
7229 // Merge two pointer types, while trying to preserve typedef info
7230 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7231 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7232 if (Unqualified) {
7233 LHSValue = LHSValue.getUnqualifiedType();
7234 RHSValue = RHSValue.getUnqualifiedType();
7235 }
7236 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7237 Unqualified);
7238 if (ResultType.isNull()) return QualType();
7239 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7240 return LHS;
7241 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7242 return RHS;
7243 return getAtomicType(ResultType);
7244 }
Chris Lattner1adb8832008-01-14 05:45:46 +00007245 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00007246 {
7247 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7248 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7249 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7250 return QualType();
7251
7252 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7253 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007254 if (Unqualified) {
7255 LHSElem = LHSElem.getUnqualifiedType();
7256 RHSElem = RHSElem.getUnqualifiedType();
7257 }
7258
7259 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00007260 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00007261 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7262 return LHS;
7263 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7264 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00007265 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7266 ArrayType::ArraySizeModifier(), 0);
7267 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7268 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00007269 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7270 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00007271 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7272 return LHS;
7273 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7274 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00007275 if (LVAT) {
7276 // FIXME: This isn't correct! But tricky to implement because
7277 // the array's size has to be the size of LHS, but the type
7278 // has to be different.
7279 return LHS;
7280 }
7281 if (RVAT) {
7282 // FIXME: This isn't correct! But tricky to implement because
7283 // the array's size has to be the size of RHS, but the type
7284 // has to be different.
7285 return RHS;
7286 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00007287 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7288 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00007289 return getIncompleteArrayType(ResultType,
7290 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00007291 }
Chris Lattner1adb8832008-01-14 05:45:46 +00007292 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00007293 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00007294 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00007295 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00007296 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00007297 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00007298 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00007299 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00007300 case Type::Complex:
7301 // Distinct complex types are incompatible.
7302 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00007303 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00007304 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00007305 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7306 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00007307 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00007308 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00007309 case Type::ObjCObject: {
7310 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00007311 // FIXME: This should be type compatibility, e.g. whether
7312 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00007313 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7314 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7315 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00007316 return LHS;
7317
Eli Friedman3d815e72008-08-22 00:56:42 +00007318 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00007319 }
Steve Naroff14108da2009-07-10 23:34:53 +00007320 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007321 if (OfBlockPointer) {
7322 if (canAssignObjCInterfacesInBlockPointer(
7323 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00007324 RHS->getAs<ObjCObjectPointerType>(),
7325 BlockReturnType))
David Blaikie7530c032012-01-17 06:56:22 +00007326 return LHS;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007327 return QualType();
7328 }
John McCall183700f2009-09-21 23:43:11 +00007329 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7330 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00007331 return LHS;
7332
Steve Naroffbc76dd02008-12-10 22:14:21 +00007333 return QualType();
David Blaikie7530c032012-01-17 06:56:22 +00007334 }
Steve Naroffec0550f2007-10-15 20:41:53 +00007335 }
Douglas Gregor72564e72009-02-26 23:50:07 +00007336
David Blaikie7530c032012-01-17 06:56:22 +00007337 llvm_unreachable("Invalid Type::Class!");
Steve Naroffec0550f2007-10-15 20:41:53 +00007338}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00007339
Fariborz Jahanian78213e42011-09-28 21:52:05 +00007340bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7341 const FunctionProtoType *FromFunctionType,
7342 const FunctionProtoType *ToFunctionType) {
7343 if (FromFunctionType->hasAnyConsumedArgs() !=
7344 ToFunctionType->hasAnyConsumedArgs())
7345 return false;
7346 FunctionProtoType::ExtProtoInfo FromEPI =
7347 FromFunctionType->getExtProtoInfo();
7348 FunctionProtoType::ExtProtoInfo ToEPI =
7349 ToFunctionType->getExtProtoInfo();
7350 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
7351 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
7352 ArgIdx != NumArgs; ++ArgIdx) {
7353 if (FromEPI.ConsumedArguments[ArgIdx] !=
7354 ToEPI.ConsumedArguments[ArgIdx])
7355 return false;
7356 }
7357 return true;
7358}
7359
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007360/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7361/// 'RHS' attributes and returns the merged version; including for function
7362/// return types.
7363QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7364 QualType LHSCan = getCanonicalType(LHS),
7365 RHSCan = getCanonicalType(RHS);
7366 // If two types are identical, they are compatible.
7367 if (LHSCan == RHSCan)
7368 return LHS;
7369 if (RHSCan->isFunctionType()) {
7370 if (!LHSCan->isFunctionType())
7371 return QualType();
7372 QualType OldReturnType =
7373 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7374 QualType NewReturnType =
7375 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7376 QualType ResReturnType =
7377 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7378 if (ResReturnType.isNull())
7379 return QualType();
7380 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7381 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7382 // In either case, use OldReturnType to build the new function type.
7383 const FunctionType *F = LHS->getAs<FunctionType>();
7384 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00007385 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7386 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner0567a792013-06-10 20:51:09 +00007387 QualType ResultType =
7388 getFunctionType(OldReturnType, FPT->getArgTypes(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007389 return ResultType;
7390 }
7391 }
7392 return QualType();
7393 }
7394
7395 // If the qualifiers are different, the types can still be merged.
7396 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7397 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7398 if (LQuals != RQuals) {
7399 // If any of these qualifiers are different, we have a type mismatch.
7400 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7401 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7402 return QualType();
7403
7404 // Exactly one GC qualifier difference is allowed: __strong is
7405 // okay if the other type has no GC qualifier but is an Objective
7406 // C object pointer (i.e. implicitly strong by default). We fix
7407 // this by pretending that the unqualified type was actually
7408 // qualified __strong.
7409 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7410 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7411 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7412
7413 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7414 return QualType();
7415
7416 if (GC_L == Qualifiers::Strong)
7417 return LHS;
7418 if (GC_R == Qualifiers::Strong)
7419 return RHS;
7420 return QualType();
7421 }
7422
7423 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7424 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7425 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7426 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7427 if (ResQT == LHSBaseQT)
7428 return LHS;
7429 if (ResQT == RHSBaseQT)
7430 return RHS;
7431 }
7432 return QualType();
7433}
7434
Chris Lattner5426bf62008-04-07 07:01:58 +00007435//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00007436// Integer Predicates
7437//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00007438
Jay Foad4ba2a172011-01-12 09:06:06 +00007439unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00007440 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00007441 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007442 if (T->isBooleanType())
7443 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00007444 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00007445 return (unsigned)getTypeSize(T);
7446}
7447
Abramo Bagnara762f1592012-09-09 10:21:24 +00007448QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregorf6094622010-07-23 15:58:24 +00007449 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00007450
7451 // Turn <4 x signed int> -> <4 x unsigned int>
7452 if (const VectorType *VTy = T->getAs<VectorType>())
7453 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00007454 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00007455
7456 // For enums, we return the unsigned version of the base type.
7457 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00007458 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00007459
7460 const BuiltinType *BTy = T->getAs<BuiltinType>();
7461 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007462 switch (BTy->getKind()) {
7463 case BuiltinType::Char_S:
7464 case BuiltinType::SChar:
7465 return UnsignedCharTy;
7466 case BuiltinType::Short:
7467 return UnsignedShortTy;
7468 case BuiltinType::Int:
7469 return UnsignedIntTy;
7470 case BuiltinType::Long:
7471 return UnsignedLongTy;
7472 case BuiltinType::LongLong:
7473 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00007474 case BuiltinType::Int128:
7475 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00007476 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00007477 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007478 }
7479}
7480
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00007481ASTMutationListener::~ASTMutationListener() { }
7482
Richard Smith9dadfab2013-05-11 05:45:24 +00007483void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7484 QualType ReturnType) {}
Chris Lattner86df27b2009-06-14 00:45:47 +00007485
7486//===----------------------------------------------------------------------===//
7487// Builtin Type Computation
7488//===----------------------------------------------------------------------===//
7489
7490/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00007491/// pointer over the consumed characters. This returns the resultant type. If
7492/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7493/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7494/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00007495///
7496/// RequiresICE is filled in on return to indicate whether the value is required
7497/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00007498static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00007499 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00007500 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00007501 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00007502 // Modifiers.
7503 int HowLong = 0;
7504 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00007505 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007506
Chris Lattner33daae62010-10-01 22:42:38 +00007507 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00007508 bool Done = false;
7509 while (!Done) {
7510 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00007511 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007512 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00007513 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007514 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007515 case 'S':
7516 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7517 assert(!Signed && "Can't use 'S' modifier multiple times!");
7518 Signed = true;
7519 break;
7520 case 'U':
7521 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7522 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7523 Unsigned = true;
7524 break;
7525 case 'L':
7526 assert(HowLong <= 2 && "Can't have LLLL modifier");
7527 ++HowLong;
7528 break;
7529 }
7530 }
7531
7532 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00007533
Chris Lattner86df27b2009-06-14 00:45:47 +00007534 // Read the base type.
7535 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00007536 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00007537 case 'v':
7538 assert(HowLong == 0 && !Signed && !Unsigned &&
7539 "Bad modifiers used with 'v'!");
7540 Type = Context.VoidTy;
7541 break;
7542 case 'f':
7543 assert(HowLong == 0 && !Signed && !Unsigned &&
7544 "Bad modifiers used with 'f'!");
7545 Type = Context.FloatTy;
7546 break;
7547 case 'd':
7548 assert(HowLong < 2 && !Signed && !Unsigned &&
7549 "Bad modifiers used with 'd'!");
7550 if (HowLong)
7551 Type = Context.LongDoubleTy;
7552 else
7553 Type = Context.DoubleTy;
7554 break;
7555 case 's':
7556 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7557 if (Unsigned)
7558 Type = Context.UnsignedShortTy;
7559 else
7560 Type = Context.ShortTy;
7561 break;
7562 case 'i':
7563 if (HowLong == 3)
7564 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7565 else if (HowLong == 2)
7566 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7567 else if (HowLong == 1)
7568 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7569 else
7570 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7571 break;
7572 case 'c':
7573 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7574 if (Signed)
7575 Type = Context.SignedCharTy;
7576 else if (Unsigned)
7577 Type = Context.UnsignedCharTy;
7578 else
7579 Type = Context.CharTy;
7580 break;
7581 case 'b': // boolean
7582 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7583 Type = Context.BoolTy;
7584 break;
7585 case 'z': // size_t.
7586 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7587 Type = Context.getSizeType();
7588 break;
7589 case 'F':
7590 Type = Context.getCFConstantStringType();
7591 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00007592 case 'G':
7593 Type = Context.getObjCIdType();
7594 break;
7595 case 'H':
7596 Type = Context.getObjCSelType();
7597 break;
Fariborz Jahanianf7992132013-01-04 18:45:40 +00007598 case 'M':
7599 Type = Context.getObjCSuperType();
7600 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007601 case 'a':
7602 Type = Context.getBuiltinVaListType();
7603 assert(!Type.isNull() && "builtin va list type not initialized!");
7604 break;
7605 case 'A':
7606 // This is a "reference" to a va_list; however, what exactly
7607 // this means depends on how va_list is defined. There are two
7608 // different kinds of va_list: ones passed by value, and ones
7609 // passed by reference. An example of a by-value va_list is
7610 // x86, where va_list is a char*. An example of by-ref va_list
7611 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7612 // we want this argument to be a char*&; for x86-64, we want
7613 // it to be a __va_list_tag*.
7614 Type = Context.getBuiltinVaListType();
7615 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00007616 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00007617 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00007618 else
Chris Lattner86df27b2009-06-14 00:45:47 +00007619 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00007620 break;
7621 case 'V': {
7622 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00007623 unsigned NumElements = strtoul(Str, &End, 10);
7624 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00007625 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00007626
Chris Lattner14e0e742010-10-01 22:53:11 +00007627 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7628 RequiresICE, false);
7629 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00007630
7631 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00007632 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00007633 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00007634 break;
7635 }
Douglas Gregorb4bc99b2012-06-07 18:08:25 +00007636 case 'E': {
7637 char *End;
7638
7639 unsigned NumElements = strtoul(Str, &End, 10);
7640 assert(End != Str && "Missing vector size");
7641
7642 Str = End;
7643
7644 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7645 false);
7646 Type = Context.getExtVectorType(ElementType, NumElements);
7647 break;
7648 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00007649 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00007650 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7651 false);
7652 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00007653 Type = Context.getComplexType(ElementType);
7654 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00007655 }
7656 case 'Y' : {
7657 Type = Context.getPointerDiffType();
7658 break;
7659 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007660 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00007661 Type = Context.getFILEType();
7662 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007663 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00007664 return QualType();
7665 }
Mike Stumpfd612db2009-07-28 23:47:15 +00007666 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007667 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00007668 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00007669 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00007670 else
7671 Type = Context.getjmp_bufType();
7672
Mike Stumpfd612db2009-07-28 23:47:15 +00007673 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007674 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00007675 return QualType();
7676 }
7677 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00007678 case 'K':
7679 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7680 Type = Context.getucontext_tType();
7681
7682 if (Type.isNull()) {
7683 Error = ASTContext::GE_Missing_ucontext;
7684 return QualType();
7685 }
7686 break;
Eli Friedman6902e412012-11-27 02:58:24 +00007687 case 'p':
7688 Type = Context.getProcessIDType();
7689 break;
Mike Stump782fa302009-07-28 02:25:19 +00007690 }
Mike Stump1eb44332009-09-09 15:08:12 +00007691
Chris Lattner33daae62010-10-01 22:42:38 +00007692 // If there are modifiers and if we're allowed to parse them, go for it.
7693 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00007694 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00007695 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00007696 default: Done = true; --Str; break;
7697 case '*':
7698 case '&': {
7699 // Both pointers and references can have their pointee types
7700 // qualified with an address space.
7701 char *End;
7702 unsigned AddrSpace = strtoul(Str, &End, 10);
7703 if (End != Str && AddrSpace != 0) {
7704 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7705 Str = End;
7706 }
7707 if (c == '*')
7708 Type = Context.getPointerType(Type);
7709 else
7710 Type = Context.getLValueReferenceType(Type);
7711 break;
7712 }
7713 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7714 case 'C':
7715 Type = Type.withConst();
7716 break;
7717 case 'D':
7718 Type = Context.getVolatileType(Type);
7719 break;
Ted Kremenek18932a02012-01-20 21:40:12 +00007720 case 'R':
7721 Type = Type.withRestrict();
7722 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007723 }
7724 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00007725
Chris Lattner14e0e742010-10-01 22:53:11 +00007726 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00007727 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00007728
Chris Lattner86df27b2009-06-14 00:45:47 +00007729 return Type;
7730}
7731
7732/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00007733QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00007734 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00007735 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00007736 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00007737
Chris Lattner5f9e2722011-07-23 10:55:15 +00007738 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00007739
Chris Lattner14e0e742010-10-01 22:53:11 +00007740 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00007741 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00007742 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7743 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007744 if (Error != GE_None)
7745 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00007746
7747 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7748
Chris Lattner86df27b2009-06-14 00:45:47 +00007749 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00007750 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007751 if (Error != GE_None)
7752 return QualType();
7753
Chris Lattner14e0e742010-10-01 22:53:11 +00007754 // If this argument is required to be an IntegerConstantExpression and the
7755 // caller cares, fill in the bitmask we return.
7756 if (RequiresICE && IntegerConstantArgs)
7757 *IntegerConstantArgs |= 1 << ArgTypes.size();
7758
Chris Lattner86df27b2009-06-14 00:45:47 +00007759 // Do array -> pointer decay. The builtin should use the decayed type.
7760 if (Ty->isArrayType())
7761 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00007762
Chris Lattner86df27b2009-06-14 00:45:47 +00007763 ArgTypes.push_back(Ty);
7764 }
7765
7766 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7767 "'.' should only occur at end of builtin type list!");
7768
John McCall00ccbef2010-12-21 00:44:39 +00007769 FunctionType::ExtInfo EI;
7770 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7771
7772 bool Variadic = (TypeStr[0] == '.');
7773
7774 // We really shouldn't be making a no-proto type here, especially in C++.
7775 if (ArgTypes.empty() && Variadic)
7776 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00007777
John McCalle23cf432010-12-14 08:05:40 +00007778 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00007779 EPI.ExtInfo = EI;
7780 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00007781
Jordan Rosebea522f2013-03-08 21:51:21 +00007782 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00007783}
Eli Friedmana95d7572009-08-19 07:44:53 +00007784
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007785GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007786 if (!FD->isExternallyVisible())
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007787 return GVA_Internal;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007788
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007789 GVALinkage External = GVA_StrongExternal;
7790 switch (FD->getTemplateSpecializationKind()) {
7791 case TSK_Undeclared:
7792 case TSK_ExplicitSpecialization:
7793 External = GVA_StrongExternal;
7794 break;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007795
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007796 case TSK_ExplicitInstantiationDefinition:
7797 return GVA_ExplicitTemplateInstantiation;
7798
7799 case TSK_ExplicitInstantiationDeclaration:
7800 case TSK_ImplicitInstantiation:
7801 External = GVA_TemplateInstantiation;
7802 break;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007803 }
7804
7805 if (!FD->isInlined())
7806 return External;
7807
David Blaikie4e4d0842012-03-11 07:00:24 +00007808 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007809 // GNU or C99 inline semantics. Determine whether this symbol should be
7810 // externally visible.
7811 if (FD->isInlineDefinitionExternallyVisible())
7812 return External;
7813
7814 // C99 inline semantics, where the symbol is not externally visible.
7815 return GVA_C99Inline;
7816 }
7817
7818 // C++0x [temp.explicit]p9:
7819 // [ Note: The intent is that an inline function that is the subject of
7820 // an explicit instantiation declaration will still be implicitly
7821 // instantiated when used so that the body can be considered for
7822 // inlining, but that no out-of-line copy of the inline function would be
7823 // generated in the translation unit. -- end note ]
7824 if (FD->getTemplateSpecializationKind()
7825 == TSK_ExplicitInstantiationDeclaration)
7826 return GVA_C99Inline;
7827
7828 return GVA_CXXInline;
7829}
7830
7831GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007832 if (!VD->isExternallyVisible())
7833 return GVA_Internal;
7834
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007835 // If this is a static data member, compute the kind of template
7836 // specialization. Otherwise, this variable is not part of a
7837 // template.
7838 TemplateSpecializationKind TSK = TSK_Undeclared;
7839 if (VD->isStaticDataMember())
7840 TSK = VD->getTemplateSpecializationKind();
7841
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007842 switch (TSK) {
7843 case TSK_Undeclared:
7844 case TSK_ExplicitSpecialization:
7845 return GVA_StrongExternal;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007846
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007847 case TSK_ExplicitInstantiationDeclaration:
7848 llvm_unreachable("Variable should not be instantiated");
7849 // Fall through to treat this like any other instantiation.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007850
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007851 case TSK_ExplicitInstantiationDefinition:
7852 return GVA_ExplicitTemplateInstantiation;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007853
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007854 case TSK_ImplicitInstantiation:
7855 return GVA_TemplateInstantiation;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007856 }
Rafael Espindola77b50252013-05-13 14:05:53 +00007857
7858 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007859}
7860
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00007861bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007862 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7863 if (!VD->isFileVarDecl())
7864 return false;
Richard Smithf396ad92013-04-01 20:22:16 +00007865 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7866 // We never need to emit an uninstantiated function template.
7867 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7868 return false;
7869 } else
7870 return false;
7871
7872 // If this is a member of a class template, we do not need to emit it.
7873 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007874 return false;
7875
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007876 // Weak references don't produce any output by themselves.
7877 if (D->hasAttr<WeakRefAttr>())
7878 return false;
7879
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007880 // Aliases and used decls are required.
7881 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7882 return true;
7883
7884 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7885 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00007886 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00007887 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007888
7889 // Constructors and destructors are required.
7890 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7891 return true;
7892
John McCalld5617ee2013-01-25 22:31:03 +00007893 // The key function for a class is required. This rule only comes
7894 // into play when inline functions can be key functions, though.
7895 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7896 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7897 const CXXRecordDecl *RD = MD->getParent();
7898 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7899 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7900 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7901 return true;
7902 }
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007903 }
7904 }
7905
7906 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7907
7908 // static, static inline, always_inline, and extern inline functions can
7909 // always be deferred. Normal inline functions can be deferred in C99/C++.
7910 // Implicit template instantiations can also be deferred in C++.
7911 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev3a5aca82012-02-02 06:06:34 +00007912 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007913 return false;
7914 return true;
7915 }
Douglas Gregor94da1582011-09-10 00:22:34 +00007916
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007917 const VarDecl *VD = cast<VarDecl>(D);
7918 assert(VD->isFileVarDecl() && "Expected file scoped var");
7919
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007920 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7921 return false;
7922
Richard Smith5f9a7e32012-11-12 21:38:00 +00007923 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007924 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smith5f9a7e32012-11-12 21:38:00 +00007925 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7926 return true;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007927
Richard Smith5f9a7e32012-11-12 21:38:00 +00007928 // Variables that have destruction with side-effects are required.
7929 if (VD->getType().isDestructedType())
7930 return true;
7931
7932 // Variables that have initialization with side-effects are required.
7933 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7934 return true;
7935
7936 return false;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007937}
Charles Davis071cc7d2010-08-16 03:33:14 +00007938
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007939CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davisee743f92010-11-09 18:04:24 +00007940 // Pass through to the C++ ABI object
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007941 return ABI->getDefaultMethodCallConv(isVariadic);
7942}
7943
7944CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
John McCallb8b2c9d2013-01-25 22:30:49 +00007945 if (CC == CC_C && !LangOpts.MRTD &&
7946 getTargetInfo().getCXXABI().isMemberFunctionCCDefault())
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007947 return CC_Default;
7948 return CC;
Charles Davisee743f92010-11-09 18:04:24 +00007949}
7950
Jay Foad4ba2a172011-01-12 09:06:06 +00007951bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00007952 // Pass through to the C++ ABI object
7953 return ABI->isNearlyEmpty(RD);
7954}
7955
Peter Collingbourne14110472011-01-13 18:57:25 +00007956MangleContext *ASTContext::createMangleContext() {
John McCallb8b2c9d2013-01-25 22:30:49 +00007957 switch (Target->getCXXABI().getKind()) {
Tim Northoverc264e162013-01-31 12:13:10 +00007958 case TargetCXXABI::GenericAArch64:
John McCallb8b2c9d2013-01-25 22:30:49 +00007959 case TargetCXXABI::GenericItanium:
7960 case TargetCXXABI::GenericARM:
7961 case TargetCXXABI::iOS:
Peter Collingbourne14110472011-01-13 18:57:25 +00007962 return createItaniumMangleContext(*this, getDiagnostics());
John McCallb8b2c9d2013-01-25 22:30:49 +00007963 case TargetCXXABI::Microsoft:
Peter Collingbourne14110472011-01-13 18:57:25 +00007964 return createMicrosoftMangleContext(*this, getDiagnostics());
7965 }
David Blaikieb219cfc2011-09-23 05:06:16 +00007966 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00007967}
7968
Charles Davis071cc7d2010-08-16 03:33:14 +00007969CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00007970
7971size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00007972 return ASTRecordLayouts.getMemorySize()
7973 + llvm::capacity_in_bytes(ObjCLayouts)
7974 + llvm::capacity_in_bytes(KeyFunctions)
7975 + llvm::capacity_in_bytes(ObjCImpls)
7976 + llvm::capacity_in_bytes(BlockVarCopyInits)
7977 + llvm::capacity_in_bytes(DeclAttrs)
7978 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7979 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7980 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7981 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7982 + llvm::capacity_in_bytes(OverriddenMethods)
7983 + llvm::capacity_in_bytes(Types)
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007984 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet0d95f0d2011-08-14 14:28:49 +00007985 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00007986}
Ted Kremenekd211cb72011-10-06 05:00:56 +00007987
David Blaikie66cff722012-11-14 01:52:05 +00007988void ASTContext::addUnnamedTag(const TagDecl *Tag) {
7989 // FIXME: This mangling should be applied to function local classes too
7990 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl() ||
Rafael Espindola5bbb0582013-05-28 14:09:46 +00007991 !isa<CXXRecordDecl>(Tag->getParent()))
David Blaikie66cff722012-11-14 01:52:05 +00007992 return;
7993
7994 std::pair<llvm::DenseMap<const DeclContext *, unsigned>::iterator, bool> P =
7995 UnnamedMangleContexts.insert(std::make_pair(Tag->getParent(), 0));
7996 UnnamedMangleNumbers.insert(std::make_pair(Tag, P.first->second++));
7997}
7998
7999int ASTContext::getUnnamedTagManglingNumber(const TagDecl *Tag) const {
8000 llvm::DenseMap<const TagDecl *, unsigned>::const_iterator I =
8001 UnnamedMangleNumbers.find(Tag);
8002 return I != UnnamedMangleNumbers.end() ? I->second : -1;
8003}
8004
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00008005unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
8006 CXXRecordDecl *Lambda = CallOperator->getParent();
8007 return LambdaMangleContexts[Lambda->getDeclContext()]
8008 .getManglingNumber(CallOperator);
8009}
8010
8011
Ted Kremenekd211cb72011-10-06 05:00:56 +00008012void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8013 ParamIndices[D] = index;
8014}
8015
8016unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8017 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8018 assert(I != ParamIndices.end() &&
8019 "ParmIndices lacks entry set by ParmVarDecl");
8020 return I->second;
8021}
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00008022
Richard Smith211c8dd2013-06-05 00:46:14 +00008023APValue *
8024ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8025 bool MayCreate) {
8026 assert(E && E->getStorageDuration() == SD_Static &&
8027 "don't need to cache the computed value for this temporary");
8028 if (MayCreate)
8029 return &MaterializedTemporaryValues[E];
8030
8031 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8032 MaterializedTemporaryValues.find(E);
8033 return I == MaterializedTemporaryValues.end() ? 0 : &I->second;
8034}
8035
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00008036bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8037 const llvm::Triple &T = getTargetInfo().getTriple();
8038 if (!T.isOSDarwin())
8039 return false;
8040
8041 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8042 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8043 uint64_t Size = sizeChars.getQuantity();
8044 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8045 unsigned Align = alignChars.getQuantity();
8046 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8047 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8048}