blob: 8984c3c96dd098f89c9e2ae1deac7be402708dad [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"
Reid Klecknercff15122013-06-17 12:56:08 +000029#include "clang/AST/RecursiveASTVisitor.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000030#include "clang/AST/TypeLoc.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000031#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000032#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000034#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000035#include "llvm/ADT/StringExtras.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000036#include "llvm/Support/Capacity.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000037#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000038#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +000039#include <map>
Anders Carlsson29445a02009-07-18 21:19:52 +000040
Reid Spencer5f016e22007-07-11 17:01:13 +000041using namespace clang;
42
Douglas Gregor18274032010-07-03 00:47:00 +000043unsigned ASTContext::NumImplicitDefaultConstructors;
44unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000045unsigned ASTContext::NumImplicitCopyConstructors;
46unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000047unsigned ASTContext::NumImplicitMoveConstructors;
48unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000049unsigned ASTContext::NumImplicitCopyAssignmentOperators;
50unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000051unsigned ASTContext::NumImplicitMoveAssignmentOperators;
52unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000053unsigned ASTContext::NumImplicitDestructors;
54unsigned ASTContext::NumImplicitDestructorsDeclared;
55
Reid Spencer5f016e22007-07-11 17:01:13 +000056enum FloatingRank {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +000057 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Reid Spencer5f016e22007-07-11 17:01:13 +000058};
59
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000060RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +000061 if (!CommentsLoaded && ExternalSource) {
62 ExternalSource->ReadComments();
63 CommentsLoaded = true;
64 }
65
66 assert(D);
67
Dmitri Gribenkoc3fee352012-06-28 16:19:39 +000068 // User can not attach documentation to implicit declarations.
69 if (D->isImplicit())
70 return NULL;
71
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +000072 // User can not attach documentation to implicit instantiations.
73 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
74 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
75 return NULL;
76 }
77
Dmitri Gribenkodce750b2012-08-20 22:36:31 +000078 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
79 if (VD->isStaticDataMember() &&
80 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
81 return NULL;
82 }
83
84 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
85 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
86 return NULL;
87 }
88
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +000089 if (const ClassTemplateSpecializationDecl *CTSD =
90 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
91 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
92 if (TSK == TSK_ImplicitInstantiation ||
93 TSK == TSK_Undeclared)
94 return NULL;
95 }
96
Dmitri Gribenkodce750b2012-08-20 22:36:31 +000097 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
98 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
99 return NULL;
100 }
Fariborz Jahanian099ecfb2013-04-17 21:05:20 +0000101 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
102 // When tag declaration (but not definition!) is part of the
103 // decl-specifier-seq of some other declaration, it doesn't get comment
104 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
105 return NULL;
106 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000107 // TODO: handle comments for function parameters properly.
108 if (isa<ParmVarDecl>(D))
109 return NULL;
110
Dmitri Gribenko96b09862012-07-31 22:37:06 +0000111 // TODO: we could look up template parameter documentation in the template
112 // documentation.
113 if (isa<TemplateTypeParmDecl>(D) ||
114 isa<NonTypeTemplateParmDecl>(D) ||
115 isa<TemplateTemplateParmDecl>(D))
116 return NULL;
117
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000118 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000119
120 // If there are no comments anywhere, we won't find anything.
121 if (RawComments.empty())
122 return NULL;
123
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000124 // Find declaration location.
125 // For Objective-C declarations we generally don't expect to have multiple
126 // declarators, thus use declaration starting location as the "declaration
127 // location".
128 // For all other declarations multiple declarators are used quite frequently,
129 // so we use the location of the identifier as the "declaration location".
130 SourceLocation DeclLoc;
131 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko96b09862012-07-31 22:37:06 +0000132 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +0000133 isa<RedeclarableTemplateDecl>(D) ||
134 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000135 DeclLoc = D->getLocStart();
136 else
137 DeclLoc = D->getLocation();
138
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000139 // If the declaration doesn't map directly to a location in a file, we
140 // can't find the comment.
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000141 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
142 return NULL;
143
144 // Find the comment that occurs just after this declaration.
Dmitri Gribenkoa444f182012-07-17 22:01:09 +0000145 ArrayRef<RawComment *>::iterator Comment;
146 {
147 // When searching for comments during parsing, the comment we are looking
148 // for is usually among the last two comments we parsed -- check them
149 // first.
Dmitri Gribenko6fd7d302013-04-10 15:35:17 +0000150 RawComment CommentAtDeclLoc(
151 SourceMgr, SourceRange(DeclLoc), false,
152 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoa444f182012-07-17 22:01:09 +0000153 BeforeThanCompare<RawComment> Compare(SourceMgr);
154 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
155 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
156 if (!Found && RawComments.size() >= 2) {
157 MaybeBeforeDecl--;
158 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
159 }
160
161 if (Found) {
162 Comment = MaybeBeforeDecl + 1;
163 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
164 &CommentAtDeclLoc, Compare));
165 } else {
166 // Slow path.
167 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
168 &CommentAtDeclLoc, Compare);
169 }
170 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000171
172 // Decompose the location for the declaration and find the beginning of the
173 // file buffer.
174 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
175
176 // First check whether we have a trailing comment.
177 if (Comment != RawComments.end() &&
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000178 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Dmitri Gribenko9c006762012-07-06 23:27:33 +0000179 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000180 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000181 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000182 // Check that Doxygen trailing comment comes after the declaration, starts
183 // on the same line and in the same file as the declaration.
184 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
185 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
186 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
187 CommentBeginDecomp.second)) {
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000188 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000189 }
190 }
191
192 // The comment just after the declaration was not a trailing comment.
193 // Let's look at the previous comment.
194 if (Comment == RawComments.begin())
195 return NULL;
196 --Comment;
197
198 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000199 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000200 return NULL;
201
202 // Decompose the end of the comment.
203 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000204 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000205
206 // If the comment and the declaration aren't in the same file, then they
207 // aren't related.
208 if (DeclLocDecomp.first != CommentEndDecomp.first)
209 return NULL;
210
211 // Get the corresponding buffer.
212 bool Invalid = false;
213 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
214 &Invalid).data();
215 if (Invalid)
216 return NULL;
217
218 // Extract text between the comment and declaration.
219 StringRef Text(Buffer + CommentEndDecomp.second,
220 DeclLocDecomp.second - CommentEndDecomp.second);
221
Dmitri Gribenko8bdb58a2012-06-27 23:43:37 +0000222 // There should be no other declarations or preprocessor directives between
223 // comment and declaration.
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000224 if (Text.find_first_of(",;{}#@") != StringRef::npos)
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000225 return NULL;
226
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000227 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000228}
229
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000230namespace {
231/// If we have a 'templated' declaration for a template, adjust 'D' to
232/// refer to the actual template.
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000233/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000234const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregorcd81df22012-08-13 16:37:30 +0000235 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000236 // Is this function declaration part of a function template?
Douglas Gregorcd81df22012-08-13 16:37:30 +0000237 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000238 return FTD;
239
240 // Nothing to do if function is not an implicit instantiation.
241 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
242 return D;
243
244 // Function is an implicit instantiation of a function template?
245 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
246 return FTD;
247
248 // Function is instantiated from a member definition of a class template?
249 if (const FunctionDecl *MemberDecl =
250 FD->getInstantiatedFromMemberFunction())
251 return MemberDecl;
252
253 return D;
Douglas Gregorcd81df22012-08-13 16:37:30 +0000254 }
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000255 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
256 // Static data member is instantiated from a member definition of a class
257 // template?
258 if (VD->isStaticDataMember())
259 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
260 return MemberDecl;
261
262 return D;
263 }
264 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
265 // Is this class declaration part of a class template?
266 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
267 return CTD;
268
269 // Class is an implicit instantiation of a class template or partial
270 // specialization?
271 if (const ClassTemplateSpecializationDecl *CTSD =
272 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
273 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
274 return D;
275 llvm::PointerUnion<ClassTemplateDecl *,
276 ClassTemplatePartialSpecializationDecl *>
277 PU = CTSD->getSpecializedTemplateOrPartial();
278 return PU.is<ClassTemplateDecl*>() ?
279 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
280 static_cast<const Decl*>(
281 PU.get<ClassTemplatePartialSpecializationDecl *>());
282 }
283
284 // Class is instantiated from a member definition of a class template?
285 if (const MemberSpecializationInfo *Info =
286 CRD->getMemberSpecializationInfo())
287 return Info->getInstantiatedFrom();
288
289 return D;
290 }
291 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
292 // Enum is instantiated from a member definition of a class template?
293 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
294 return MemberDecl;
295
296 return D;
297 }
298 // FIXME: Adjust alias templates?
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000299 return D;
300}
301} // unnamed namespace
302
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000303const RawComment *ASTContext::getRawCommentForAnyRedecl(
304 const Decl *D,
305 const Decl **OriginalDecl) const {
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000306 D = adjustDeclToTemplate(D);
Douglas Gregorcd81df22012-08-13 16:37:30 +0000307
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000308 // Check whether we have cached a comment for this declaration already.
309 {
310 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
311 RedeclComments.find(D);
312 if (Pos != RedeclComments.end()) {
313 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000314 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
315 if (OriginalDecl)
316 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000317 return Raw.getRaw();
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000318 }
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000319 }
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000320 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000321
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000322 // Search for comments attached to declarations in the redeclaration chain.
323 const RawComment *RC = NULL;
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000324 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000325 for (Decl::redecl_iterator I = D->redecls_begin(),
326 E = D->redecls_end();
327 I != E; ++I) {
328 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
329 RedeclComments.find(*I);
330 if (Pos != RedeclComments.end()) {
331 const RawCommentAndCacheFlags &Raw = Pos->second;
332 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
333 RC = Raw.getRaw();
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000334 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000335 break;
336 }
337 } else {
338 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000339 OriginalDeclForRC = *I;
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000340 RawCommentAndCacheFlags Raw;
341 if (RC) {
342 Raw.setRaw(RC);
343 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
344 } else
345 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000346 Raw.setOriginalDecl(*I);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000347 RedeclComments[*I] = Raw;
348 if (RC)
349 break;
350 }
351 }
352
Dmitri Gribenko8376f592012-06-28 16:25:36 +0000353 // If we found a comment, it should be a documentation comment.
354 assert(!RC || RC->isDocumentation());
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000355
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000356 if (OriginalDecl)
357 *OriginalDecl = OriginalDeclForRC;
358
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000359 // Update cache for every declaration in the redeclaration chain.
360 RawCommentAndCacheFlags Raw;
361 Raw.setRaw(RC);
362 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000363 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000364
365 for (Decl::redecl_iterator I = D->redecls_begin(),
366 E = D->redecls_end();
367 I != E; ++I) {
368 RawCommentAndCacheFlags &R = RedeclComments[*I];
369 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
370 R = Raw;
371 }
372
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000373 return RC;
374}
375
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000376static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
377 SmallVectorImpl<const NamedDecl *> &Redeclared) {
378 const DeclContext *DC = ObjCMethod->getDeclContext();
379 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
380 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
381 if (!ID)
382 return;
383 // Add redeclared method here.
Douglas Gregord3297242013-01-16 23:00:23 +0000384 for (ObjCInterfaceDecl::known_extensions_iterator
385 Ext = ID->known_extensions_begin(),
386 ExtEnd = ID->known_extensions_end();
387 Ext != ExtEnd; ++Ext) {
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000388 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregord3297242013-01-16 23:00:23 +0000389 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000390 ObjCMethod->isInstanceMethod()))
391 Redeclared.push_back(RedeclaredMethod);
392 }
393 }
394}
395
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000396comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
397 const Decl *D) const {
398 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
399 ThisDeclInfo->CommentDecl = D;
400 ThisDeclInfo->IsFilled = false;
401 ThisDeclInfo->fill();
402 ThisDeclInfo->CommentDecl = FC->getDecl();
403 comments::FullComment *CFC =
404 new (*this) comments::FullComment(FC->getBlocks(),
405 ThisDeclInfo);
406 return CFC;
407
408}
409
Richard Smith0a74a4c2013-05-21 05:24:00 +0000410comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
411 const RawComment *RC = getRawCommentForDeclNoCache(D);
412 return RC ? RC->parse(*this, 0, D) : 0;
413}
414
Dmitri Gribenko19523542012-09-29 11:40:46 +0000415comments::FullComment *ASTContext::getCommentForDecl(
416 const Decl *D,
417 const Preprocessor *PP) const {
Fariborz Jahanianfbff0c42013-05-13 17:27:00 +0000418 if (D->isInvalidDecl())
419 return NULL;
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000420 D = adjustDeclToTemplate(D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000421
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000422 const Decl *Canonical = D->getCanonicalDecl();
423 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
424 ParsedComments.find(Canonical);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000425
426 if (Pos != ParsedComments.end()) {
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000427 if (Canonical != D) {
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000428 comments::FullComment *FC = Pos->second;
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000429 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000430 return CFC;
431 }
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000432 return Pos->second;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000433 }
434
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000435 const Decl *OriginalDecl;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000436
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000437 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000438 if (!RC) {
439 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko1e905da2012-11-03 14:24:57 +0000440 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanianc328d9c2013-01-12 00:28:34 +0000441 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000442 if (OMD && OMD->isPropertyAccessor())
443 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
444 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
445 return cloneFullComment(FC, D);
Fariborz Jahanianc328d9c2013-01-12 00:28:34 +0000446 if (OMD)
Dmitri Gribenko1e905da2012-11-03 14:24:57 +0000447 addRedeclaredMethods(OMD, Overridden);
448 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000449 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
450 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
451 return cloneFullComment(FC, D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000452 }
Fariborz Jahanian4857fdc2013-05-02 15:44:16 +0000453 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +0000454 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000455 // does not have one of its own.
Fariborz Jahanian41170b52013-01-25 22:48:32 +0000456 QualType QT = TD->getUnderlyingType();
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +0000457 if (const TagType *TT = QT->getAs<TagType>())
458 if (const Decl *TD = TT->getDecl())
459 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000460 return cloneFullComment(FC, D);
Fariborz Jahanian41170b52013-01-25 22:48:32 +0000461 }
Fariborz Jahanian622bb4a2013-04-26 20:55:38 +0000462 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
463 while (IC->getSuperClass()) {
464 IC = IC->getSuperClass();
465 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
466 return cloneFullComment(FC, D);
467 }
468 }
469 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
470 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
471 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
472 return cloneFullComment(FC, D);
473 }
474 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
475 if (!(RD = RD->getDefinition()))
476 return NULL;
477 // Check non-virtual bases.
478 for (CXXRecordDecl::base_class_const_iterator I =
479 RD->bases_begin(), E = RD->bases_end(); I != E; ++I) {
Fariborz Jahanian91efca02013-04-26 23:34:36 +0000480 if (I->isVirtual() || (I->getAccessSpecifier() != AS_public))
Fariborz Jahanian622bb4a2013-04-26 20:55:38 +0000481 continue;
482 QualType Ty = I->getType();
483 if (Ty.isNull())
484 continue;
485 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
486 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
487 continue;
488
489 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
490 return cloneFullComment(FC, D);
491 }
492 }
493 // Check virtual bases.
494 for (CXXRecordDecl::base_class_const_iterator I =
495 RD->vbases_begin(), E = RD->vbases_end(); I != E; ++I) {
Fariborz Jahanian91efca02013-04-26 23:34:36 +0000496 if (I->getAccessSpecifier() != AS_public)
497 continue;
Fariborz Jahanian622bb4a2013-04-26 20:55:38 +0000498 QualType Ty = I->getType();
499 if (Ty.isNull())
500 continue;
501 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
502 if (!(VirtualBase= VirtualBase->getDefinition()))
503 continue;
504 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
505 return cloneFullComment(FC, D);
506 }
507 }
508 }
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000509 return NULL;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000510 }
511
Dmitri Gribenko4b41c652012-08-22 18:12:19 +0000512 // If the RawComment was attached to other redeclaration of this Decl, we
513 // should parse the comment in context of that other Decl. This is important
514 // because comments can contain references to parameter names which can be
515 // different across redeclarations.
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000516 if (D != OriginalDecl)
Dmitri Gribenko19523542012-09-29 11:40:46 +0000517 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000518
Dmitri Gribenko19523542012-09-29 11:40:46 +0000519 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000520 ParsedComments[Canonical] = FC;
521 return FC;
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000522}
523
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000524void
525ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
526 TemplateTemplateParmDecl *Parm) {
527 ID.AddInteger(Parm->getDepth());
528 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +0000529 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000530
531 TemplateParameterList *Params = Parm->getTemplateParameters();
532 ID.AddInteger(Params->size());
533 for (TemplateParameterList::const_iterator P = Params->begin(),
534 PEnd = Params->end();
535 P != PEnd; ++P) {
536 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
537 ID.AddInteger(0);
538 ID.AddBoolean(TTP->isParameterPack());
539 continue;
540 }
541
542 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
543 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000544 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000545 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000546 if (NTTP->isExpandedParameterPack()) {
547 ID.AddBoolean(true);
548 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000549 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
550 QualType T = NTTP->getExpansionType(I);
551 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
552 }
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000553 } else
554 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000555 continue;
556 }
557
558 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
559 ID.AddInteger(2);
560 Profile(ID, TTP);
561 }
562}
563
564TemplateTemplateParmDecl *
565ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +0000566 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000567 // Check if we already have a canonical template template parameter.
568 llvm::FoldingSetNodeID ID;
569 CanonicalTemplateTemplateParm::Profile(ID, TTP);
570 void *InsertPos = 0;
571 CanonicalTemplateTemplateParm *Canonical
572 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
573 if (Canonical)
574 return Canonical->getParam();
575
576 // Build a canonical template parameter list.
577 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000578 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000579 CanonParams.reserve(Params->size());
580 for (TemplateParameterList::const_iterator P = Params->begin(),
581 PEnd = Params->end();
582 P != PEnd; ++P) {
583 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
584 CanonParams.push_back(
585 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000586 SourceLocation(),
587 SourceLocation(),
588 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000589 TTP->getIndex(), 0, false,
590 TTP->isParameterPack()));
591 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000592 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
593 QualType T = getCanonicalType(NTTP->getType());
594 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
595 NonTypeTemplateParmDecl *Param;
596 if (NTTP->isExpandedParameterPack()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000597 SmallVector<QualType, 2> ExpandedTypes;
598 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000599 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
600 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
601 ExpandedTInfos.push_back(
602 getTrivialTypeSourceInfo(ExpandedTypes.back()));
603 }
604
605 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000606 SourceLocation(),
607 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000608 NTTP->getDepth(),
609 NTTP->getPosition(), 0,
610 T,
611 TInfo,
612 ExpandedTypes.data(),
613 ExpandedTypes.size(),
614 ExpandedTInfos.data());
615 } else {
616 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000617 SourceLocation(),
618 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000619 NTTP->getDepth(),
620 NTTP->getPosition(), 0,
621 T,
622 NTTP->isParameterPack(),
623 TInfo);
624 }
625 CanonParams.push_back(Param);
626
627 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000628 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
629 cast<TemplateTemplateParmDecl>(*P)));
630 }
631
632 TemplateTemplateParmDecl *CanonTTP
633 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
634 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000635 TTP->getPosition(),
636 TTP->isParameterPack(),
637 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000638 TemplateParameterList::Create(*this, SourceLocation(),
639 SourceLocation(),
640 CanonParams.data(),
641 CanonParams.size(),
642 SourceLocation()));
643
644 // Get the new insert position for the node we care about.
645 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
646 assert(Canonical == 0 && "Shouldn't be in the map!");
647 (void)Canonical;
648
649 // Create the canonical template template parameter entry.
650 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
651 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
652 return CanonTTP;
653}
654
Charles Davis071cc7d2010-08-16 03:33:14 +0000655CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000656 if (!LangOpts.CPlusPlus) return 0;
657
John McCallb8b2c9d2013-01-25 22:30:49 +0000658 switch (T.getCXXABI().getKind()) {
659 case TargetCXXABI::GenericARM:
660 case TargetCXXABI::iOS:
John McCallee79a4c2010-08-21 22:46:04 +0000661 return CreateARMCXXABI(*this);
Tim Northoverc264e162013-01-31 12:13:10 +0000662 case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
John McCallb8b2c9d2013-01-25 22:30:49 +0000663 case TargetCXXABI::GenericItanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000664 return CreateItaniumCXXABI(*this);
John McCallb8b2c9d2013-01-25 22:30:49 +0000665 case TargetCXXABI::Microsoft:
Charles Davis20cf7172010-08-19 02:18:14 +0000666 return CreateMicrosoftCXXABI(*this);
667 }
David Blaikie7530c032012-01-17 06:56:22 +0000668 llvm_unreachable("Invalid CXXABI type!");
Charles Davis071cc7d2010-08-16 03:33:14 +0000669}
670
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000671static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000672 const LangOptions &LOpts) {
673 if (LOpts.FakeAddressSpaceMap) {
674 // The fake address space map must have a distinct entry for each
675 // language-specific address space.
676 static const unsigned FakeAddrSpaceMap[] = {
677 1, // opencl_global
678 2, // opencl_local
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +0000679 3, // opencl_constant
680 4, // cuda_device
681 5, // cuda_constant
682 6 // cuda_shared
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000683 };
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000684 return &FakeAddrSpaceMap;
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000685 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000686 return &T.getAddressSpaceMap();
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000687 }
688}
689
Douglas Gregor3e3cd932011-09-01 20:23:19 +0000690ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000691 const TargetInfo *t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000692 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000693 Builtin::Context &builtins,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000694 unsigned size_reserve,
695 bool DelayInitialization)
696 : FunctionProtoTypes(this_()),
697 TemplateSpecializationTypes(this_()),
698 DependentTemplateSpecializationTypes(this_()),
699 SubstTemplateTemplateParmPacks(this_()),
700 GlobalNestedNameSpecifier(0),
Nico Webercac18ad2013-06-20 21:44:55 +0000701 Int128Decl(0), UInt128Decl(0), Float128StubDecl(0),
Meador Ingec5613b22012-06-16 03:34:49 +0000702 BuiltinVaListDecl(0),
Douglas Gregora6ea10e2012-01-17 18:09:05 +0000703 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanian96171302012-08-30 18:49:41 +0000704 BOOLDecl(0),
Douglas Gregore97179c2011-09-08 01:46:34 +0000705 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000706 FILEDecl(0),
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +0000707 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
708 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
709 cudaConfigureCallDecl(0),
Douglas Gregore6649772011-12-03 00:30:27 +0000710 NullTypeSourceInfo(QualType()),
711 FirstLocalImport(), LastLocalImport(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000712 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor30c42402011-09-27 22:38:19 +0000713 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000714 Idents(idents), Selectors(sels),
715 BuiltinInfo(builtins),
716 DeclarationNames(*this),
Douglas Gregor30c42402011-09-27 22:38:19 +0000717 ExternalSource(0), Listener(0),
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000718 Comments(SM), CommentsLoaded(false),
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +0000719 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
Rafael Espindola42b78612013-05-29 19:51:12 +0000720 LastSDM(0, 0)
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000721{
Mike Stump1eb44332009-09-09 15:08:12 +0000722 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000723 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000724
725 if (!DelayInitialization) {
726 assert(t && "No target supplied for ASTContext initialization");
727 InitBuiltinTypes(*t);
728 }
Daniel Dunbare91593e2008-08-11 04:54:23 +0000729}
730
Reid Spencer5f016e22007-07-11 17:01:13 +0000731ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000732 // Release the DenseMaps associated with DeclContext objects.
733 // FIXME: Is this the ideal solution?
734 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000735
Manuel Klimekf0f353b2013-06-03 13:51:33 +0000736 // Call all of the deallocation functions on all of their targets.
737 for (DeallocationMap::const_iterator I = Deallocations.begin(),
738 E = Deallocations.end(); I != E; ++I)
739 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
740 (I->first)((I->second)[J]);
741
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000742 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000743 // because they can contain DenseMaps.
744 for (llvm::DenseMap<const ObjCContainerDecl*,
745 const ASTRecordLayout*>::iterator
746 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
747 // Increment in loop to prevent using deallocated memory.
748 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
749 R->Destroy(*this);
750
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000751 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
752 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
753 // Increment in loop to prevent using deallocated memory.
754 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
755 R->Destroy(*this);
756 }
Douglas Gregor63200642010-08-30 16:49:28 +0000757
758 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
759 AEnd = DeclAttrs.end();
760 A != AEnd; ++A)
761 A->second->~AttrVec();
762}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000763
Douglas Gregor00545312010-05-23 18:26:36 +0000764void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimekf0f353b2013-06-03 13:51:33 +0000765 Deallocations[Callback].push_back(Data);
Douglas Gregor00545312010-05-23 18:26:36 +0000766}
767
Mike Stump1eb44332009-09-09 15:08:12 +0000768void
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000769ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000770 ExternalSource.reset(Source.take());
771}
772
Reid Spencer5f016e22007-07-11 17:01:13 +0000773void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000774 llvm::errs() << "\n*** AST Context Stats:\n";
775 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000776
Douglas Gregordbe833d2009-05-26 14:40:08 +0000777 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000778#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000779#define ABSTRACT_TYPE(Name, Parent)
780#include "clang/AST/TypeNodes.def"
781 0 // Extra
782 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000783
Reid Spencer5f016e22007-07-11 17:01:13 +0000784 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
785 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000786 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000787 }
788
Douglas Gregordbe833d2009-05-26 14:40:08 +0000789 unsigned Idx = 0;
790 unsigned TotalBytes = 0;
791#define TYPE(Name, Parent) \
792 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000793 llvm::errs() << " " << counts[Idx] << " " << #Name \
794 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000795 TotalBytes += counts[Idx] * sizeof(Name##Type); \
796 ++Idx;
797#define ABSTRACT_TYPE(Name, Parent)
798#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000799
Chandler Carruthcd92a652011-07-04 05:32:14 +0000800 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
801
Douglas Gregor4923aa22010-07-02 20:37:36 +0000802 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000803 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
804 << NumImplicitDefaultConstructors
805 << " implicit default constructors created\n";
806 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
807 << NumImplicitCopyConstructors
808 << " implicit copy constructors created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000809 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000810 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
811 << NumImplicitMoveConstructors
812 << " implicit move constructors created\n";
813 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
814 << NumImplicitCopyAssignmentOperators
815 << " implicit copy assignment operators created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000816 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000817 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
818 << NumImplicitMoveAssignmentOperators
819 << " implicit move assignment operators created\n";
820 llvm::errs() << NumImplicitDestructorsDeclared << "/"
821 << NumImplicitDestructors
822 << " implicit destructors created\n";
823
Douglas Gregor2cf26342009-04-09 22:27:44 +0000824 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000825 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000826 ExternalSource->PrintStats();
827 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000828
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000829 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000830}
831
Douglas Gregor772eeae2011-08-12 06:49:56 +0000832TypedefDecl *ASTContext::getInt128Decl() const {
833 if (!Int128Decl) {
834 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
835 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
836 getTranslationUnitDecl(),
837 SourceLocation(),
838 SourceLocation(),
839 &Idents.get("__int128_t"),
840 TInfo);
841 }
842
843 return Int128Decl;
844}
845
846TypedefDecl *ASTContext::getUInt128Decl() const {
847 if (!UInt128Decl) {
848 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
849 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
850 getTranslationUnitDecl(),
851 SourceLocation(),
852 SourceLocation(),
853 &Idents.get("__uint128_t"),
854 TInfo);
855 }
856
857 return UInt128Decl;
858}
Reid Spencer5f016e22007-07-11 17:01:13 +0000859
Nico Webercac18ad2013-06-20 21:44:55 +0000860TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber3f7c1b12013-06-21 01:29:36 +0000861 assert(LangOpts.CPlusPlus && "should only be called for c++");
Nico Webercac18ad2013-06-20 21:44:55 +0000862 if (!Float128StubDecl) {
Nico Weber9b9bdba2013-06-20 23:30:30 +0000863 Float128StubDecl = CXXRecordDecl::Create(const_cast<ASTContext &>(*this),
864 TTK_Struct,
865 getTranslationUnitDecl(),
866 SourceLocation(),
867 SourceLocation(),
868 &Idents.get("__float128"));
Nico Webercac18ad2013-06-20 21:44:55 +0000869 }
870
871 return Float128StubDecl;
872}
873
John McCalle27ec8a2009-10-23 23:03:21 +0000874void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000875 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000876 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000877 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000878}
879
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000880void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
881 assert((!this->Target || this->Target == &Target) &&
882 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000883 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000884
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000885 this->Target = &Target;
886
887 ABI.reset(createCXXABI(Target));
888 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
889
Reid Spencer5f016e22007-07-11 17:01:13 +0000890 // C99 6.2.5p19.
891 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000892
Reid Spencer5f016e22007-07-11 17:01:13 +0000893 // C99 6.2.5p2.
894 InitBuiltinType(BoolTy, BuiltinType::Bool);
895 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000896 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000897 InitBuiltinType(CharTy, BuiltinType::Char_S);
898 else
899 InitBuiltinType(CharTy, BuiltinType::Char_U);
900 // C99 6.2.5p4.
901 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
902 InitBuiltinType(ShortTy, BuiltinType::Short);
903 InitBuiltinType(IntTy, BuiltinType::Int);
904 InitBuiltinType(LongTy, BuiltinType::Long);
905 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000906
Reid Spencer5f016e22007-07-11 17:01:13 +0000907 // C99 6.2.5p6.
908 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
909 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
910 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
911 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
912 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000913
Reid Spencer5f016e22007-07-11 17:01:13 +0000914 // C99 6.2.5p10.
915 InitBuiltinType(FloatTy, BuiltinType::Float);
916 InitBuiltinType(DoubleTy, BuiltinType::Double);
917 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000918
Chris Lattner2df9ced2009-04-30 02:43:43 +0000919 // GNU extension, 128-bit integers.
920 InitBuiltinType(Int128Ty, BuiltinType::Int128);
921 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
922
Hans Wennborg15f92ba2013-05-10 10:08:40 +0000923 // C++ 3.9.1p5
924 if (TargetInfo::isTypeSigned(Target.getWCharType()))
925 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
926 else // -fshort-wchar makes wchar_t be unsigned.
927 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
928 if (LangOpts.CPlusPlus && LangOpts.WChar)
929 WideCharTy = WCharTy;
930 else {
931 // C99 (or C++ using -fno-wchar).
932 WideCharTy = getFromTargetType(Target.getWCharType());
933 }
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000934
James Molloy392da482012-05-04 10:55:22 +0000935 WIntTy = getFromTargetType(Target.getWIntType());
936
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000937 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
938 InitBuiltinType(Char16Ty, BuiltinType::Char16);
939 else // C99
940 Char16Ty = getFromTargetType(Target.getChar16Type());
941
942 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
943 InitBuiltinType(Char32Ty, BuiltinType::Char32);
944 else // C99
945 Char32Ty = getFromTargetType(Target.getChar32Type());
946
Douglas Gregor898574e2008-12-05 23:32:09 +0000947 // Placeholder type for type-dependent expressions whose type is
948 // completely unknown. No code should ever check a type against
949 // DependentTy and users should never see it; however, it is here to
950 // help diagnose failures to properly check for type-dependent
951 // expressions.
952 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000953
John McCall2a984ca2010-10-12 00:20:44 +0000954 // Placeholder type for functions.
955 InitBuiltinType(OverloadTy, BuiltinType::Overload);
956
John McCall864c0412011-04-26 20:42:42 +0000957 // Placeholder type for bound members.
958 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
959
John McCall3c3b7f92011-10-25 17:37:35 +0000960 // Placeholder type for pseudo-objects.
961 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
962
John McCall1de4d4e2011-04-07 08:22:57 +0000963 // "any" type; useful for debugger-like clients.
964 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
965
John McCall0ddaeb92011-10-17 18:09:15 +0000966 // Placeholder type for unbridged ARC casts.
967 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
968
Eli Friedmana6c66ce2012-08-31 00:14:07 +0000969 // Placeholder type for builtin functions.
970 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
971
Reid Spencer5f016e22007-07-11 17:01:13 +0000972 // C99 6.2.5p11.
973 FloatComplexTy = getComplexType(FloatTy);
974 DoubleComplexTy = getComplexType(DoubleTy);
975 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000976
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000977 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000978 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
979 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000980 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeib13621d2012-12-18 14:38:23 +0000981
982 if (LangOpts.OpenCL) {
983 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
984 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
985 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
986 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
987 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
988 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000989
Guy Benyei21f18c42013-02-07 10:55:47 +0000990 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000991 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeib13621d2012-12-18 14:38:23 +0000992 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000993
994 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian93a49942012-04-16 21:03:30 +0000995 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
996 SignedCharTy : BoolTy);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000997
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000998 ObjCConstantStringType = QualType();
Fariborz Jahanianf7992132013-01-04 18:45:40 +0000999
1000 ObjCSuperType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001001
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001002 // void * type
1003 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001004
1005 // nullptr type (C++0x 2.14.7)
1006 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001007
1008 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1009 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingefb40e3f2012-07-01 15:57:25 +00001010
1011 // Builtin type used to help define __builtin_va_list.
1012 VaListTagTy = QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001013}
1014
David Blaikied6471f72011-09-25 23:23:43 +00001015DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001016 return SourceMgr.getDiagnostics();
1017}
1018
Douglas Gregor63200642010-08-30 16:49:28 +00001019AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1020 AttrVec *&Result = DeclAttrs[D];
1021 if (!Result) {
1022 void *Mem = Allocate(sizeof(AttrVec));
1023 Result = new (Mem) AttrVec;
1024 }
1025
1026 return *Result;
1027}
1028
1029/// \brief Erase the attributes corresponding to the given declaration.
1030void ASTContext::eraseDeclAttrs(const Decl *D) {
1031 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1032 if (Pos != DeclAttrs.end()) {
1033 Pos->second->~AttrVec();
1034 DeclAttrs.erase(Pos);
1035 }
1036}
1037
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001038MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +00001039ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001040 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +00001041 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +00001042 = InstantiatedFromStaticDataMember.find(Var);
1043 if (Pos == InstantiatedFromStaticDataMember.end())
1044 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001045
Douglas Gregor7caa6822009-07-24 20:34:43 +00001046 return Pos->second;
1047}
1048
Mike Stump1eb44332009-09-09 15:08:12 +00001049void
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001050ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +00001051 TemplateSpecializationKind TSK,
1052 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001053 assert(Inst->isStaticDataMember() && "Not a static data member");
1054 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1055 assert(!InstantiatedFromStaticDataMember[Inst] &&
1056 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001057 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +00001058 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +00001059}
1060
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001061FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1062 const FunctionDecl *FD){
1063 assert(FD && "Specialization is 0");
1064 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +00001065 = ClassScopeSpecializationPattern.find(FD);
1066 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001067 return 0;
1068
1069 return Pos->second;
1070}
1071
1072void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1073 FunctionDecl *Pattern) {
1074 assert(FD && "Specialization is 0");
1075 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +00001076 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001077}
1078
John McCall7ba107a2009-11-18 02:36:19 +00001079NamedDecl *
John McCalled976492009-12-04 22:46:56 +00001080ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +00001081 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +00001082 = InstantiatedFromUsingDecl.find(UUD);
1083 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +00001084 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001085
Anders Carlsson0d8df782009-08-29 19:37:28 +00001086 return Pos->second;
1087}
1088
1089void
John McCalled976492009-12-04 22:46:56 +00001090ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1091 assert((isa<UsingDecl>(Pattern) ||
1092 isa<UnresolvedUsingValueDecl>(Pattern) ||
1093 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1094 "pattern decl is not a using decl");
1095 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1096 InstantiatedFromUsingDecl[Inst] = Pattern;
1097}
1098
1099UsingShadowDecl *
1100ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1101 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1102 = InstantiatedFromUsingShadowDecl.find(Inst);
1103 if (Pos == InstantiatedFromUsingShadowDecl.end())
1104 return 0;
1105
1106 return Pos->second;
1107}
1108
1109void
1110ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1111 UsingShadowDecl *Pattern) {
1112 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1113 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00001114}
1115
Anders Carlssond8b285f2009-09-01 04:26:58 +00001116FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1117 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1118 = InstantiatedFromUnnamedFieldDecl.find(Field);
1119 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1120 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001121
Anders Carlssond8b285f2009-09-01 04:26:58 +00001122 return Pos->second;
1123}
1124
1125void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1126 FieldDecl *Tmpl) {
1127 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1128 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1129 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1130 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +00001131
Anders Carlssond8b285f2009-09-01 04:26:58 +00001132 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1133}
1134
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001135ASTContext::overridden_cxx_method_iterator
1136ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1137 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001138 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001139 if (Pos == OverriddenMethods.end())
1140 return 0;
1141
1142 return Pos->second.begin();
1143}
1144
1145ASTContext::overridden_cxx_method_iterator
1146ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1147 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001148 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001149 if (Pos == OverriddenMethods.end())
1150 return 0;
1151
1152 return Pos->second.end();
1153}
1154
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001155unsigned
1156ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1157 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001158 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001159 if (Pos == OverriddenMethods.end())
1160 return 0;
1161
1162 return Pos->second.size();
1163}
1164
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001165void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1166 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001167 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001168 OverriddenMethods[Method].push_back(Overridden);
1169}
1170
Dmitri Gribenko1e905da2012-11-03 14:24:57 +00001171void ASTContext::getOverriddenMethods(
1172 const NamedDecl *D,
1173 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001174 assert(D);
1175
1176 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis685d1042013-04-17 00:09:03 +00001177 Overridden.append(overridden_methods_begin(CXXMethod),
1178 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001179 return;
1180 }
1181
1182 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1183 if (!Method)
1184 return;
1185
Argyrios Kyrtzidis740ae672012-10-09 18:19:01 +00001186 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1187 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisbc0a2bb2012-10-09 20:08:43 +00001188 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001189}
1190
Douglas Gregore6649772011-12-03 00:30:27 +00001191void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1192 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1193 assert(!Import->isFromASTFile() && "Non-local import declaration");
1194 if (!FirstLocalImport) {
1195 FirstLocalImport = Import;
1196 LastLocalImport = Import;
1197 return;
1198 }
1199
1200 LastLocalImport->NextLocalImport = Import;
1201 LastLocalImport = Import;
1202}
1203
Chris Lattner464175b2007-07-18 17:52:12 +00001204//===----------------------------------------------------------------------===//
1205// Type Sizing and Analysis
1206//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +00001207
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001208/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1209/// scalar floating point type.
1210const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +00001211 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001212 assert(BT && "Not a floating point type!");
1213 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001214 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001215 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001216 case BuiltinType::Float: return Target->getFloatFormat();
1217 case BuiltinType::Double: return Target->getDoubleFormat();
1218 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001219 }
1220}
1221
Ken Dyck8b752f12010-01-27 17:10:57 +00001222/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +00001223/// specified decl. Note that bitfields do not have a valid alignment, so
1224/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +00001225/// If @p RefAsPointee, references are treated like their underlying type
1226/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +00001227CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001228 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +00001229
John McCall4081a5c2010-10-08 18:24:19 +00001230 bool UseAlignAttrOnly = false;
1231 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1232 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +00001233
John McCall4081a5c2010-10-08 18:24:19 +00001234 // __attribute__((aligned)) can increase or decrease alignment
1235 // *except* on a struct or struct member, where it only increases
1236 // alignment unless 'packed' is also specified.
1237 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +00001238 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +00001239 // ignore that possibility; Sema should diagnose it.
1240 if (isa<FieldDecl>(D)) {
1241 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1242 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1243 } else {
1244 UseAlignAttrOnly = true;
1245 }
1246 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +00001247 else if (isa<FieldDecl>(D))
1248 UseAlignAttrOnly =
1249 D->hasAttr<PackedAttr>() ||
1250 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +00001251
John McCallba4f5d52011-01-20 07:57:12 +00001252 // If we're using the align attribute only, just ignore everything
1253 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +00001254 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +00001255 // do nothing
1256
John McCall4081a5c2010-10-08 18:24:19 +00001257 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001258 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001259 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001260 if (RefAsPointee)
1261 T = RT->getPointeeType();
1262 else
1263 T = getPointerType(RT->getPointeeType());
1264 }
1265 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +00001266 // Adjust alignments of declarations with array type by the
1267 // large-array alignment on the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001268 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +00001269 const ArrayType *arrayType;
1270 if (MinWidth && (arrayType = getAsArrayType(T))) {
1271 if (isa<VariableArrayType>(arrayType))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001272 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall3b657512011-01-19 10:06:00 +00001273 else if (isa<ConstantArrayType>(arrayType) &&
1274 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001275 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +00001276
John McCall3b657512011-01-19 10:06:00 +00001277 // Walk through any array types while we're at it.
1278 T = getBaseElementType(arrayType);
1279 }
Chad Rosier9f1210c2011-07-26 07:03:04 +00001280 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigand6b203512013-05-06 16:23:57 +00001281 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1282 if (VD->hasGlobalStorage())
1283 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1284 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001285 }
John McCallba4f5d52011-01-20 07:57:12 +00001286
1287 // Fields can be subject to extra alignment constraints, like if
1288 // the field is packed, the struct is packed, or the struct has a
1289 // a max-field-alignment constraint (#pragma pack). So calculate
1290 // the actual alignment of the field within the struct, and then
1291 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay147fab92013-06-25 22:19:15 +00001292 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1293 const RecordDecl *Parent = Field->getParent();
1294 // We can only produce a sensible answer if the record is valid.
1295 if (!Parent->isInvalidDecl()) {
1296 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCallba4f5d52011-01-20 07:57:12 +00001297
Matt Beaumont-Gay147fab92013-06-25 22:19:15 +00001298 // Start with the record's overall alignment.
1299 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +00001300
Matt Beaumont-Gay147fab92013-06-25 22:19:15 +00001301 // Use the GCD of that and the offset within the record.
1302 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1303 if (Offset > 0) {
1304 // Alignment is always a power of 2, so the GCD will be a power of 2,
1305 // which means we get to do this crazy thing instead of Euclid's.
1306 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1307 if (LowBitOfOffset < FieldAlign)
1308 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1309 }
1310
1311 Align = std::min(Align, FieldAlign);
John McCallba4f5d52011-01-20 07:57:12 +00001312 }
Charles Davis05f62472010-02-23 04:52:00 +00001313 }
Chris Lattneraf707ab2009-01-24 21:53:27 +00001314 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001315
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001316 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001317}
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001318
John McCall929bbfb2012-08-21 04:10:00 +00001319// getTypeInfoDataSizeInChars - Return the size of a type, in
1320// chars. If the type is a record, its data size is returned. This is
1321// the size of the memcpy that's performed when assigning this type
1322// using a trivial copy/move assignment operator.
1323std::pair<CharUnits, CharUnits>
1324ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1325 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1326
1327 // In C++, objects can sometimes be allocated into the tail padding
1328 // of a base-class subobject. We decide whether that's possible
1329 // during class layout, so here we can just trust the layout results.
1330 if (getLangOpts().CPlusPlus) {
1331 if (const RecordType *RT = T->getAs<RecordType>()) {
1332 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1333 sizeAndAlign.first = layout.getDataSize();
1334 }
1335 }
1336
1337 return sizeAndAlign;
1338}
1339
Richard Trieu910f17e2013-05-14 21:59:17 +00001340/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1341/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1342std::pair<CharUnits, CharUnits>
1343static getConstantArrayInfoInChars(const ASTContext &Context,
1344 const ConstantArrayType *CAT) {
1345 std::pair<CharUnits, CharUnits> EltInfo =
1346 Context.getTypeInfoInChars(CAT->getElementType());
1347 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieu1069b732013-05-14 23:41:50 +00001348 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1349 (uint64_t)(-1)/Size) &&
Richard Trieu910f17e2013-05-14 21:59:17 +00001350 "Overflow in array type char size evaluation");
1351 uint64_t Width = EltInfo.first.getQuantity() * Size;
1352 unsigned Align = EltInfo.second.getQuantity();
1353 Width = llvm::RoundUpToAlignment(Width, Align);
1354 return std::make_pair(CharUnits::fromQuantity(Width),
1355 CharUnits::fromQuantity(Align));
1356}
1357
John McCallea1471e2010-05-20 01:18:31 +00001358std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001359ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001360 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1361 return getConstantArrayInfoInChars(*this, CAT);
John McCallea1471e2010-05-20 01:18:31 +00001362 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001363 return std::make_pair(toCharUnitsFromBits(Info.first),
1364 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +00001365}
1366
1367std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001368ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +00001369 return getTypeInfoInChars(T.getTypePtr());
1370}
1371
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001372std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1373 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1374 if (it != MemoizedTypeInfo.end())
1375 return it->second;
1376
1377 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1378 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1379 return Info;
1380}
1381
1382/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1383/// method does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +00001384///
1385/// FIXME: Pointers into different addr spaces could have different sizes and
1386/// alignment requirements: getPointerInfo should take an AddrSpace, this
1387/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001388std::pair<uint64_t, unsigned>
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001389ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +00001390 uint64_t Width=0;
1391 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +00001392 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001393#define TYPE(Class, Base)
1394#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +00001395#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +00001396#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikiedc809782013-07-13 21:08:03 +00001397#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1398 case Type::Class: \
1399 assert(!T->isDependentType() && "should not see dependent types here"); \
1400 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregor72564e72009-02-26 23:50:07 +00001401#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +00001402 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +00001403
Chris Lattner692233e2007-07-13 22:27:08 +00001404 case Type::FunctionNoProto:
1405 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +00001406 // GCC extension: alignof(function) = 32 bits
1407 Width = 0;
1408 Align = 32;
1409 break;
1410
Douglas Gregor72564e72009-02-26 23:50:07 +00001411 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +00001412 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +00001413 Width = 0;
1414 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1415 break;
1416
Steve Narofffb22d962007-08-30 01:06:46 +00001417 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001418 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001419
Chris Lattner98be4942008-03-05 18:54:05 +00001420 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001421 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001422 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1423 "Overflow in array type bit size evaluation");
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001424 Width = EltInfo.first*Size;
Chris Lattner030d8842007-07-19 22:06:24 +00001425 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +00001426 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +00001427 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +00001428 }
Nate Begeman213541a2008-04-18 23:10:10 +00001429 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +00001430 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001431 const VectorType *VT = cast<VectorType>(T);
1432 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1433 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +00001434 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001435 // If the alignment is not a power of 2, round up to the next power of 2.
1436 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +00001437 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001438 Align = llvm::NextPowerOf2(Align);
1439 Width = llvm::RoundUpToAlignment(Width, Align);
1440 }
Chad Rosierf9e9af72012-07-13 23:57:43 +00001441 // Adjust the alignment based on the target max.
1442 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1443 if (TargetVectorAlign && TargetVectorAlign < Align)
1444 Align = TargetVectorAlign;
Chris Lattner030d8842007-07-19 22:06:24 +00001445 break;
1446 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001447
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001448 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +00001449 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001450 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001451 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +00001452 // GCC extension: alignof(void) = 8 bits.
1453 Width = 0;
1454 Align = 8;
1455 break;
1456
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001457 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001458 Width = Target->getBoolWidth();
1459 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001460 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001461 case BuiltinType::Char_S:
1462 case BuiltinType::Char_U:
1463 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001464 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001465 Width = Target->getCharWidth();
1466 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001467 break;
Chris Lattner3f59c972010-12-25 23:25:43 +00001468 case BuiltinType::WChar_S:
1469 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001470 Width = Target->getWCharWidth();
1471 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001472 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001473 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001474 Width = Target->getChar16Width();
1475 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001476 break;
1477 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001478 Width = Target->getChar32Width();
1479 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001480 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001481 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001482 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001483 Width = Target->getShortWidth();
1484 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001485 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001486 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001487 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001488 Width = Target->getIntWidth();
1489 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001490 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001491 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001492 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001493 Width = Target->getLongWidth();
1494 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001495 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001496 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001497 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001498 Width = Target->getLongLongWidth();
1499 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001500 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +00001501 case BuiltinType::Int128:
1502 case BuiltinType::UInt128:
1503 Width = 128;
1504 Align = 128; // int128_t is 128-bit aligned on all targets.
1505 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001506 case BuiltinType::Half:
1507 Width = Target->getHalfWidth();
1508 Align = Target->getHalfAlign();
1509 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001510 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001511 Width = Target->getFloatWidth();
1512 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001513 break;
1514 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001515 Width = Target->getDoubleWidth();
1516 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001517 break;
1518 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001519 Width = Target->getLongDoubleWidth();
1520 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001521 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001522 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001523 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1524 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +00001525 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001526 case BuiltinType::ObjCId:
1527 case BuiltinType::ObjCClass:
1528 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001529 Width = Target->getPointerWidth(0);
1530 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001531 break;
Guy Benyei21f18c42013-02-07 10:55:47 +00001532 case BuiltinType::OCLSampler:
1533 // Samplers are modeled as integers.
1534 Width = Target->getIntWidth();
1535 Align = Target->getIntAlign();
1536 break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00001537 case BuiltinType::OCLEvent:
Guy Benyeib13621d2012-12-18 14:38:23 +00001538 case BuiltinType::OCLImage1d:
1539 case BuiltinType::OCLImage1dArray:
1540 case BuiltinType::OCLImage1dBuffer:
1541 case BuiltinType::OCLImage2d:
1542 case BuiltinType::OCLImage2dArray:
1543 case BuiltinType::OCLImage3d:
1544 // Currently these types are pointers to opaque types.
1545 Width = Target->getPointerWidth(0);
1546 Align = Target->getPointerAlign(0);
1547 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001548 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +00001549 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001550 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001551 Width = Target->getPointerWidth(0);
1552 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001553 break;
Steve Naroff485eeff2008-09-24 15:05:44 +00001554 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001555 unsigned AS = getTargetAddressSpace(
1556 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001557 Width = Target->getPointerWidth(AS);
1558 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +00001559 break;
1560 }
Sebastian Redl5d484e82009-11-23 17:18:46 +00001561 case Type::LValueReference:
1562 case Type::RValueReference: {
1563 // alignof and sizeof should never enter this code path here, so we go
1564 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001565 unsigned AS = getTargetAddressSpace(
1566 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001567 Width = Target->getPointerWidth(AS);
1568 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +00001569 break;
1570 }
Chris Lattnerf72a4432008-03-08 08:34:58 +00001571 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001572 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001573 Width = Target->getPointerWidth(AS);
1574 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +00001575 break;
1576 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00001577 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +00001578 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Reid Kleckner84e9ab42013-03-28 20:02:56 +00001579 llvm::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001580 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001581 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001582 case Type::Complex: {
1583 // Complex types have the same alignment as their elements, but twice the
1584 // size.
Mike Stump1eb44332009-09-09 15:08:12 +00001585 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +00001586 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001587 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +00001588 Align = EltInfo.second;
1589 break;
1590 }
John McCallc12c5bb2010-05-15 11:32:37 +00001591 case Type::ObjCObject:
1592 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner12df2462013-06-24 17:51:48 +00001593 case Type::Decayed:
1594 return getTypeInfo(cast<DecayedType>(T)->getDecayedType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +00001595 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001596 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +00001597 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001598 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001599 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +00001600 break;
1601 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001602 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001603 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001604 const TagType *TT = cast<TagType>(T);
1605
1606 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001607 Width = 8;
1608 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001609 break;
1610 }
Mike Stump1eb44332009-09-09 15:08:12 +00001611
Daniel Dunbar1d751182008-11-08 05:48:37 +00001612 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001613 return getTypeInfo(ET->getDecl()->getIntegerType());
1614
Daniel Dunbar1d751182008-11-08 05:48:37 +00001615 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001616 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001617 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001618 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001619 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001620 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001621
Chris Lattner9fcfe922009-10-22 05:17:15 +00001622 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001623 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1624 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001625
Richard Smith34b41d92011-02-20 03:19:35 +00001626 case Type::Auto: {
1627 const AutoType *A = cast<AutoType>(T);
Richard Smithdc7a4f52013-04-30 13:56:41 +00001628 assert(!A->getDeducedType().isNull() &&
1629 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001630 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001631 }
1632
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001633 case Type::Paren:
1634 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1635
Douglas Gregor18857642009-04-30 17:32:17 +00001636 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001637 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001638 std::pair<uint64_t, unsigned> Info
1639 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001640 // If the typedef has an aligned attribute on it, it overrides any computed
1641 // alignment we have. This violates the GCC documentation (which says that
1642 // attribute(aligned) can only round up) but matches its implementation.
1643 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1644 Align = AttrAlign;
1645 else
1646 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001647 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001648 break;
Chris Lattner71763312008-04-06 22:05:18 +00001649 }
Douglas Gregor18857642009-04-30 17:32:17 +00001650
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001651 case Type::Elaborated:
1652 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001653
John McCall9d156a72011-01-06 01:58:22 +00001654 case Type::Attributed:
1655 return getTypeInfo(
1656 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1657
Eli Friedmanb001de72011-10-06 23:00:33 +00001658 case Type::Atomic: {
John McCall9eda3ab2013-03-07 21:37:17 +00001659 // Start with the base type information.
Eli Friedman2be46072011-10-14 20:59:01 +00001660 std::pair<uint64_t, unsigned> Info
1661 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1662 Width = Info.first;
1663 Align = Info.second;
John McCall9eda3ab2013-03-07 21:37:17 +00001664
1665 // If the size of the type doesn't exceed the platform's max
1666 // atomic promotion width, make the size and alignment more
1667 // favorable to atomic operations:
1668 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1669 // Round the size up to a power of 2.
1670 if (!llvm::isPowerOf2_64(Width))
1671 Width = llvm::NextPowerOf2(Width);
1672
1673 // Set the alignment equal to the size.
Eli Friedman2be46072011-10-14 20:59:01 +00001674 Align = static_cast<unsigned>(Width);
1675 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001676 }
1677
Douglas Gregor18857642009-04-30 17:32:17 +00001678 }
Mike Stump1eb44332009-09-09 15:08:12 +00001679
Eli Friedman2be46072011-10-14 20:59:01 +00001680 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001681 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001682}
1683
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001684/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1685CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1686 return CharUnits::fromQuantity(BitSize / getCharWidth());
1687}
1688
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001689/// toBits - Convert a size in characters to a size in characters.
1690int64_t ASTContext::toBits(CharUnits CharSize) const {
1691 return CharSize.getQuantity() * getCharWidth();
1692}
1693
Ken Dyckbdc601b2009-12-22 14:23:30 +00001694/// getTypeSizeInChars - Return the size of the specified type, in characters.
1695/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001696CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001697 return getTypeInfoInChars(T).first;
Ken Dyckbdc601b2009-12-22 14:23:30 +00001698}
Jay Foad4ba2a172011-01-12 09:06:06 +00001699CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001700 return getTypeInfoInChars(T).first;
Ken Dyckbdc601b2009-12-22 14:23:30 +00001701}
1702
Ken Dyck16e20cc2010-01-26 17:25:18 +00001703/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001704/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001705CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001706 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001707}
Jay Foad4ba2a172011-01-12 09:06:06 +00001708CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001709 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001710}
1711
Chris Lattner34ebde42009-01-27 18:08:34 +00001712/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1713/// type for the current target in bits. This can be different than the ABI
1714/// alignment in cases where it is beneficial for performance to overalign
1715/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001716unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001717 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001718
1719 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001720 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001721 T = CT->getElementType().getTypePtr();
1722 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosiercde7a1d2012-03-21 20:20:47 +00001723 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1724 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman1eed6022009-05-25 21:27:19 +00001725 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1726
Chris Lattner34ebde42009-01-27 18:08:34 +00001727 return ABIAlign;
1728}
1729
Ulrich Weigand6b203512013-05-06 16:23:57 +00001730/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1731/// to a global variable of the specified type.
1732unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1733 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1734}
1735
1736/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1737/// should be given to a global variable of the specified type.
1738CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1739 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1740}
1741
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001742/// DeepCollectObjCIvars -
1743/// This routine first collects all declared, but not synthesized, ivars in
1744/// super class and then collects all ivars, including those synthesized for
1745/// current class. This routine is used for implementation of current class
1746/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001747///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001748void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1749 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001750 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001751 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1752 DeepCollectObjCIvars(SuperClass, false, Ivars);
1753 if (!leafClass) {
1754 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1755 E = OI->ivar_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001756 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001757 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001758 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001759 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001760 Iv= Iv->getNextIvar())
1761 Ivars.push_back(Iv);
1762 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001763}
1764
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001765/// CollectInheritedProtocols - Collect all protocols in current class and
1766/// those inherited by it.
1767void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001768 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001769 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001770 // We can use protocol_iterator here instead of
1771 // all_referenced_protocol_iterator since we are walking all categories.
1772 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1773 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001774 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001775 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001776 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001777 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001778 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001779 CollectInheritedProtocols(*P, Protocols);
1780 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001781 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001782
1783 // Categories of this Interface.
Douglas Gregord3297242013-01-16 23:00:23 +00001784 for (ObjCInterfaceDecl::visible_categories_iterator
1785 Cat = OI->visible_categories_begin(),
1786 CatEnd = OI->visible_categories_end();
1787 Cat != CatEnd; ++Cat) {
1788 CollectInheritedProtocols(*Cat, Protocols);
1789 }
1790
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001791 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1792 while (SD) {
1793 CollectInheritedProtocols(SD, Protocols);
1794 SD = SD->getSuperClass();
1795 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001796 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001797 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001798 PE = OC->protocol_end(); P != PE; ++P) {
1799 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001800 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001801 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1802 PE = Proto->protocol_end(); P != PE; ++P)
1803 CollectInheritedProtocols(*P, Protocols);
1804 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001805 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001806 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1807 PE = OP->protocol_end(); P != PE; ++P) {
1808 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(),
1811 PE = Proto->protocol_end(); P != PE; ++P)
1812 CollectInheritedProtocols(*P, Protocols);
1813 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001814 }
1815}
1816
Jay Foad4ba2a172011-01-12 09:06:06 +00001817unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001818 unsigned count = 0;
1819 // Count ivars declared in class extension.
Douglas Gregord3297242013-01-16 23:00:23 +00001820 for (ObjCInterfaceDecl::known_extensions_iterator
1821 Ext = OI->known_extensions_begin(),
1822 ExtEnd = OI->known_extensions_end();
1823 Ext != ExtEnd; ++Ext) {
1824 count += Ext->ivar_size();
1825 }
1826
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001827 // Count ivar defined in this class's implementation. This
1828 // includes synthesized ivars.
1829 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001830 count += ImplDecl->ivar_size();
1831
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001832 return count;
1833}
1834
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +00001835bool ASTContext::isSentinelNullExpr(const Expr *E) {
1836 if (!E)
1837 return false;
1838
1839 // nullptr_t is always treated as null.
1840 if (E->getType()->isNullPtrType()) return true;
1841
1842 if (E->getType()->isAnyPointerType() &&
1843 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1844 Expr::NPC_ValueDependentIsNull))
1845 return true;
1846
1847 // Unfortunately, __null has type 'int'.
1848 if (isa<GNUNullExpr>(E)) return true;
1849
1850 return false;
1851}
1852
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001853/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1854ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1855 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1856 I = ObjCImpls.find(D);
1857 if (I != ObjCImpls.end())
1858 return cast<ObjCImplementationDecl>(I->second);
1859 return 0;
1860}
1861/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1862ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1863 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1864 I = ObjCImpls.find(D);
1865 if (I != ObjCImpls.end())
1866 return cast<ObjCCategoryImplDecl>(I->second);
1867 return 0;
1868}
1869
1870/// \brief Set the implementation of ObjCInterfaceDecl.
1871void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1872 ObjCImplementationDecl *ImplD) {
1873 assert(IFaceD && ImplD && "Passed null params");
1874 ObjCImpls[IFaceD] = ImplD;
1875}
1876/// \brief Set the implementation of ObjCCategoryDecl.
1877void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1878 ObjCCategoryImplDecl *ImplD) {
1879 assert(CatD && ImplD && "Passed null params");
1880 ObjCImpls[CatD] = ImplD;
1881}
1882
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001883const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1884 const NamedDecl *ND) const {
1885 if (const ObjCInterfaceDecl *ID =
1886 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001887 return ID;
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001888 if (const ObjCCategoryDecl *CD =
1889 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001890 return CD->getClassInterface();
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001891 if (const ObjCImplDecl *IMD =
1892 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001893 return IMD->getClassInterface();
1894
1895 return 0;
1896}
1897
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001898/// \brief Get the copy initialization expression of VarDecl,or NULL if
1899/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001900Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001901 assert(VD && "Passed null params");
1902 assert(VD->hasAttr<BlocksAttr>() &&
1903 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001904 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001905 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001906 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1907}
1908
1909/// \brief Set the copy inialization expression of a block var decl.
1910void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1911 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001912 assert(VD->hasAttr<BlocksAttr>() &&
1913 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001914 BlockVarCopyInits[VD] = Init;
1915}
1916
John McCalla93c9342009-12-07 02:54:59 +00001917TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001918 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001919 if (!DataSize)
1920 DataSize = TypeLoc::getFullDataSizeForType(T);
1921 else
1922 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001923 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001924
John McCalla93c9342009-12-07 02:54:59 +00001925 TypeSourceInfo *TInfo =
1926 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1927 new (TInfo) TypeSourceInfo(T);
1928 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001929}
1930
John McCalla93c9342009-12-07 02:54:59 +00001931TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001932 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001933 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001934 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001935 return DI;
1936}
1937
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001938const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001939ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001940 return getObjCLayout(D, 0);
1941}
1942
1943const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001944ASTContext::getASTObjCImplementationLayout(
1945 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001946 return getObjCLayout(D->getClassInterface(), D);
1947}
1948
Chris Lattnera7674d82007-07-13 22:13:22 +00001949//===----------------------------------------------------------------------===//
1950// Type creation/memoization methods
1951//===----------------------------------------------------------------------===//
1952
Jay Foad4ba2a172011-01-12 09:06:06 +00001953QualType
John McCall3b657512011-01-19 10:06:00 +00001954ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1955 unsigned fastQuals = quals.getFastQualifiers();
1956 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001957
1958 // Check if we've already instantiated this type.
1959 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001960 ExtQuals::Profile(ID, baseType, quals);
1961 void *insertPos = 0;
1962 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1963 assert(eq->getQualifiers() == quals);
1964 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001965 }
1966
John McCall3b657512011-01-19 10:06:00 +00001967 // If the base type is not canonical, make the appropriate canonical type.
1968 QualType canon;
1969 if (!baseType->isCanonicalUnqualified()) {
1970 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall200fa532012-02-08 00:46:36 +00001971 canonSplit.Quals.addConsistentQualifiers(quals);
1972 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00001973
1974 // Re-find the insert position.
1975 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1976 }
1977
1978 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1979 ExtQualNodes.InsertNode(eq, insertPos);
1980 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001981}
1982
Jay Foad4ba2a172011-01-12 09:06:06 +00001983QualType
1984ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001985 QualType CanT = getCanonicalType(T);
1986 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001987 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001988
John McCall0953e762009-09-24 19:53:00 +00001989 // If we are composing extended qualifiers together, merge together
1990 // into one ExtQuals node.
1991 QualifierCollector Quals;
1992 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001993
John McCall0953e762009-09-24 19:53:00 +00001994 // If this type already has an address space specified, it cannot get
1995 // another one.
1996 assert(!Quals.hasAddressSpace() &&
1997 "Type cannot be in multiple addr spaces!");
1998 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001999
John McCall0953e762009-09-24 19:53:00 +00002000 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00002001}
2002
Chris Lattnerb7d25532009-02-18 22:53:11 +00002003QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00002004 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002005 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00002006 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002007 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00002008
John McCall7f040a92010-12-24 02:08:15 +00002009 if (const PointerType *ptr = T->getAs<PointerType>()) {
2010 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00002011 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00002012 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2013 return getPointerType(ResultType);
2014 }
2015 }
Mike Stump1eb44332009-09-09 15:08:12 +00002016
John McCall0953e762009-09-24 19:53:00 +00002017 // If we are composing extended qualifiers together, merge together
2018 // into one ExtQuals node.
2019 QualifierCollector Quals;
2020 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002021
John McCall0953e762009-09-24 19:53:00 +00002022 // If this type already has an ObjCGC specified, it cannot get
2023 // another one.
2024 assert(!Quals.hasObjCGCAttr() &&
2025 "Type cannot have multiple ObjCGCs!");
2026 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00002027
John McCall0953e762009-09-24 19:53:00 +00002028 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002029}
Chris Lattnera7674d82007-07-13 22:13:22 +00002030
John McCalle6a365d2010-12-19 02:44:49 +00002031const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2032 FunctionType::ExtInfo Info) {
2033 if (T->getExtInfo() == Info)
2034 return T;
2035
2036 QualType Result;
2037 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2038 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
2039 } else {
2040 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2041 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2042 EPI.ExtInfo = Info;
Reid Kleckner0567a792013-06-10 20:51:09 +00002043 Result = getFunctionType(FPT->getResultType(), FPT->getArgTypes(), EPI);
John McCalle6a365d2010-12-19 02:44:49 +00002044 }
2045
2046 return cast<FunctionType>(Result.getTypePtr());
2047}
2048
Richard Smith60e141e2013-05-04 07:00:32 +00002049void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2050 QualType ResultType) {
Richard Smith9dadfab2013-05-11 05:45:24 +00002051 FD = FD->getMostRecentDecl();
2052 while (true) {
Richard Smith60e141e2013-05-04 07:00:32 +00002053 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2054 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2055 FD->setType(getFunctionType(ResultType, FPT->getArgTypes(), EPI));
Richard Smith9dadfab2013-05-11 05:45:24 +00002056 if (FunctionDecl *Next = FD->getPreviousDecl())
2057 FD = Next;
2058 else
2059 break;
Richard Smith60e141e2013-05-04 07:00:32 +00002060 }
Richard Smith9dadfab2013-05-11 05:45:24 +00002061 if (ASTMutationListener *L = getASTMutationListener())
2062 L->DeducedReturnType(FD, ResultType);
Richard Smith60e141e2013-05-04 07:00:32 +00002063}
2064
Reid Spencer5f016e22007-07-11 17:01:13 +00002065/// getComplexType - Return the uniqued reference to the type for a complex
2066/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002067QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002068 // Unique pointers, to guarantee there is only one pointer of a particular
2069 // structure.
2070 llvm::FoldingSetNodeID ID;
2071 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002072
Reid Spencer5f016e22007-07-11 17:01:13 +00002073 void *InsertPos = 0;
2074 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2075 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002076
Reid Spencer5f016e22007-07-11 17:01:13 +00002077 // If the pointee type isn't canonical, this won't be a canonical type either,
2078 // so fill in the canonical type field.
2079 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002080 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002081 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002082
Reid Spencer5f016e22007-07-11 17:01:13 +00002083 // Get the new insert position for the node we care about.
2084 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002085 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002086 }
John McCall6b304a02009-09-24 23:30:46 +00002087 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002088 Types.push_back(New);
2089 ComplexTypes.InsertNode(New, InsertPos);
2090 return QualType(New, 0);
2091}
2092
Reid Spencer5f016e22007-07-11 17:01:13 +00002093/// getPointerType - Return the uniqued reference to the type for a pointer to
2094/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002095QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002096 // Unique pointers, to guarantee there is only one pointer of a particular
2097 // structure.
2098 llvm::FoldingSetNodeID ID;
2099 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002100
Reid Spencer5f016e22007-07-11 17:01:13 +00002101 void *InsertPos = 0;
2102 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2103 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002104
Reid Spencer5f016e22007-07-11 17:01:13 +00002105 // If the pointee type isn't canonical, this won't be a canonical type either,
2106 // so fill in the canonical type field.
2107 QualType Canonical;
Bob Wilsonc90cc932013-03-15 17:12:43 +00002108 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002109 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002110
Bob Wilsonc90cc932013-03-15 17:12:43 +00002111 // Get the new insert position for the node we care about.
2112 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2113 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2114 }
John McCall6b304a02009-09-24 23:30:46 +00002115 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002116 Types.push_back(New);
2117 PointerTypes.InsertNode(New, InsertPos);
2118 return QualType(New, 0);
2119}
2120
Reid Kleckner12df2462013-06-24 17:51:48 +00002121QualType ASTContext::getDecayedType(QualType T) const {
2122 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2123
2124 llvm::FoldingSetNodeID ID;
2125 DecayedType::Profile(ID, T);
2126 void *InsertPos = 0;
2127 if (DecayedType *DT = DecayedTypes.FindNodeOrInsertPos(ID, InsertPos))
2128 return QualType(DT, 0);
2129
2130 QualType Decayed;
2131
2132 // C99 6.7.5.3p7:
2133 // A declaration of a parameter as "array of type" shall be
2134 // adjusted to "qualified pointer to type", where the type
2135 // qualifiers (if any) are those specified within the [ and ] of
2136 // the array type derivation.
2137 if (T->isArrayType())
2138 Decayed = getArrayDecayedType(T);
2139
2140 // C99 6.7.5.3p8:
2141 // A declaration of a parameter as "function returning type"
2142 // shall be adjusted to "pointer to function returning type", as
2143 // in 6.3.2.1.
2144 if (T->isFunctionType())
2145 Decayed = getPointerType(T);
2146
2147 QualType Canonical = getCanonicalType(Decayed);
2148
2149 // Get the new insert position for the node we care about.
2150 DecayedType *NewIP = DecayedTypes.FindNodeOrInsertPos(ID, InsertPos);
2151 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2152
2153 DecayedType *New =
2154 new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2155 Types.push_back(New);
2156 DecayedTypes.InsertNode(New, InsertPos);
2157 return QualType(New, 0);
2158}
2159
Mike Stump1eb44332009-09-09 15:08:12 +00002160/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00002161/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00002162QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00002163 assert(T->isFunctionType() && "block of function types only");
2164 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00002165 // structure.
2166 llvm::FoldingSetNodeID ID;
2167 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002168
Steve Naroff5618bd42008-08-27 16:04:49 +00002169 void *InsertPos = 0;
2170 if (BlockPointerType *PT =
2171 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2172 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002173
2174 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00002175 // type either so fill in the canonical type field.
2176 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002177 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00002178 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002179
Steve Naroff5618bd42008-08-27 16:04:49 +00002180 // Get the new insert position for the node we care about.
2181 BlockPointerType *NewIP =
2182 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002183 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00002184 }
John McCall6b304a02009-09-24 23:30:46 +00002185 BlockPointerType *New
2186 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00002187 Types.push_back(New);
2188 BlockPointerTypes.InsertNode(New, InsertPos);
2189 return QualType(New, 0);
2190}
2191
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002192/// getLValueReferenceType - Return the uniqued reference to the type for an
2193/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002194QualType
2195ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00002196 assert(getCanonicalType(T) != OverloadTy &&
2197 "Unresolved overloaded function type");
2198
Reid Spencer5f016e22007-07-11 17:01:13 +00002199 // Unique pointers, to guarantee there is only one pointer of a particular
2200 // structure.
2201 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002202 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002203
2204 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002205 if (LValueReferenceType *RT =
2206 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002207 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002208
John McCall54e14c42009-10-22 22:37:11 +00002209 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2210
Reid Spencer5f016e22007-07-11 17:01:13 +00002211 // If the referencee type isn't canonical, this won't be a canonical type
2212 // either, so fill in the canonical type field.
2213 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002214 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2215 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2216 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002217
Reid Spencer5f016e22007-07-11 17:01:13 +00002218 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002219 LValueReferenceType *NewIP =
2220 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002221 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002222 }
2223
John McCall6b304a02009-09-24 23:30:46 +00002224 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00002225 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2226 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002227 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002228 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00002229
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002230 return QualType(New, 0);
2231}
2232
2233/// getRValueReferenceType - Return the uniqued reference to the type for an
2234/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002235QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002236 // Unique pointers, to guarantee there is only one pointer of a particular
2237 // structure.
2238 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002239 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002240
2241 void *InsertPos = 0;
2242 if (RValueReferenceType *RT =
2243 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2244 return QualType(RT, 0);
2245
John McCall54e14c42009-10-22 22:37:11 +00002246 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2247
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002248 // If the referencee type isn't canonical, this won't be a canonical type
2249 // either, so fill in the canonical type field.
2250 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002251 if (InnerRef || !T.isCanonical()) {
2252 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2253 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002254
2255 // Get the new insert position for the node we care about.
2256 RValueReferenceType *NewIP =
2257 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002258 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002259 }
2260
John McCall6b304a02009-09-24 23:30:46 +00002261 RValueReferenceType *New
2262 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002263 Types.push_back(New);
2264 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002265 return QualType(New, 0);
2266}
2267
Sebastian Redlf30208a2009-01-24 21:16:55 +00002268/// getMemberPointerType - Return the uniqued reference to the type for a
2269/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00002270QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002271 // Unique pointers, to guarantee there is only one pointer of a particular
2272 // structure.
2273 llvm::FoldingSetNodeID ID;
2274 MemberPointerType::Profile(ID, T, Cls);
2275
2276 void *InsertPos = 0;
2277 if (MemberPointerType *PT =
2278 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2279 return QualType(PT, 0);
2280
2281 // If the pointee or class type isn't canonical, this won't be a canonical
2282 // type either, so fill in the canonical type field.
2283 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00002284 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002285 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2286
2287 // Get the new insert position for the node we care about.
2288 MemberPointerType *NewIP =
2289 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002290 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00002291 }
John McCall6b304a02009-09-24 23:30:46 +00002292 MemberPointerType *New
2293 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002294 Types.push_back(New);
2295 MemberPointerTypes.InsertNode(New, InsertPos);
2296 return QualType(New, 0);
2297}
2298
Mike Stump1eb44332009-09-09 15:08:12 +00002299/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00002300/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002301QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00002302 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00002303 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002304 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00002305 assert((EltTy->isDependentType() ||
2306 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00002307 "Constant array of VLAs is illegal!");
2308
Chris Lattner38aeec72009-05-13 04:12:56 +00002309 // Convert the array size into a canonical width matching the pointer size for
2310 // the target.
2311 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002312 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002313 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00002314
Reid Spencer5f016e22007-07-11 17:01:13 +00002315 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002316 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00002317
Reid Spencer5f016e22007-07-11 17:01:13 +00002318 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002319 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002320 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002321 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002322
John McCall3b657512011-01-19 10:06:00 +00002323 // If the element type isn't canonical or has qualifiers, this won't
2324 // be a canonical type either, so fill in the canonical type field.
2325 QualType Canon;
2326 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2327 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002328 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002329 ASM, IndexTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002330 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00002331
Reid Spencer5f016e22007-07-11 17:01:13 +00002332 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00002333 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002334 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002335 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002336 }
Mike Stump1eb44332009-09-09 15:08:12 +00002337
John McCall6b304a02009-09-24 23:30:46 +00002338 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002339 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002340 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002341 Types.push_back(New);
2342 return QualType(New, 0);
2343}
2344
John McCallce889032011-01-18 08:40:38 +00002345/// getVariableArrayDecayedType - Turns the given type, which may be
2346/// variably-modified, into the corresponding type with all the known
2347/// sizes replaced with [*].
2348QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2349 // Vastly most common case.
2350 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002351
John McCallce889032011-01-18 08:40:38 +00002352 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002353
John McCallce889032011-01-18 08:40:38 +00002354 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00002355 const Type *ty = split.Ty;
John McCallce889032011-01-18 08:40:38 +00002356 switch (ty->getTypeClass()) {
2357#define TYPE(Class, Base)
2358#define ABSTRACT_TYPE(Class, Base)
2359#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2360#include "clang/AST/TypeNodes.def"
2361 llvm_unreachable("didn't desugar past all non-canonical types?");
2362
2363 // These types should never be variably-modified.
2364 case Type::Builtin:
2365 case Type::Complex:
2366 case Type::Vector:
2367 case Type::ExtVector:
2368 case Type::DependentSizedExtVector:
2369 case Type::ObjCObject:
2370 case Type::ObjCInterface:
2371 case Type::ObjCObjectPointer:
2372 case Type::Record:
2373 case Type::Enum:
2374 case Type::UnresolvedUsing:
2375 case Type::TypeOfExpr:
2376 case Type::TypeOf:
2377 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00002378 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00002379 case Type::DependentName:
2380 case Type::InjectedClassName:
2381 case Type::TemplateSpecialization:
2382 case Type::DependentTemplateSpecialization:
2383 case Type::TemplateTypeParm:
2384 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00002385 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00002386 case Type::PackExpansion:
2387 llvm_unreachable("type should never be variably-modified");
2388
2389 // These types can be variably-modified but should never need to
2390 // further decay.
2391 case Type::FunctionNoProto:
2392 case Type::FunctionProto:
2393 case Type::BlockPointer:
2394 case Type::MemberPointer:
2395 return type;
2396
2397 // These types can be variably-modified. All these modifications
2398 // preserve structure except as noted by comments.
2399 // TODO: if we ever care about optimizing VLAs, there are no-op
2400 // optimizations available here.
2401 case Type::Pointer:
2402 result = getPointerType(getVariableArrayDecayedType(
2403 cast<PointerType>(ty)->getPointeeType()));
2404 break;
2405
2406 case Type::LValueReference: {
2407 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2408 result = getLValueReferenceType(
2409 getVariableArrayDecayedType(lv->getPointeeType()),
2410 lv->isSpelledAsLValue());
2411 break;
2412 }
2413
2414 case Type::RValueReference: {
2415 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2416 result = getRValueReferenceType(
2417 getVariableArrayDecayedType(lv->getPointeeType()));
2418 break;
2419 }
2420
Eli Friedmanb001de72011-10-06 23:00:33 +00002421 case Type::Atomic: {
2422 const AtomicType *at = cast<AtomicType>(ty);
2423 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2424 break;
2425 }
2426
John McCallce889032011-01-18 08:40:38 +00002427 case Type::ConstantArray: {
2428 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2429 result = getConstantArrayType(
2430 getVariableArrayDecayedType(cat->getElementType()),
2431 cat->getSize(),
2432 cat->getSizeModifier(),
2433 cat->getIndexTypeCVRQualifiers());
2434 break;
2435 }
2436
2437 case Type::DependentSizedArray: {
2438 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2439 result = getDependentSizedArrayType(
2440 getVariableArrayDecayedType(dat->getElementType()),
2441 dat->getSizeExpr(),
2442 dat->getSizeModifier(),
2443 dat->getIndexTypeCVRQualifiers(),
2444 dat->getBracketsRange());
2445 break;
2446 }
2447
2448 // Turn incomplete types into [*] types.
2449 case Type::IncompleteArray: {
2450 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2451 result = getVariableArrayType(
2452 getVariableArrayDecayedType(iat->getElementType()),
2453 /*size*/ 0,
2454 ArrayType::Normal,
2455 iat->getIndexTypeCVRQualifiers(),
2456 SourceRange());
2457 break;
2458 }
2459
2460 // Turn VLA types into [*] types.
2461 case Type::VariableArray: {
2462 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2463 result = getVariableArrayType(
2464 getVariableArrayDecayedType(vat->getElementType()),
2465 /*size*/ 0,
2466 ArrayType::Star,
2467 vat->getIndexTypeCVRQualifiers(),
2468 vat->getBracketsRange());
2469 break;
2470 }
2471 }
2472
2473 // Apply the top-level qualifiers from the original.
John McCall200fa532012-02-08 00:46:36 +00002474 return getQualifiedType(result, split.Quals);
John McCallce889032011-01-18 08:40:38 +00002475}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002476
Steve Naroffbdbf7b02007-08-30 18:14:25 +00002477/// getVariableArrayType - Returns a non-unique reference to the type for a
2478/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002479QualType ASTContext::getVariableArrayType(QualType EltTy,
2480 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00002481 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002482 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00002483 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002484 // Since we don't unique expressions, it isn't possible to unique VLA's
2485 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00002486 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00002487
John McCall3b657512011-01-19 10:06:00 +00002488 // Be sure to pull qualifiers off the element type.
2489 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2490 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002491 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002492 IndexTypeQuals, Brackets);
John McCall200fa532012-02-08 00:46:36 +00002493 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor715e9c82010-05-23 16:10:32 +00002494 }
2495
John McCall6b304a02009-09-24 23:30:46 +00002496 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002497 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002498
2499 VariableArrayTypes.push_back(New);
2500 Types.push_back(New);
2501 return QualType(New, 0);
2502}
2503
Douglas Gregor898574e2008-12-05 23:32:09 +00002504/// getDependentSizedArrayType - Returns a non-unique reference to
2505/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00002506/// type.
John McCall3b657512011-01-19 10:06:00 +00002507QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2508 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00002509 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002510 unsigned elementTypeQuals,
2511 SourceRange brackets) const {
2512 assert((!numElements || numElements->isTypeDependent() ||
2513 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00002514 "Size must be type- or value-dependent!");
2515
John McCall3b657512011-01-19 10:06:00 +00002516 // Dependently-sized array types that do not have a specified number
2517 // of elements will have their sizes deduced from a dependent
2518 // initializer. We do no canonicalization here at all, which is okay
2519 // because they can't be used in most locations.
2520 if (!numElements) {
2521 DependentSizedArrayType *newType
2522 = new (*this, TypeAlignment)
2523 DependentSizedArrayType(*this, elementType, QualType(),
2524 numElements, ASM, elementTypeQuals,
2525 brackets);
2526 Types.push_back(newType);
2527 return QualType(newType, 0);
2528 }
2529
2530 // Otherwise, we actually build a new type every time, but we
2531 // also build a canonical type.
2532
2533 SplitQualType canonElementType = getCanonicalType(elementType).split();
2534
2535 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00002536 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002537 DependentSizedArrayType::Profile(ID, *this,
John McCall200fa532012-02-08 00:46:36 +00002538 QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002539 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002540
John McCall3b657512011-01-19 10:06:00 +00002541 // Look for an existing type with these properties.
2542 DependentSizedArrayType *canonTy =
2543 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002544
John McCall3b657512011-01-19 10:06:00 +00002545 // If we don't have one, build one.
2546 if (!canonTy) {
2547 canonTy = new (*this, TypeAlignment)
John McCall200fa532012-02-08 00:46:36 +00002548 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002549 QualType(), numElements, ASM, elementTypeQuals,
2550 brackets);
2551 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2552 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002553 }
2554
John McCall3b657512011-01-19 10:06:00 +00002555 // Apply qualifiers from the element type to the array.
2556 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall200fa532012-02-08 00:46:36 +00002557 canonElementType.Quals);
Mike Stump1eb44332009-09-09 15:08:12 +00002558
John McCall3b657512011-01-19 10:06:00 +00002559 // If we didn't need extra canonicalization for the element type,
2560 // then just use that as our result.
John McCall200fa532012-02-08 00:46:36 +00002561 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall3b657512011-01-19 10:06:00 +00002562 return canon;
2563
2564 // Otherwise, we need to build a type which follows the spelling
2565 // of the element type.
2566 DependentSizedArrayType *sugaredType
2567 = new (*this, TypeAlignment)
2568 DependentSizedArrayType(*this, elementType, canon, numElements,
2569 ASM, elementTypeQuals, brackets);
2570 Types.push_back(sugaredType);
2571 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00002572}
2573
John McCall3b657512011-01-19 10:06:00 +00002574QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00002575 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002576 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002577 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002578 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002579
John McCall3b657512011-01-19 10:06:00 +00002580 void *insertPos = 0;
2581 if (IncompleteArrayType *iat =
2582 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2583 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002584
2585 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00002586 // either, so fill in the canonical type field. We also have to pull
2587 // qualifiers off the element type.
2588 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00002589
John McCall3b657512011-01-19 10:06:00 +00002590 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2591 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall200fa532012-02-08 00:46:36 +00002592 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002593 ASM, elementTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002594 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002595
2596 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00002597 IncompleteArrayType *existing =
2598 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2599 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00002600 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00002601
John McCall3b657512011-01-19 10:06:00 +00002602 IncompleteArrayType *newType = new (*this, TypeAlignment)
2603 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002604
John McCall3b657512011-01-19 10:06:00 +00002605 IncompleteArrayTypes.InsertNode(newType, insertPos);
2606 Types.push_back(newType);
2607 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00002608}
2609
Steve Naroff73322922007-07-18 18:00:27 +00002610/// getVectorType - Return the unique reference to a vector type of
2611/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00002612QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00002613 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00002614 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00002615
Reid Spencer5f016e22007-07-11 17:01:13 +00002616 // Check if we've already instantiated a vector of this type.
2617 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00002618 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00002619
Reid Spencer5f016e22007-07-11 17:01:13 +00002620 void *InsertPos = 0;
2621 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2622 return QualType(VTP, 0);
2623
2624 // If the element type isn't canonical, this won't be a canonical type either,
2625 // so fill in the canonical type field.
2626 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00002627 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00002628 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002629
Reid Spencer5f016e22007-07-11 17:01:13 +00002630 // Get the new insert position for the node we care about.
2631 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002632 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002633 }
John McCall6b304a02009-09-24 23:30:46 +00002634 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00002635 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002636 VectorTypes.InsertNode(New, InsertPos);
2637 Types.push_back(New);
2638 return QualType(New, 0);
2639}
2640
Nate Begeman213541a2008-04-18 23:10:10 +00002641/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00002642/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002643QualType
2644ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00002645 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00002646
Steve Naroff73322922007-07-18 18:00:27 +00002647 // Check if we've already instantiated a vector of this type.
2648 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00002649 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002650 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00002651 void *InsertPos = 0;
2652 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2653 return QualType(VTP, 0);
2654
2655 // If the element type isn't canonical, this won't be a canonical type either,
2656 // so fill in the canonical type field.
2657 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002658 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002659 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00002660
Steve Naroff73322922007-07-18 18:00:27 +00002661 // Get the new insert position for the node we care about.
2662 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002663 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00002664 }
John McCall6b304a02009-09-24 23:30:46 +00002665 ExtVectorType *New = new (*this, TypeAlignment)
2666 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00002667 VectorTypes.InsertNode(New, InsertPos);
2668 Types.push_back(New);
2669 return QualType(New, 0);
2670}
2671
Jay Foad4ba2a172011-01-12 09:06:06 +00002672QualType
2673ASTContext::getDependentSizedExtVectorType(QualType vecType,
2674 Expr *SizeExpr,
2675 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002676 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002677 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002678 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002679
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002680 void *InsertPos = 0;
2681 DependentSizedExtVectorType *Canon
2682 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2683 DependentSizedExtVectorType *New;
2684 if (Canon) {
2685 // We already have a canonical version of this array type; use it as
2686 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002687 New = new (*this, TypeAlignment)
2688 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2689 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002690 } else {
2691 QualType CanonVecTy = getCanonicalType(vecType);
2692 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002693 New = new (*this, TypeAlignment)
2694 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2695 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002696
2697 DependentSizedExtVectorType *CanonCheck
2698 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2699 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2700 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002701 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2702 } else {
2703 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2704 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002705 New = new (*this, TypeAlignment)
2706 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002707 }
2708 }
Mike Stump1eb44332009-09-09 15:08:12 +00002709
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002710 Types.push_back(New);
2711 return QualType(New, 0);
2712}
2713
Douglas Gregor72564e72009-02-26 23:50:07 +00002714/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002715///
Jay Foad4ba2a172011-01-12 09:06:06 +00002716QualType
2717ASTContext::getFunctionNoProtoType(QualType ResultTy,
2718 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00002719 const CallingConv DefaultCC = Info.getCC();
2720 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2721 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00002722 // Unique functions, to guarantee there is only one function of a particular
2723 // structure.
2724 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002725 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002726
Reid Spencer5f016e22007-07-11 17:01:13 +00002727 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002728 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002729 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002730 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002731
Reid Spencer5f016e22007-07-11 17:01:13 +00002732 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00002733 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00002734 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00002735 Canonical =
2736 getFunctionNoProtoType(getCanonicalType(ResultTy),
2737 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00002738
Reid Spencer5f016e22007-07-11 17:01:13 +00002739 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002740 FunctionNoProtoType *NewIP =
2741 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002742 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002743 }
Mike Stump1eb44332009-09-09 15:08:12 +00002744
Roman Divackycfe9af22011-03-01 17:40:53 +00002745 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002746 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002747 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002748 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002749 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002750 return QualType(New, 0);
2751}
2752
Douglas Gregor02dd7982013-01-17 23:36:45 +00002753/// \brief Determine whether \p T is canonical as the result type of a function.
2754static bool isCanonicalResultType(QualType T) {
2755 return T.isCanonical() &&
2756 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2757 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2758}
2759
Reid Spencer5f016e22007-07-11 17:01:13 +00002760/// getFunctionType - Return a normal function type with a typed argument
2761/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002762QualType
Jordan Rosebea522f2013-03-08 21:51:21 +00002763ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad4ba2a172011-01-12 09:06:06 +00002764 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rosebea522f2013-03-08 21:51:21 +00002765 size_t NumArgs = ArgArray.size();
2766
Reid Spencer5f016e22007-07-11 17:01:13 +00002767 // Unique functions, to guarantee there is only one function of a particular
2768 // structure.
2769 llvm::FoldingSetNodeID ID;
Jordan Rosebea522f2013-03-08 21:51:21 +00002770 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2771 *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002772
2773 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002774 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002775 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002776 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002777
2778 // Determine whether the type being created is already canonical or not.
Richard Smitheefb3d52012-02-10 09:58:53 +00002779 bool isCanonical =
Douglas Gregor02dd7982013-01-17 23:36:45 +00002780 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smitheefb3d52012-02-10 09:58:53 +00002781 !EPI.HasTrailingReturn;
Reid Spencer5f016e22007-07-11 17:01:13 +00002782 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002783 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002784 isCanonical = false;
2785
Roman Divackycfe9af22011-03-01 17:40:53 +00002786 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2787 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2788 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002789
Reid Spencer5f016e22007-07-11 17:01:13 +00002790 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002791 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002792 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002793 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002794 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002795 CanonicalArgs.reserve(NumArgs);
2796 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002797 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002798
John McCalle23cf432010-12-14 08:05:40 +00002799 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +00002800 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002801 CanonicalEPI.ExceptionSpecType = EST_None;
2802 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002803 CanonicalEPI.ExtInfo
2804 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2805
Douglas Gregor02dd7982013-01-17 23:36:45 +00002806 // Result types do not have ARC lifetime qualifiers.
2807 QualType CanResultTy = getCanonicalType(ResultTy);
2808 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2809 Qualifiers Qs = CanResultTy.getQualifiers();
2810 Qs.removeObjCLifetime();
2811 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2812 }
2813
Jordan Rosebea522f2013-03-08 21:51:21 +00002814 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002815
Reid Spencer5f016e22007-07-11 17:01:13 +00002816 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002817 FunctionProtoType *NewIP =
2818 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002819 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002820 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002821
John McCallf85e1932011-06-15 23:02:42 +00002822 // FunctionProtoType objects are allocated with extra bytes after
2823 // them for three variable size arrays at the end:
2824 // - parameter types
2825 // - exception types
2826 // - consumed-arguments flags
2827 // Instead of the exception types, there could be a noexcept
Richard Smithb9d0b762012-07-27 04:22:15 +00002828 // expression, or information used to resolve the exception
2829 // specification.
John McCalle23cf432010-12-14 08:05:40 +00002830 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002831 NumArgs * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002832 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00002833 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002834 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002835 Size += sizeof(Expr*);
Richard Smithe6975e92012-04-17 00:58:00 +00002836 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smith13bffc52012-04-19 00:08:28 +00002837 Size += 2 * sizeof(FunctionDecl*);
Richard Smithb9d0b762012-07-27 04:22:15 +00002838 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2839 Size += sizeof(FunctionDecl*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002840 }
John McCallf85e1932011-06-15 23:02:42 +00002841 if (EPI.ConsumedArguments)
2842 Size += NumArgs * sizeof(bool);
2843
John McCalle23cf432010-12-14 08:05:40 +00002844 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002845 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2846 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Jordan Rosebea522f2013-03-08 21:51:21 +00002847 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002848 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002849 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002850 return QualType(FTP, 0);
2851}
2852
John McCall3cb0ebd2010-03-10 03:28:59 +00002853#ifndef NDEBUG
2854static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2855 if (!isa<CXXRecordDecl>(D)) return false;
2856 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2857 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2858 return true;
2859 if (RD->getDescribedClassTemplate() &&
2860 !isa<ClassTemplateSpecializationDecl>(RD))
2861 return true;
2862 return false;
2863}
2864#endif
2865
2866/// getInjectedClassNameType - Return the unique reference to the
2867/// injected class name type for the specified templated declaration.
2868QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002869 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002870 assert(NeedsInjectedClassNameType(Decl));
2871 if (Decl->TypeForDecl) {
2872 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregoref96ee02012-01-14 16:38:05 +00002873 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002874 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2875 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2876 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2877 } else {
John McCallf4c73712011-01-19 06:33:43 +00002878 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002879 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002880 Decl->TypeForDecl = newType;
2881 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002882 }
2883 return QualType(Decl->TypeForDecl, 0);
2884}
2885
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002886/// getTypeDeclType - Return the unique reference to the type for the
2887/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002888QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002889 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002890 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002891
Richard Smith162e1c12011-04-15 14:24:37 +00002892 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002893 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002894
John McCallbecb8d52010-03-10 06:48:02 +00002895 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2896 "Template type parameter types are always available.");
2897
John McCall19c85762010-02-16 03:57:14 +00002898 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002899 assert(!Record->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002900 "struct/union has previous declaration");
2901 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002902 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002903 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002904 assert(!Enum->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002905 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002906 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002907 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002908 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002909 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2910 Decl->TypeForDecl = newType;
2911 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002912 } else
John McCallbecb8d52010-03-10 06:48:02 +00002913 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002914
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002915 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002916}
2917
Reid Spencer5f016e22007-07-11 17:01:13 +00002918/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002919/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002920QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002921ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2922 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002923 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002924
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002925 if (Canonical.isNull())
2926 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002927 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002928 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002929 Decl->TypeForDecl = newType;
2930 Types.push_back(newType);
2931 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002932}
2933
Jay Foad4ba2a172011-01-12 09:06:06 +00002934QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002935 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2936
Douglas Gregoref96ee02012-01-14 16:38:05 +00002937 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002938 if (PrevDecl->TypeForDecl)
2939 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2940
John McCallf4c73712011-01-19 06:33:43 +00002941 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2942 Decl->TypeForDecl = newType;
2943 Types.push_back(newType);
2944 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002945}
2946
Jay Foad4ba2a172011-01-12 09:06:06 +00002947QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002948 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2949
Douglas Gregoref96ee02012-01-14 16:38:05 +00002950 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002951 if (PrevDecl->TypeForDecl)
2952 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2953
John McCallf4c73712011-01-19 06:33:43 +00002954 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2955 Decl->TypeForDecl = newType;
2956 Types.push_back(newType);
2957 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002958}
2959
John McCall9d156a72011-01-06 01:58:22 +00002960QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2961 QualType modifiedType,
2962 QualType equivalentType) {
2963 llvm::FoldingSetNodeID id;
2964 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2965
2966 void *insertPos = 0;
2967 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2968 if (type) return QualType(type, 0);
2969
2970 QualType canon = getCanonicalType(equivalentType);
2971 type = new (*this, TypeAlignment)
2972 AttributedType(canon, attrKind, modifiedType, equivalentType);
2973
2974 Types.push_back(type);
2975 AttributedTypes.InsertNode(type, insertPos);
2976
2977 return QualType(type, 0);
2978}
2979
2980
John McCall49a832b2009-10-18 09:09:24 +00002981/// \brief Retrieve a substitution-result type.
2982QualType
2983ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002984 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002985 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002986 && "replacement types must always be canonical");
2987
2988 llvm::FoldingSetNodeID ID;
2989 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2990 void *InsertPos = 0;
2991 SubstTemplateTypeParmType *SubstParm
2992 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2993
2994 if (!SubstParm) {
2995 SubstParm = new (*this, TypeAlignment)
2996 SubstTemplateTypeParmType(Parm, Replacement);
2997 Types.push_back(SubstParm);
2998 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2999 }
3000
3001 return QualType(SubstParm, 0);
3002}
3003
Douglas Gregorc3069d62011-01-14 02:55:32 +00003004/// \brief Retrieve a
3005QualType ASTContext::getSubstTemplateTypeParmPackType(
3006 const TemplateTypeParmType *Parm,
3007 const TemplateArgument &ArgPack) {
3008#ifndef NDEBUG
3009 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
3010 PEnd = ArgPack.pack_end();
3011 P != PEnd; ++P) {
3012 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3013 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
3014 }
3015#endif
3016
3017 llvm::FoldingSetNodeID ID;
3018 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3019 void *InsertPos = 0;
3020 if (SubstTemplateTypeParmPackType *SubstParm
3021 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3022 return QualType(SubstParm, 0);
3023
3024 QualType Canon;
3025 if (!Parm->isCanonicalUnqualified()) {
3026 Canon = getCanonicalType(QualType(Parm, 0));
3027 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3028 ArgPack);
3029 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3030 }
3031
3032 SubstTemplateTypeParmPackType *SubstParm
3033 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3034 ArgPack);
3035 Types.push_back(SubstParm);
3036 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3037 return QualType(SubstParm, 0);
3038}
3039
Douglas Gregorfab9d672009-02-05 23:33:38 +00003040/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00003041/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003042/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00003043QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003044 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003045 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00003046 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003047 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00003048 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003049 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00003050 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3051
3052 if (TypeParm)
3053 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003054
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003055 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003056 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003057 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003058
3059 TemplateTypeParmType *TypeCheck
3060 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3061 assert(!TypeCheck && "Template type parameter canonical type broken");
3062 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003063 } else
John McCall6b304a02009-09-24 23:30:46 +00003064 TypeParm = new (*this, TypeAlignment)
3065 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00003066
3067 Types.push_back(TypeParm);
3068 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3069
3070 return QualType(TypeParm, 0);
3071}
3072
John McCall3cb0ebd2010-03-10 03:28:59 +00003073TypeSourceInfo *
3074ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3075 SourceLocation NameLoc,
3076 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003077 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003078 assert(!Name.getAsDependentTemplateName() &&
3079 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00003080 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00003081
3082 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie39e6ab42013-02-18 22:06:02 +00003083 TemplateSpecializationTypeLoc TL =
3084 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara55d23c92012-02-06 14:41:24 +00003085 TL.setTemplateKeywordLoc(SourceLocation());
John McCall3cb0ebd2010-03-10 03:28:59 +00003086 TL.setTemplateNameLoc(NameLoc);
3087 TL.setLAngleLoc(Args.getLAngleLoc());
3088 TL.setRAngleLoc(Args.getRAngleLoc());
3089 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3090 TL.setArgLocInfo(i, Args[i].getLocInfo());
3091 return DI;
3092}
3093
Mike Stump1eb44332009-09-09 15:08:12 +00003094QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00003095ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00003096 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003097 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003098 assert(!Template.getAsDependentTemplateName() &&
3099 "No dependent template names here!");
3100
John McCalld5532b62009-11-23 01:53:49 +00003101 unsigned NumArgs = Args.size();
3102
Chris Lattner5f9e2722011-07-23 10:55:15 +00003103 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00003104 ArgVec.reserve(NumArgs);
3105 for (unsigned i = 0; i != NumArgs; ++i)
3106 ArgVec.push_back(Args[i].getArgument());
3107
John McCall31f17ec2010-04-27 00:57:59 +00003108 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003109 Underlying);
John McCall833ca992009-10-29 08:12:44 +00003110}
3111
Douglas Gregorb70126a2012-02-03 17:16:23 +00003112#ifndef NDEBUG
3113static bool hasAnyPackExpansions(const TemplateArgument *Args,
3114 unsigned NumArgs) {
3115 for (unsigned I = 0; I != NumArgs; ++I)
3116 if (Args[I].isPackExpansion())
3117 return true;
3118
3119 return true;
3120}
3121#endif
3122
John McCall833ca992009-10-29 08:12:44 +00003123QualType
3124ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003125 const TemplateArgument *Args,
3126 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003127 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003128 assert(!Template.getAsDependentTemplateName() &&
3129 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003130 // Look through qualified template names.
3131 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3132 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003133
Douglas Gregorb70126a2012-02-03 17:16:23 +00003134 bool IsTypeAlias =
Richard Smith3e4c6c42011-05-05 21:57:07 +00003135 Template.getAsTemplateDecl() &&
3136 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00003137 QualType CanonType;
3138 if (!Underlying.isNull())
3139 CanonType = getCanonicalType(Underlying);
3140 else {
Douglas Gregorb70126a2012-02-03 17:16:23 +00003141 // We can get here with an alias template when the specialization contains
3142 // a pack expansion that does not match up with a parameter pack.
3143 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3144 "Caller must compute aliased type");
3145 IsTypeAlias = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00003146 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3147 NumArgs);
3148 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00003149
Douglas Gregor1275ae02009-07-28 23:00:59 +00003150 // Allocate the (non-canonical) template specialization type, but don't
3151 // try to unique it: these types typically have location information that
3152 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00003153 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3154 sizeof(TemplateArgument) * NumArgs +
Douglas Gregorb70126a2012-02-03 17:16:23 +00003155 (IsTypeAlias? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00003156 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00003157 TemplateSpecializationType *Spec
Douglas Gregorb70126a2012-02-03 17:16:23 +00003158 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3159 IsTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00003160
Douglas Gregor55f6b142009-02-09 18:46:07 +00003161 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00003162 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00003163}
3164
Mike Stump1eb44332009-09-09 15:08:12 +00003165QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003166ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3167 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00003168 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003169 assert(!Template.getAsDependentTemplateName() &&
3170 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00003171
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003172 // Look through qualified template names.
3173 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3174 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003175
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003176 // Build the canonical template specialization type.
3177 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003178 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003179 CanonArgs.reserve(NumArgs);
3180 for (unsigned I = 0; I != NumArgs; ++I)
3181 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3182
3183 // Determine whether this canonical template specialization type already
3184 // exists.
3185 llvm::FoldingSetNodeID ID;
3186 TemplateSpecializationType::Profile(ID, CanonTemplate,
3187 CanonArgs.data(), NumArgs, *this);
3188
3189 void *InsertPos = 0;
3190 TemplateSpecializationType *Spec
3191 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3192
3193 if (!Spec) {
3194 // Allocate a new canonical template specialization type.
3195 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3196 sizeof(TemplateArgument) * NumArgs),
3197 TypeAlignment);
3198 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3199 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003200 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003201 Types.push_back(Spec);
3202 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3203 }
3204
3205 assert(Spec->isDependentType() &&
3206 "Non-dependent template-id type must have a canonical type");
3207 return QualType(Spec, 0);
3208}
3209
3210QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003211ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3212 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00003213 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00003214 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003215 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003216
3217 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003218 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003219 if (T)
3220 return QualType(T, 0);
3221
Douglas Gregor789b1f62010-02-04 18:10:26 +00003222 QualType Canon = NamedType;
3223 if (!Canon.isCanonical()) {
3224 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003225 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3226 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00003227 (void)CheckT;
3228 }
3229
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003230 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003231 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003232 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003233 return QualType(T, 0);
3234}
3235
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003236QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00003237ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003238 llvm::FoldingSetNodeID ID;
3239 ParenType::Profile(ID, InnerType);
3240
3241 void *InsertPos = 0;
3242 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3243 if (T)
3244 return QualType(T, 0);
3245
3246 QualType Canon = InnerType;
3247 if (!Canon.isCanonical()) {
3248 Canon = getCanonicalType(InnerType);
3249 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3250 assert(!CheckT && "Paren canonical type broken");
3251 (void)CheckT;
3252 }
3253
3254 T = new (*this) ParenType(InnerType, Canon);
3255 Types.push_back(T);
3256 ParenTypes.InsertNode(T, InsertPos);
3257 return QualType(T, 0);
3258}
3259
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003260QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3261 NestedNameSpecifier *NNS,
3262 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003263 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00003264 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3265
3266 if (Canon.isNull()) {
3267 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003268 ElaboratedTypeKeyword CanonKeyword = Keyword;
3269 if (Keyword == ETK_None)
3270 CanonKeyword = ETK_Typename;
3271
3272 if (CanonNNS != NNS || CanonKeyword != Keyword)
3273 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003274 }
3275
3276 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003277 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003278
3279 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00003280 DependentNameType *T
3281 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00003282 if (T)
3283 return QualType(T, 0);
3284
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003285 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00003286 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00003287 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003288 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00003289}
3290
Mike Stump1eb44332009-09-09 15:08:12 +00003291QualType
John McCall33500952010-06-11 00:33:02 +00003292ASTContext::getDependentTemplateSpecializationType(
3293 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003294 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00003295 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003296 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00003297 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00003298 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00003299 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3300 ArgCopy.push_back(Args[I].getArgument());
3301 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3302 ArgCopy.size(),
3303 ArgCopy.data());
3304}
3305
3306QualType
3307ASTContext::getDependentTemplateSpecializationType(
3308 ElaboratedTypeKeyword Keyword,
3309 NestedNameSpecifier *NNS,
3310 const IdentifierInfo *Name,
3311 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00003312 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003313 assert((!NNS || NNS->isDependent()) &&
3314 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00003315
Douglas Gregor789b1f62010-02-04 18:10:26 +00003316 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00003317 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3318 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003319
3320 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00003321 DependentTemplateSpecializationType *T
3322 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003323 if (T)
3324 return QualType(T, 0);
3325
John McCall33500952010-06-11 00:33:02 +00003326 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003327
John McCall33500952010-06-11 00:33:02 +00003328 ElaboratedTypeKeyword CanonKeyword = Keyword;
3329 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3330
3331 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003332 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00003333 for (unsigned I = 0; I != NumArgs; ++I) {
3334 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3335 if (!CanonArgs[I].structurallyEquals(Args[I]))
3336 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00003337 }
3338
John McCall33500952010-06-11 00:33:02 +00003339 QualType Canon;
3340 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3341 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3342 Name, NumArgs,
3343 CanonArgs.data());
3344
3345 // Find the insert position again.
3346 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3347 }
3348
3349 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3350 sizeof(TemplateArgument) * NumArgs),
3351 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00003352 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00003353 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00003354 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00003355 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003356 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00003357}
3358
Douglas Gregorcded4f62011-01-14 17:04:44 +00003359QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikiedc84cd52013-02-20 22:23:23 +00003360 Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00003361 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00003362 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003363
3364 assert(Pattern->containsUnexpandedParameterPack() &&
3365 "Pack expansions must expand one or more parameter packs");
3366 void *InsertPos = 0;
3367 PackExpansionType *T
3368 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3369 if (T)
3370 return QualType(T, 0);
3371
3372 QualType Canon;
3373 if (!Pattern.isCanonical()) {
Richard Smithd8672ef2012-07-16 00:20:35 +00003374 Canon = getCanonicalType(Pattern);
3375 // The canonical type might not contain an unexpanded parameter pack, if it
3376 // contains an alias template specialization which ignores one of its
3377 // parameters.
3378 if (Canon->containsUnexpandedParameterPack()) {
3379 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003380
Richard Smithd8672ef2012-07-16 00:20:35 +00003381 // Find the insert position again, in case we inserted an element into
3382 // PackExpansionTypes and invalidated our insert position.
3383 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3384 }
Douglas Gregor7536dd52010-12-20 02:24:11 +00003385 }
3386
Douglas Gregorcded4f62011-01-14 17:04:44 +00003387 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003388 Types.push_back(T);
3389 PackExpansionTypes.InsertNode(T, InsertPos);
3390 return QualType(T, 0);
3391}
3392
Chris Lattner88cb27a2008-04-07 04:56:42 +00003393/// CmpProtocolNames - Comparison predicate for sorting protocols
3394/// alphabetically.
3395static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3396 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003397 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00003398}
3399
John McCallc12c5bb2010-05-15 11:32:37 +00003400static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00003401 unsigned NumProtocols) {
3402 if (NumProtocols == 0) return true;
3403
Douglas Gregor61cc2962012-01-02 02:00:30 +00003404 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3405 return false;
3406
John McCall54e14c42009-10-22 22:37:11 +00003407 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregor61cc2962012-01-02 02:00:30 +00003408 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3409 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCall54e14c42009-10-22 22:37:11 +00003410 return false;
3411 return true;
3412}
3413
3414static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00003415 unsigned &NumProtocols) {
3416 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00003417
Chris Lattner88cb27a2008-04-07 04:56:42 +00003418 // Sort protocols, keyed by name.
3419 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3420
Douglas Gregor61cc2962012-01-02 02:00:30 +00003421 // Canonicalize.
3422 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3423 Protocols[I] = Protocols[I]->getCanonicalDecl();
3424
Chris Lattner88cb27a2008-04-07 04:56:42 +00003425 // Remove duplicates.
3426 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3427 NumProtocols = ProtocolsEnd-Protocols;
3428}
3429
John McCallc12c5bb2010-05-15 11:32:37 +00003430QualType ASTContext::getObjCObjectType(QualType BaseType,
3431 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00003432 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003433 // If the base type is an interface and there aren't any protocols
3434 // to add, then the interface type will do just fine.
3435 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3436 return BaseType;
3437
3438 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003439 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00003440 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003441 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00003442 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3443 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003444
John McCallc12c5bb2010-05-15 11:32:37 +00003445 // Build the canonical type, which has the canonical base type and
3446 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00003447 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00003448 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3449 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3450 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003451 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00003452 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003453 unsigned UniqueCount = NumProtocols;
3454
John McCall54e14c42009-10-22 22:37:11 +00003455 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00003456 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3457 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00003458 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00003459 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3460 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003461 }
3462
3463 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00003464 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3465 }
3466
3467 unsigned Size = sizeof(ObjCObjectTypeImpl);
3468 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3469 void *Mem = Allocate(Size, TypeAlignment);
3470 ObjCObjectTypeImpl *T =
3471 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3472
3473 Types.push_back(T);
3474 ObjCObjectTypes.InsertNode(T, InsertPos);
3475 return QualType(T, 0);
3476}
3477
3478/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3479/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003480QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003481 llvm::FoldingSetNodeID ID;
3482 ObjCObjectPointerType::Profile(ID, ObjectT);
3483
3484 void *InsertPos = 0;
3485 if (ObjCObjectPointerType *QT =
3486 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3487 return QualType(QT, 0);
3488
3489 // Find the canonical object type.
3490 QualType Canonical;
3491 if (!ObjectT.isCanonical()) {
3492 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3493
3494 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00003495 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3496 }
3497
Douglas Gregorfd6a0882010-02-08 22:59:26 +00003498 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00003499 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3500 ObjCObjectPointerType *QType =
3501 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00003502
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003503 Types.push_back(QType);
3504 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00003505 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003506}
Chris Lattner88cb27a2008-04-07 04:56:42 +00003507
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003508/// getObjCInterfaceType - Return the unique reference to the type for the
3509/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00003510QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3511 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003512 if (Decl->TypeForDecl)
3513 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003514
Douglas Gregor0af55012011-12-16 03:12:41 +00003515 if (PrevDecl) {
3516 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3517 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3518 return QualType(PrevDecl->TypeForDecl, 0);
3519 }
3520
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00003521 // Prefer the definition, if there is one.
3522 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3523 Decl = Def;
3524
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003525 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3526 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3527 Decl->TypeForDecl = T;
3528 Types.push_back(T);
3529 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00003530}
3531
Douglas Gregor72564e72009-02-26 23:50:07 +00003532/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3533/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00003534/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00003535/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003536/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003537QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003538 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00003539 if (tofExpr->isTypeDependent()) {
3540 llvm::FoldingSetNodeID ID;
3541 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00003542
Douglas Gregorb1975722009-07-30 23:18:24 +00003543 void *InsertPos = 0;
3544 DependentTypeOfExprType *Canon
3545 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3546 if (Canon) {
3547 // We already have a "canonical" version of an identical, dependent
3548 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00003549 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00003550 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003551 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00003552 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003553 Canon
3554 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00003555 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3556 toe = Canon;
3557 }
3558 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003559 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00003560 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00003561 }
Steve Naroff9752f252007-08-01 18:02:17 +00003562 Types.push_back(toe);
3563 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003564}
3565
Steve Naroff9752f252007-08-01 18:02:17 +00003566/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3567/// TypeOfType AST's. The only motivation to unique these nodes would be
3568/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003569/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003570/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003571QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00003572 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00003573 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00003574 Types.push_back(tot);
3575 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003576}
3577
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00003578
Anders Carlsson395b4752009-06-24 19:06:50 +00003579/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3580/// DecltypeType AST's. The only motivation to unique these nodes would be
3581/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003582/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00003583/// on canonical types (which are always unique).
Douglas Gregorf8af9822012-02-12 18:42:33 +00003584QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003585 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00003586
3587 // C++0x [temp.type]p2:
3588 // If an expression e involves a template parameter, decltype(e) denotes a
3589 // unique dependent type. Two such decltype-specifiers refer to the same
3590 // type only if their expressions are equivalent (14.5.6.1).
3591 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003592 llvm::FoldingSetNodeID ID;
3593 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00003594
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003595 void *InsertPos = 0;
3596 DependentDecltypeType *Canon
3597 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3598 if (Canon) {
3599 // We already have a "canonical" version of an equivalent, dependent
3600 // decltype type. Use that as our canonical type.
Richard Smith0d729102012-08-13 20:08:14 +00003601 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003602 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003603 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003604 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003605 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003606 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3607 dt = Canon;
3608 }
3609 } else {
Douglas Gregorf8af9822012-02-12 18:42:33 +00003610 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3611 getCanonicalType(UnderlyingType));
Douglas Gregordd0257c2009-07-08 00:03:05 +00003612 }
Anders Carlsson395b4752009-06-24 19:06:50 +00003613 Types.push_back(dt);
3614 return QualType(dt, 0);
3615}
3616
Sean Huntca63c202011-05-24 22:41:36 +00003617/// getUnaryTransformationType - We don't unique these, since the memory
3618/// savings are minimal and these are rare.
3619QualType ASTContext::getUnaryTransformType(QualType BaseType,
3620 QualType UnderlyingType,
3621 UnaryTransformType::UTTKind Kind)
3622 const {
3623 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00003624 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3625 Kind,
3626 UnderlyingType->isDependentType() ?
Peter Collingbourne12fc4b02012-03-05 16:02:06 +00003627 QualType() : getCanonicalType(UnderlyingType));
Sean Huntca63c202011-05-24 22:41:36 +00003628 Types.push_back(Ty);
3629 return QualType(Ty, 0);
3630}
3631
Richard Smith60e141e2013-05-04 07:00:32 +00003632/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3633/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3634/// canonical deduced-but-dependent 'auto' type.
3635QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Richard Smithdc7a4f52013-04-30 13:56:41 +00003636 bool IsDependent) const {
Richard Smith60e141e2013-05-04 07:00:32 +00003637 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
3638 return getAutoDeductType();
3639
3640 // Look in the folding set for an existing type.
Richard Smith483b9f32011-02-21 20:05:19 +00003641 void *InsertPos = 0;
Richard Smith60e141e2013-05-04 07:00:32 +00003642 llvm::FoldingSetNodeID ID;
3643 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
3644 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3645 return QualType(AT, 0);
Richard Smith483b9f32011-02-21 20:05:19 +00003646
Richard Smitha2c36462013-04-26 16:15:35 +00003647 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithdc7a4f52013-04-30 13:56:41 +00003648 IsDecltypeAuto,
3649 IsDependent);
Richard Smith483b9f32011-02-21 20:05:19 +00003650 Types.push_back(AT);
3651 if (InsertPos)
3652 AutoTypes.InsertNode(AT, InsertPos);
3653 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00003654}
3655
Eli Friedmanb001de72011-10-06 23:00:33 +00003656/// getAtomicType - Return the uniqued reference to the atomic type for
3657/// the given value type.
3658QualType ASTContext::getAtomicType(QualType T) const {
3659 // Unique pointers, to guarantee there is only one pointer of a particular
3660 // structure.
3661 llvm::FoldingSetNodeID ID;
3662 AtomicType::Profile(ID, T);
3663
3664 void *InsertPos = 0;
3665 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3666 return QualType(AT, 0);
3667
3668 // If the atomic value type isn't canonical, this won't be a canonical type
3669 // either, so fill in the canonical type field.
3670 QualType Canonical;
3671 if (!T.isCanonical()) {
3672 Canonical = getAtomicType(getCanonicalType(T));
3673
3674 // Get the new insert position for the node we care about.
3675 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3676 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3677 }
3678 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3679 Types.push_back(New);
3680 AtomicTypes.InsertNode(New, InsertPos);
3681 return QualType(New, 0);
3682}
3683
Richard Smithad762fc2011-04-14 22:09:26 +00003684/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3685QualType ASTContext::getAutoDeductType() const {
3686 if (AutoDeductTy.isNull())
Richard Smith60e141e2013-05-04 07:00:32 +00003687 AutoDeductTy = QualType(
3688 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
3689 /*dependent*/false),
3690 0);
Richard Smithad762fc2011-04-14 22:09:26 +00003691 return AutoDeductTy;
3692}
3693
3694/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3695QualType ASTContext::getAutoRRefDeductType() const {
3696 if (AutoRRefDeductTy.isNull())
3697 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3698 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3699 return AutoRRefDeductTy;
3700}
3701
Reid Spencer5f016e22007-07-11 17:01:13 +00003702/// getTagDeclType - Return the unique reference to the type for the
3703/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003704QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003705 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003706 // FIXME: What is the design on getTagDeclType when it requires casting
3707 // away const? mutable?
3708 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003709}
3710
Mike Stump1eb44332009-09-09 15:08:12 +00003711/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3712/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3713/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003714CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003715 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003716}
3717
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003718/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3719CanQualType ASTContext::getIntMaxType() const {
3720 return getFromTargetType(Target->getIntMaxType());
3721}
3722
3723/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3724CanQualType ASTContext::getUIntMaxType() const {
3725 return getFromTargetType(Target->getUIntMaxType());
3726}
3727
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003728/// getSignedWCharType - Return the type of "signed wchar_t".
3729/// Used when in C++, as a GCC extension.
3730QualType ASTContext::getSignedWCharType() const {
3731 // FIXME: derive from "Target" ?
3732 return WCharTy;
3733}
3734
3735/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3736/// Used when in C++, as a GCC extension.
3737QualType ASTContext::getUnsignedWCharType() const {
3738 // FIXME: derive from "Target" ?
3739 return UnsignedIntTy;
3740}
3741
Enea Zaffanella9677eb82013-01-26 17:08:37 +00003742QualType ASTContext::getIntPtrType() const {
3743 return getFromTargetType(Target->getIntPtrType());
3744}
3745
3746QualType ASTContext::getUIntPtrType() const {
3747 return getCorrespondingUnsignedType(getIntPtrType());
3748}
3749
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003750/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003751/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3752QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003753 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003754}
3755
Eli Friedman6902e412012-11-27 02:58:24 +00003756/// \brief Return the unique type for "pid_t" defined in
3757/// <sys/types.h>. We need this to compute the correct type for vfork().
3758QualType ASTContext::getProcessIDType() const {
3759 return getFromTargetType(Target->getProcessIDType());
3760}
3761
Chris Lattnere6327742008-04-02 05:18:44 +00003762//===----------------------------------------------------------------------===//
3763// Type Operators
3764//===----------------------------------------------------------------------===//
3765
Jay Foad4ba2a172011-01-12 09:06:06 +00003766CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003767 // Push qualifiers into arrays, and then discard any remaining
3768 // qualifiers.
3769 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003770 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003771 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003772 QualType Result;
3773 if (isa<ArrayType>(Ty)) {
3774 Result = getArrayDecayedType(QualType(Ty,0));
3775 } else if (isa<FunctionType>(Ty)) {
3776 Result = getPointerType(QualType(Ty, 0));
3777 } else {
3778 Result = QualType(Ty, 0);
3779 }
3780
3781 return CanQualType::CreateUnsafe(Result);
3782}
3783
John McCall62c28c82011-01-18 07:41:22 +00003784QualType ASTContext::getUnqualifiedArrayType(QualType type,
3785 Qualifiers &quals) {
3786 SplitQualType splitType = type.getSplitUnqualifiedType();
3787
3788 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3789 // the unqualified desugared type and then drops it on the floor.
3790 // We then have to strip that sugar back off with
3791 // getUnqualifiedDesugaredType(), which is silly.
3792 const ArrayType *AT =
John McCall200fa532012-02-08 00:46:36 +00003793 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall62c28c82011-01-18 07:41:22 +00003794
3795 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003796 if (!AT) {
John McCall200fa532012-02-08 00:46:36 +00003797 quals = splitType.Quals;
3798 return QualType(splitType.Ty, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003799 }
3800
John McCall62c28c82011-01-18 07:41:22 +00003801 // Otherwise, recurse on the array's element type.
3802 QualType elementType = AT->getElementType();
3803 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3804
3805 // If that didn't change the element type, AT has no qualifiers, so we
3806 // can just use the results in splitType.
3807 if (elementType == unqualElementType) {
3808 assert(quals.empty()); // from the recursive call
John McCall200fa532012-02-08 00:46:36 +00003809 quals = splitType.Quals;
3810 return QualType(splitType.Ty, 0);
John McCall62c28c82011-01-18 07:41:22 +00003811 }
3812
3813 // Otherwise, add in the qualifiers from the outermost type, then
3814 // build the type back up.
John McCall200fa532012-02-08 00:46:36 +00003815 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003816
Douglas Gregor9dadd942010-05-17 18:45:21 +00003817 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003818 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003819 CAT->getSizeModifier(), 0);
3820 }
3821
Douglas Gregor9dadd942010-05-17 18:45:21 +00003822 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003823 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003824 }
3825
Douglas Gregor9dadd942010-05-17 18:45:21 +00003826 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003827 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003828 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003829 VAT->getSizeModifier(),
3830 VAT->getIndexTypeCVRQualifiers(),
3831 VAT->getBracketsRange());
3832 }
3833
3834 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003835 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003836 DSAT->getSizeModifier(), 0,
3837 SourceRange());
3838}
3839
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003840/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3841/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3842/// they point to and return true. If T1 and T2 aren't pointer types
3843/// or pointer-to-member types, or if they are not similar at this
3844/// level, returns false and leaves T1 and T2 unchanged. Top-level
3845/// qualifiers on T1 and T2 are ignored. This function will typically
3846/// be called in a loop that successively "unwraps" pointer and
3847/// pointer-to-member types to compare them at each level.
3848bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3849 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3850 *T2PtrType = T2->getAs<PointerType>();
3851 if (T1PtrType && T2PtrType) {
3852 T1 = T1PtrType->getPointeeType();
3853 T2 = T2PtrType->getPointeeType();
3854 return true;
3855 }
3856
3857 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3858 *T2MPType = T2->getAs<MemberPointerType>();
3859 if (T1MPType && T2MPType &&
3860 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3861 QualType(T2MPType->getClass(), 0))) {
3862 T1 = T1MPType->getPointeeType();
3863 T2 = T2MPType->getPointeeType();
3864 return true;
3865 }
3866
David Blaikie4e4d0842012-03-11 07:00:24 +00003867 if (getLangOpts().ObjC1) {
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003868 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3869 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3870 if (T1OPType && T2OPType) {
3871 T1 = T1OPType->getPointeeType();
3872 T2 = T2OPType->getPointeeType();
3873 return true;
3874 }
3875 }
3876
3877 // FIXME: Block pointers, too?
3878
3879 return false;
3880}
3881
Jay Foad4ba2a172011-01-12 09:06:06 +00003882DeclarationNameInfo
3883ASTContext::getNameForTemplate(TemplateName Name,
3884 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003885 switch (Name.getKind()) {
3886 case TemplateName::QualifiedTemplate:
3887 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003888 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003889 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3890 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003891
John McCall14606042011-06-30 08:33:18 +00003892 case TemplateName::OverloadedTemplate: {
3893 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3894 // DNInfo work in progress: CHECKME: what about DNLoc?
3895 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3896 }
3897
3898 case TemplateName::DependentTemplate: {
3899 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003900 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003901 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003902 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3903 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003904 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003905 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3906 // DNInfo work in progress: FIXME: source locations?
3907 DeclarationNameLoc DNLoc;
3908 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3909 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3910 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003911 }
3912 }
3913
John McCall14606042011-06-30 08:33:18 +00003914 case TemplateName::SubstTemplateTemplateParm: {
3915 SubstTemplateTemplateParmStorage *subst
3916 = Name.getAsSubstTemplateTemplateParm();
3917 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3918 NameLoc);
3919 }
3920
3921 case TemplateName::SubstTemplateTemplateParmPack: {
3922 SubstTemplateTemplateParmPackStorage *subst
3923 = Name.getAsSubstTemplateTemplateParmPack();
3924 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3925 NameLoc);
3926 }
3927 }
3928
3929 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003930}
3931
Jay Foad4ba2a172011-01-12 09:06:06 +00003932TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003933 switch (Name.getKind()) {
3934 case TemplateName::QualifiedTemplate:
3935 case TemplateName::Template: {
3936 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003937 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003938 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003939 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3940
3941 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003942 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003943 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003944
John McCall14606042011-06-30 08:33:18 +00003945 case TemplateName::OverloadedTemplate:
3946 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003947
John McCall14606042011-06-30 08:33:18 +00003948 case TemplateName::DependentTemplate: {
3949 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3950 assert(DTN && "Non-dependent template names must refer to template decls.");
3951 return DTN->CanonicalTemplateName;
3952 }
3953
3954 case TemplateName::SubstTemplateTemplateParm: {
3955 SubstTemplateTemplateParmStorage *subst
3956 = Name.getAsSubstTemplateTemplateParm();
3957 return getCanonicalTemplateName(subst->getReplacement());
3958 }
3959
3960 case TemplateName::SubstTemplateTemplateParmPack: {
3961 SubstTemplateTemplateParmPackStorage *subst
3962 = Name.getAsSubstTemplateTemplateParmPack();
3963 TemplateTemplateParmDecl *canonParameter
3964 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3965 TemplateArgument canonArgPack
3966 = getCanonicalTemplateArgument(subst->getArgumentPack());
3967 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3968 }
3969 }
3970
3971 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003972}
3973
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003974bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3975 X = getCanonicalTemplateName(X);
3976 Y = getCanonicalTemplateName(Y);
3977 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3978}
3979
Mike Stump1eb44332009-09-09 15:08:12 +00003980TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003981ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003982 switch (Arg.getKind()) {
3983 case TemplateArgument::Null:
3984 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003985
Douglas Gregor1275ae02009-07-28 23:00:59 +00003986 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003987 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003988
Douglas Gregord2008e22012-04-06 22:40:38 +00003989 case TemplateArgument::Declaration: {
Eli Friedmand7a6b162012-09-26 02:36:12 +00003990 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
3991 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregord2008e22012-04-06 22:40:38 +00003992 }
Mike Stump1eb44332009-09-09 15:08:12 +00003993
Eli Friedmand7a6b162012-09-26 02:36:12 +00003994 case TemplateArgument::NullPtr:
3995 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
3996 /*isNullPtr*/true);
3997
Douglas Gregor788cd062009-11-11 01:00:40 +00003998 case TemplateArgument::Template:
3999 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00004000
4001 case TemplateArgument::TemplateExpansion:
4002 return TemplateArgument(getCanonicalTemplateName(
4003 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00004004 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00004005
Douglas Gregor1275ae02009-07-28 23:00:59 +00004006 case TemplateArgument::Integral:
Benjamin Kramer85524372012-06-07 15:09:51 +00004007 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00004008
Douglas Gregor1275ae02009-07-28 23:00:59 +00004009 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00004010 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00004011
Douglas Gregor1275ae02009-07-28 23:00:59 +00004012 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00004013 if (Arg.pack_size() == 0)
4014 return Arg;
4015
Douglas Gregor910f8002010-11-07 23:05:16 +00004016 TemplateArgument *CanonArgs
4017 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00004018 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004019 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00004020 AEnd = Arg.pack_end();
4021 A != AEnd; (void)++A, ++Idx)
4022 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00004023
Douglas Gregor910f8002010-11-07 23:05:16 +00004024 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00004025 }
4026 }
4027
4028 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00004029 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00004030}
4031
Douglas Gregord57959a2009-03-27 23:10:48 +00004032NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00004033ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004034 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00004035 return 0;
4036
4037 switch (NNS->getKind()) {
4038 case NestedNameSpecifier::Identifier:
4039 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00004040 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00004041 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4042 NNS->getAsIdentifier());
4043
4044 case NestedNameSpecifier::Namespace:
4045 // A namespace is canonical; build a nested-name-specifier with
4046 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00004047 return NestedNameSpecifier::Create(*this, 0,
4048 NNS->getAsNamespace()->getOriginalNamespace());
4049
4050 case NestedNameSpecifier::NamespaceAlias:
4051 // A namespace is canonical; build a nested-name-specifier with
4052 // this namespace and no prefix.
4053 return NestedNameSpecifier::Create(*this, 0,
4054 NNS->getAsNamespaceAlias()->getNamespace()
4055 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00004056
4057 case NestedNameSpecifier::TypeSpec:
4058 case NestedNameSpecifier::TypeSpecWithTemplate: {
4059 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00004060
4061 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4062 // break it apart into its prefix and identifier, then reconsititute those
4063 // as the canonical nested-name-specifier. This is required to canonicalize
4064 // a dependent nested-name-specifier involving typedefs of dependent-name
4065 // types, e.g.,
4066 // typedef typename T::type T1;
4067 // typedef typename T1::type T2;
Eli Friedman16412ef2012-03-03 04:09:56 +00004068 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4069 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor264bf662010-11-04 00:09:33 +00004070 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor264bf662010-11-04 00:09:33 +00004071
Eli Friedman16412ef2012-03-03 04:09:56 +00004072 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4073 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4074 // first place?
John McCall3b657512011-01-19 10:06:00 +00004075 return NestedNameSpecifier::Create(*this, 0, false,
4076 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00004077 }
4078
4079 case NestedNameSpecifier::Global:
4080 // The global specifier is canonical and unique.
4081 return NNS;
4082 }
4083
David Blaikie7530c032012-01-17 06:56:22 +00004084 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregord57959a2009-03-27 23:10:48 +00004085}
4086
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004087
Jay Foad4ba2a172011-01-12 09:06:06 +00004088const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004089 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004090 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004091 // Handle the common positive case fast.
4092 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4093 return AT;
4094 }
Mike Stump1eb44332009-09-09 15:08:12 +00004095
John McCall0953e762009-09-24 19:53:00 +00004096 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00004097 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004098 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004099
John McCall0953e762009-09-24 19:53:00 +00004100 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004101 // implements C99 6.7.3p8: "If the specification of an array type includes
4102 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00004103
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004104 // If we get here, we either have type qualifiers on the type, or we have
4105 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00004106 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00004107
John McCall3b657512011-01-19 10:06:00 +00004108 SplitQualType split = T.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004109 Qualifiers qs = split.Quals;
Mike Stump1eb44332009-09-09 15:08:12 +00004110
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004111 // If we have a simple case, just return now.
John McCall200fa532012-02-08 00:46:36 +00004112 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall3b657512011-01-19 10:06:00 +00004113 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004114 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00004115
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004116 // Otherwise, we have an array and we have qualifiers on it. Push the
4117 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00004118 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00004119
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004120 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4121 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4122 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004123 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004124 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4125 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4126 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004127 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00004128
Mike Stump1eb44332009-09-09 15:08:12 +00004129 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00004130 = dyn_cast<DependentSizedArrayType>(ATy))
4131 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00004132 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00004133 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00004134 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004135 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004136 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00004137
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004138 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004139 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00004140 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004141 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004142 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004143 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00004144}
4145
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004146QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner12df2462013-06-24 17:51:48 +00004147 if (T->isArrayType() || T->isFunctionType())
4148 return getDecayedType(T);
4149 return T;
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004150}
4151
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004152QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004153 T = getVariableArrayDecayedType(T);
4154 T = getAdjustedParameterType(T);
4155 return T.getUnqualifiedType();
4156}
4157
Chris Lattnere6327742008-04-02 05:18:44 +00004158/// getArrayDecayedType - Return the properly qualified result of decaying the
4159/// specified array type to a pointer. This operation is non-trivial when
4160/// handling typedefs etc. The canonical type of "T" must be an array type,
4161/// this returns a pointer to a properly qualified element of the array.
4162///
4163/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00004164QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004165 // Get the element type with 'getAsArrayType' so that we don't lose any
4166 // typedefs in the element type of the array. This also handles propagation
4167 // of type qualifiers from the array type into the element type if present
4168 // (C99 6.7.3p8).
4169 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4170 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00004171
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004172 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00004173
4174 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00004175 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00004176}
4177
John McCall3b657512011-01-19 10:06:00 +00004178QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4179 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00004180}
4181
John McCall3b657512011-01-19 10:06:00 +00004182QualType ASTContext::getBaseElementType(QualType type) const {
4183 Qualifiers qs;
4184 while (true) {
4185 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004186 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall3b657512011-01-19 10:06:00 +00004187 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00004188
John McCall3b657512011-01-19 10:06:00 +00004189 type = array->getElementType();
John McCall200fa532012-02-08 00:46:36 +00004190 qs.addConsistentQualifiers(split.Quals);
John McCall3b657512011-01-19 10:06:00 +00004191 }
Mike Stump1eb44332009-09-09 15:08:12 +00004192
John McCall3b657512011-01-19 10:06:00 +00004193 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00004194}
4195
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004196/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00004197uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004198ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4199 uint64_t ElementCount = 1;
4200 do {
4201 ElementCount *= CA->getSize().getZExtValue();
Richard Smithd5e83942012-12-06 03:04:50 +00004202 CA = dyn_cast_or_null<ConstantArrayType>(
4203 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004204 } while (CA);
4205 return ElementCount;
4206}
4207
Reid Spencer5f016e22007-07-11 17:01:13 +00004208/// getFloatingRank - Return a relative rank for floating point types.
4209/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00004210static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00004211 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00004212 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00004213
John McCall183700f2009-09-21 23:43:11 +00004214 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4215 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004216 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00004217 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00004218 case BuiltinType::Float: return FloatRank;
4219 case BuiltinType::Double: return DoubleRank;
4220 case BuiltinType::LongDouble: return LongDoubleRank;
4221 }
4222}
4223
Mike Stump1eb44332009-09-09 15:08:12 +00004224/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4225/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00004226/// 'typeDomain' is a real floating point or complex type.
4227/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00004228QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4229 QualType Domain) const {
4230 FloatingRank EltRank = getFloatingRank(Size);
4231 if (Domain->isComplexType()) {
4232 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00004233 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Narofff1448a02007-08-27 01:27:54 +00004234 case FloatRank: return FloatComplexTy;
4235 case DoubleRank: return DoubleComplexTy;
4236 case LongDoubleRank: return LongDoubleComplexTy;
4237 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004238 }
Chris Lattner1361b112008-04-06 23:58:54 +00004239
4240 assert(Domain->isRealFloatingType() && "Unknown domain!");
4241 switch (EltRank) {
Joey Gouly19dbb202013-01-23 11:56:20 +00004242 case HalfRank: return HalfTy;
Chris Lattner1361b112008-04-06 23:58:54 +00004243 case FloatRank: return FloatTy;
4244 case DoubleRank: return DoubleTy;
4245 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00004246 }
David Blaikie561d3ab2012-01-17 02:30:50 +00004247 llvm_unreachable("getFloatingRank(): illegal value for rank");
Reid Spencer5f016e22007-07-11 17:01:13 +00004248}
4249
Chris Lattner7cfeb082008-04-06 23:55:33 +00004250/// getFloatingTypeOrder - Compare the rank of the two specified floating
4251/// point types, ignoring the domain of the type (i.e. 'double' ==
4252/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004253/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004254int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00004255 FloatingRank LHSR = getFloatingRank(LHS);
4256 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004257
Chris Lattnera75cea32008-04-06 23:38:49 +00004258 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004259 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00004260 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004261 return 1;
4262 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004263}
4264
Chris Lattnerf52ab252008-04-06 22:59:24 +00004265/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4266/// routine will assert if passed a built-in type that isn't an integer or enum,
4267/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00004268unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00004269 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00004270
Chris Lattnerf52ab252008-04-06 22:59:24 +00004271 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004272 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00004273 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004274 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004275 case BuiltinType::Char_S:
4276 case BuiltinType::Char_U:
4277 case BuiltinType::SChar:
4278 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004279 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004280 case BuiltinType::Short:
4281 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004282 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004283 case BuiltinType::Int:
4284 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004285 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004286 case BuiltinType::Long:
4287 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004288 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004289 case BuiltinType::LongLong:
4290 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004291 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00004292 case BuiltinType::Int128:
4293 case BuiltinType::UInt128:
4294 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00004295 }
4296}
4297
Eli Friedman04e83572009-08-20 04:21:42 +00004298/// \brief Whether this is a promotable bitfield reference according
4299/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4300///
4301/// \returns the type this bit-field will promote to, or NULL if no
4302/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00004303QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00004304 if (E->isTypeDependent() || E->isValueDependent())
4305 return QualType();
4306
John McCall993f43f2013-05-06 21:39:12 +00004307 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman04e83572009-08-20 04:21:42 +00004308 if (!Field)
4309 return QualType();
4310
4311 QualType FT = Field->getType();
4312
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004313 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00004314 uint64_t IntSize = getTypeSize(IntTy);
4315 // GCC extension compatibility: if the bit-field size is less than or equal
4316 // to the size of int, it gets promoted no matter what its type is.
4317 // For instance, unsigned long bf : 4 gets promoted to signed int.
4318 if (BitWidth < IntSize)
4319 return IntTy;
4320
4321 if (BitWidth == IntSize)
4322 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4323
4324 // Types bigger than int are not subject to promotions, and therefore act
4325 // like the base type.
4326 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4327 // is ridiculous.
4328 return QualType();
4329}
4330
Eli Friedmana95d7572009-08-19 07:44:53 +00004331/// getPromotedIntegerType - Returns the type that Promotable will
4332/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4333/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00004334QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00004335 assert(!Promotable.isNull());
4336 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00004337 if (const EnumType *ET = Promotable->getAs<EnumType>())
4338 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00004339
4340 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4341 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4342 // (3.9.1) can be converted to a prvalue of the first of the following
4343 // types that can represent all the values of its underlying type:
4344 // int, unsigned int, long int, unsigned long int, long long int, or
4345 // unsigned long long int [...]
4346 // FIXME: Is there some better way to compute this?
4347 if (BT->getKind() == BuiltinType::WChar_S ||
4348 BT->getKind() == BuiltinType::WChar_U ||
4349 BT->getKind() == BuiltinType::Char16 ||
4350 BT->getKind() == BuiltinType::Char32) {
4351 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4352 uint64_t FromSize = getTypeSize(BT);
4353 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4354 LongLongTy, UnsignedLongLongTy };
4355 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4356 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4357 if (FromSize < ToSize ||
4358 (FromSize == ToSize &&
4359 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4360 return PromoteTypes[Idx];
4361 }
4362 llvm_unreachable("char type should fit into long long");
4363 }
4364 }
4365
4366 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00004367 if (Promotable->isSignedIntegerType())
4368 return IntTy;
Eli Friedman5b64e772012-11-15 01:21:59 +00004369 uint64_t PromotableSize = getIntWidth(Promotable);
4370 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedmana95d7572009-08-19 07:44:53 +00004371 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4372 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4373}
4374
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004375/// \brief Recurses in pointer/array types until it finds an objc retainable
4376/// type and returns its ownership.
4377Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4378 while (!T.isNull()) {
4379 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4380 return T.getObjCLifetime();
4381 if (T->isArrayType())
4382 T = getBaseElementType(T);
4383 else if (const PointerType *PT = T->getAs<PointerType>())
4384 T = PT->getPointeeType();
4385 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00004386 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004387 else
4388 break;
4389 }
4390
4391 return Qualifiers::OCL_None;
4392}
4393
Mike Stump1eb44332009-09-09 15:08:12 +00004394/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00004395/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004396/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004397int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00004398 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4399 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00004400 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004401
Chris Lattnerf52ab252008-04-06 22:59:24 +00004402 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4403 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00004404
Chris Lattner7cfeb082008-04-06 23:55:33 +00004405 unsigned LHSRank = getIntegerRank(LHSC);
4406 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00004407
Chris Lattner7cfeb082008-04-06 23:55:33 +00004408 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4409 if (LHSRank == RHSRank) return 0;
4410 return LHSRank > RHSRank ? 1 : -1;
4411 }
Mike Stump1eb44332009-09-09 15:08:12 +00004412
Chris Lattner7cfeb082008-04-06 23:55:33 +00004413 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4414 if (LHSUnsigned) {
4415 // If the unsigned [LHS] type is larger, return it.
4416 if (LHSRank >= RHSRank)
4417 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004418
Chris Lattner7cfeb082008-04-06 23:55:33 +00004419 // If the signed type can represent all values of the unsigned type, it
4420 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004421 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004422 return -1;
4423 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00004424
Chris Lattner7cfeb082008-04-06 23:55:33 +00004425 // If the unsigned [RHS] type is larger, return it.
4426 if (RHSRank >= LHSRank)
4427 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00004428
Chris Lattner7cfeb082008-04-06 23:55:33 +00004429 // If the signed type can represent all values of the unsigned type, it
4430 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004431 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004432 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004433}
Anders Carlsson71993dd2007-08-17 05:31:46 +00004434
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004435static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004436CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4437 DeclContext *DC, IdentifierInfo *Id) {
4438 SourceLocation Loc;
David Blaikie4e4d0842012-03-11 07:00:24 +00004439 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004440 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004441 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004442 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004443}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004444
Mike Stump1eb44332009-09-09 15:08:12 +00004445// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00004446QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00004447 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004448 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004449 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004450 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00004451 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004452
Anders Carlssonf06273f2007-11-19 00:25:30 +00004453 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00004454
Anders Carlsson71993dd2007-08-17 05:31:46 +00004455 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00004456 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00004457 // int flags;
4458 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00004459 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00004460 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00004461 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00004462 FieldTypes[3] = LongTy;
4463
Anders Carlsson71993dd2007-08-17 05:31:46 +00004464 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00004465 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00004466 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004467 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00004468 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00004469 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00004470 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004471 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004472 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004473 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004474 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00004475 }
4476
Douglas Gregor838db382010-02-11 01:19:42 +00004477 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00004478 }
Mike Stump1eb44332009-09-09 15:08:12 +00004479
Anders Carlsson71993dd2007-08-17 05:31:46 +00004480 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00004481}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004482
Fariborz Jahanianf7992132013-01-04 18:45:40 +00004483QualType ASTContext::getObjCSuperType() const {
4484 if (ObjCSuperType.isNull()) {
4485 RecordDecl *ObjCSuperTypeDecl =
4486 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4487 TUDecl->addDecl(ObjCSuperTypeDecl);
4488 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4489 }
4490 return ObjCSuperType;
4491}
4492
Douglas Gregor319ac892009-04-23 22:29:11 +00004493void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004494 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00004495 assert(Rec && "Invalid CFConstantStringType");
4496 CFConstantStringTypeDecl = Rec->getDecl();
4497}
4498
Jay Foad4ba2a172011-01-12 09:06:06 +00004499QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00004500 if (BlockDescriptorType)
4501 return getTagDeclType(BlockDescriptorType);
4502
4503 RecordDecl *T;
4504 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004505 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004506 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00004507 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004508
4509 QualType FieldTypes[] = {
4510 UnsignedLongTy,
4511 UnsignedLongTy,
4512 };
4513
Craig Topper3aa29df2013-07-15 08:24:27 +00004514 static const char *const FieldNames[] = {
Mike Stumpadaaad32009-10-20 02:12:22 +00004515 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00004516 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00004517 };
4518
4519 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004520 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00004521 SourceLocation(),
4522 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004523 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00004524 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004525 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004526 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004527 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00004528 T->addDecl(Field);
4529 }
4530
Douglas Gregor838db382010-02-11 01:19:42 +00004531 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004532
4533 BlockDescriptorType = T;
4534
4535 return getTagDeclType(BlockDescriptorType);
4536}
4537
Jay Foad4ba2a172011-01-12 09:06:06 +00004538QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00004539 if (BlockDescriptorExtendedType)
4540 return getTagDeclType(BlockDescriptorExtendedType);
4541
4542 RecordDecl *T;
4543 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004544 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004545 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00004546 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004547
4548 QualType FieldTypes[] = {
4549 UnsignedLongTy,
4550 UnsignedLongTy,
4551 getPointerType(VoidPtrTy),
4552 getPointerType(VoidPtrTy)
4553 };
4554
Craig Topper3aa29df2013-07-15 08:24:27 +00004555 static const char *const FieldNames[] = {
Mike Stump083c25e2009-10-22 00:49:09 +00004556 "reserved",
4557 "Size",
4558 "CopyFuncPtr",
4559 "DestroyFuncPtr"
4560 };
4561
4562 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004563 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00004564 SourceLocation(),
4565 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004566 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00004567 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004568 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004569 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004570 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00004571 T->addDecl(Field);
4572 }
4573
Douglas Gregor838db382010-02-11 01:19:42 +00004574 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004575
4576 BlockDescriptorExtendedType = T;
4577
4578 return getTagDeclType(BlockDescriptorExtendedType);
4579}
4580
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004581/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4582/// requires copy/dispose. Note that this must match the logic
4583/// in buildByrefHelpers.
4584bool ASTContext::BlockRequiresCopying(QualType Ty,
4585 const VarDecl *D) {
4586 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4587 const Expr *copyExpr = getBlockVarCopyInits(D);
4588 if (!copyExpr && record->hasTrivialDestructor()) return false;
4589
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004590 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00004591 }
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004592
4593 if (!Ty->isObjCRetainableType()) return false;
4594
4595 Qualifiers qs = Ty.getQualifiers();
4596
4597 // If we have lifetime, that dominates.
4598 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4599 assert(getLangOpts().ObjCAutoRefCount);
4600
4601 switch (lifetime) {
4602 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4603
4604 // These are just bits as far as the runtime is concerned.
4605 case Qualifiers::OCL_ExplicitNone:
4606 case Qualifiers::OCL_Autoreleasing:
4607 return false;
4608
4609 // Tell the runtime that this is ARC __weak, called by the
4610 // byref routines.
4611 case Qualifiers::OCL_Weak:
4612 // ARC __strong __block variables need to be retained.
4613 case Qualifiers::OCL_Strong:
4614 return true;
4615 }
4616 llvm_unreachable("fell out of lifetime switch!");
4617 }
4618 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4619 Ty->isObjCObjectPointerType());
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004620}
4621
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004622bool ASTContext::getByrefLifetime(QualType Ty,
4623 Qualifiers::ObjCLifetime &LifeTime,
4624 bool &HasByrefExtendedLayout) const {
4625
4626 if (!getLangOpts().ObjC1 ||
4627 getLangOpts().getGC() != LangOptions::NonGC)
4628 return false;
4629
4630 HasByrefExtendedLayout = false;
Fariborz Jahanian34db84f2012-12-11 19:58:01 +00004631 if (Ty->isRecordType()) {
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004632 HasByrefExtendedLayout = true;
4633 LifeTime = Qualifiers::OCL_None;
4634 }
4635 else if (getLangOpts().ObjCAutoRefCount)
4636 LifeTime = Ty.getObjCLifetime();
4637 // MRR.
4638 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4639 LifeTime = Qualifiers::OCL_ExplicitNone;
4640 else
4641 LifeTime = Qualifiers::OCL_None;
4642 return true;
4643}
4644
Douglas Gregore97179c2011-09-08 01:46:34 +00004645TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4646 if (!ObjCInstanceTypeDecl)
4647 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4648 getTranslationUnitDecl(),
4649 SourceLocation(),
4650 SourceLocation(),
4651 &Idents.get("instancetype"),
4652 getTrivialTypeSourceInfo(getObjCIdType()));
4653 return ObjCInstanceTypeDecl;
4654}
4655
Anders Carlssone8c49532007-10-29 06:33:42 +00004656// This returns true if a type has been typedefed to BOOL:
4657// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00004658static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00004659 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00004660 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4661 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00004662
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004663 return false;
4664}
4665
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004666/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004667/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00004668CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00004669 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4670 return CharUnits::Zero();
4671
Ken Dyck199c3d62010-01-11 17:06:35 +00004672 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004673
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004674 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004675 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004676 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004677 // Treat arrays as pointers, since that's how they're passed in.
4678 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004679 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004680 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004681}
4682
4683static inline
4684std::string charUnitsToString(const CharUnits &CU) {
4685 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004686}
4687
John McCall6b5a61b2011-02-07 10:33:21 +00004688/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004689/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004690std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4691 std::string S;
4692
David Chisnall5e530af2009-11-17 19:33:30 +00004693 const BlockDecl *Decl = Expr->getBlockDecl();
4694 QualType BlockTy =
4695 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4696 // Encode result type.
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004697 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004698 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4699 BlockTy->getAs<FunctionType>()->getResultType(),
4700 S, true /*Extended*/);
4701 else
4702 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4703 S);
David Chisnall5e530af2009-11-17 19:33:30 +00004704 // Compute size of all parameters.
4705 // Start with computing size of a pointer in number of bytes.
4706 // FIXME: There might(should) be a better way of doing this computation!
4707 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004708 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4709 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004710 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004711 E = Decl->param_end(); PI != E; ++PI) {
4712 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004713 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahanian075a5432012-06-30 00:48:59 +00004714 if (sz.isZero())
4715 continue;
Ken Dyck199c3d62010-01-11 17:06:35 +00004716 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004717 ParmOffset += sz;
4718 }
4719 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004720 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004721 // Block pointer and offset.
4722 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004723
4724 // Argument types.
4725 ParmOffset = PtrSize;
4726 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4727 Decl->param_end(); PI != E; ++PI) {
4728 ParmVarDecl *PVDecl = *PI;
4729 QualType PType = PVDecl->getOriginalType();
4730 if (const ArrayType *AT =
4731 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4732 // Use array's original type only if it has known number of
4733 // elements.
4734 if (!isa<ConstantArrayType>(AT))
4735 PType = PVDecl->getType();
4736 } else if (PType->isFunctionType())
4737 PType = PVDecl->getType();
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004738 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004739 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4740 S, true /*Extended*/);
4741 else
4742 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004743 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004744 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004745 }
John McCall6b5a61b2011-02-07 10:33:21 +00004746
4747 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004748}
4749
Douglas Gregorf968d832011-05-27 01:19:52 +00004750bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004751 std::string& S) {
4752 // Encode result type.
4753 getObjCEncodingForType(Decl->getResultType(), S);
4754 CharUnits ParmOffset;
4755 // Compute size of all parameters.
4756 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4757 E = Decl->param_end(); PI != E; ++PI) {
4758 QualType PType = (*PI)->getType();
4759 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004760 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004761 continue;
4762
David Chisnall5389f482010-12-30 14:05:53 +00004763 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004764 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004765 ParmOffset += sz;
4766 }
4767 S += charUnitsToString(ParmOffset);
4768 ParmOffset = CharUnits::Zero();
4769
4770 // Argument types.
4771 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4772 E = Decl->param_end(); PI != E; ++PI) {
4773 ParmVarDecl *PVDecl = *PI;
4774 QualType PType = PVDecl->getOriginalType();
4775 if (const ArrayType *AT =
4776 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4777 // Use array's original type only if it has known number of
4778 // elements.
4779 if (!isa<ConstantArrayType>(AT))
4780 PType = PVDecl->getType();
4781 } else if (PType->isFunctionType())
4782 PType = PVDecl->getType();
4783 getObjCEncodingForType(PType, S);
4784 S += charUnitsToString(ParmOffset);
4785 ParmOffset += getObjCEncodingTypeSize(PType);
4786 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004787
4788 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004789}
4790
Bob Wilsondc8dab62011-11-30 01:57:58 +00004791/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4792/// method parameter or return type. If Extended, include class names and
4793/// block object types.
4794void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4795 QualType T, std::string& S,
4796 bool Extended) const {
4797 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4798 getObjCEncodingForTypeQualifier(QT, S);
4799 // Encode parameter type.
4800 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4801 true /*OutermostType*/,
4802 false /*EncodingProperty*/,
4803 false /*StructField*/,
4804 Extended /*EncodeBlockParameters*/,
4805 Extended /*EncodeClassNames*/);
4806}
4807
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004808/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004809/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004810bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004811 std::string& S,
4812 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004813 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004814 // Encode return type.
4815 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4816 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004817 // Compute size of all parameters.
4818 // Start with computing size of a pointer in number of bytes.
4819 // FIXME: There might(should) be a better way of doing this computation!
4820 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004821 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004822 // The first two arguments (self and _cmd) are pointers; account for
4823 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004824 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004825 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004826 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004827 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004828 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004829 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004830 continue;
4831
Ken Dyck199c3d62010-01-11 17:06:35 +00004832 assert (sz.isPositive() &&
4833 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004834 ParmOffset += sz;
4835 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004836 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004837 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004838 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004839
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004840 // Argument types.
4841 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004842 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004843 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004844 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004845 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004846 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004847 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4848 // Use array's original type only if it has known number of
4849 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004850 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004851 PType = PVDecl->getType();
4852 } else if (PType->isFunctionType())
4853 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004854 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4855 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004856 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004857 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004858 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004859
4860 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004861}
4862
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004863/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004864/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004865/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4866/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004867/// Property attributes are stored as a comma-delimited C string. The simple
4868/// attributes readonly and bycopy are encoded as single characters. The
4869/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4870/// encoded as single characters, followed by an identifier. Property types
4871/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004872/// these attributes are defined by the following enumeration:
4873/// @code
4874/// enum PropertyAttributes {
4875/// kPropertyReadOnly = 'R', // property is read-only.
4876/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4877/// kPropertyByref = '&', // property is a reference to the value last assigned
4878/// kPropertyDynamic = 'D', // property is dynamic
4879/// kPropertyGetter = 'G', // followed by getter selector name
4880/// kPropertySetter = 'S', // followed by setter selector name
4881/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson0d4cb852012-03-22 17:48:02 +00004882/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004883/// kPropertyWeak = 'W' // 'weak' property
4884/// kPropertyStrong = 'P' // property GC'able
4885/// kPropertyNonAtomic = 'N' // property non-atomic
4886/// };
4887/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004888void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004889 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004890 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004891 // Collect information from the property implementation decl(s).
4892 bool Dynamic = false;
4893 ObjCPropertyImplDecl *SynthesizePID = 0;
4894
4895 // FIXME: Duplicated code due to poor abstraction.
4896 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004897 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004898 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4899 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004900 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004901 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004902 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004903 if (PID->getPropertyDecl() == PD) {
4904 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4905 Dynamic = true;
4906 } else {
4907 SynthesizePID = PID;
4908 }
4909 }
4910 }
4911 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004912 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004913 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004914 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004915 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004916 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004917 if (PID->getPropertyDecl() == PD) {
4918 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4919 Dynamic = true;
4920 } else {
4921 SynthesizePID = PID;
4922 }
4923 }
Mike Stump1eb44332009-09-09 15:08:12 +00004924 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004925 }
4926 }
4927
4928 // FIXME: This is not very efficient.
4929 S = "T";
4930
4931 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004932 // GCC has some special rules regarding encoding of properties which
4933 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004934 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004935 true /* outermost type */,
4936 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004937
4938 if (PD->isReadOnly()) {
4939 S += ",R";
Nico Weberd7ceab32013-05-08 23:47:40 +00004940 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
4941 S += ",C";
4942 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
4943 S += ",&";
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004944 } else {
4945 switch (PD->getSetterKind()) {
4946 case ObjCPropertyDecl::Assign: break;
4947 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004948 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004949 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004950 }
4951 }
4952
4953 // It really isn't clear at all what this means, since properties
4954 // are "dynamic by default".
4955 if (Dynamic)
4956 S += ",D";
4957
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004958 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4959 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004960
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004961 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4962 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004963 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004964 }
4965
4966 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4967 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004968 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004969 }
4970
4971 if (SynthesizePID) {
4972 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4973 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004974 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004975 }
4976
4977 // FIXME: OBJCGC: weak & strong
4978}
4979
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004980/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004981/// Another legacy compatibility encoding: 32-bit longs are encoded as
4982/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004983/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4984///
4985void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004986 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004987 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004988 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004989 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004990 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004991 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004992 PointeeTy = IntTy;
4993 }
4994 }
4995}
4996
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004997void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00004998 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004999 // We follow the behavior of gcc, expanding structures which are
5000 // directly pointed to, and expanding embedded structures. Note that
5001 // these rules are sufficient to prevent recursive encoding of the
5002 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00005003 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00005004 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005005}
5006
John McCall3624e9e2012-12-20 02:45:14 +00005007static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5008 BuiltinType::Kind kind) {
5009 switch (kind) {
David Chisnall64fd7e82010-06-04 01:10:52 +00005010 case BuiltinType::Void: return 'v';
5011 case BuiltinType::Bool: return 'B';
5012 case BuiltinType::Char_U:
5013 case BuiltinType::UChar: return 'C';
John McCall3624e9e2012-12-20 02:45:14 +00005014 case BuiltinType::Char16:
David Chisnall64fd7e82010-06-04 01:10:52 +00005015 case BuiltinType::UShort: return 'S';
John McCall3624e9e2012-12-20 02:45:14 +00005016 case BuiltinType::Char32:
David Chisnall64fd7e82010-06-04 01:10:52 +00005017 case BuiltinType::UInt: return 'I';
5018 case BuiltinType::ULong:
John McCall3624e9e2012-12-20 02:45:14 +00005019 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00005020 case BuiltinType::UInt128: return 'T';
5021 case BuiltinType::ULongLong: return 'Q';
5022 case BuiltinType::Char_S:
5023 case BuiltinType::SChar: return 'c';
5024 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00005025 case BuiltinType::WChar_S:
5026 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00005027 case BuiltinType::Int: return 'i';
5028 case BuiltinType::Long:
John McCall3624e9e2012-12-20 02:45:14 +00005029 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00005030 case BuiltinType::LongLong: return 'q';
5031 case BuiltinType::Int128: return 't';
5032 case BuiltinType::Float: return 'f';
5033 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00005034 case BuiltinType::LongDouble: return 'D';
John McCall3624e9e2012-12-20 02:45:14 +00005035 case BuiltinType::NullPtr: return '*'; // like char*
5036
5037 case BuiltinType::Half:
5038 // FIXME: potentially need @encodes for these!
5039 return ' ';
5040
5041 case BuiltinType::ObjCId:
5042 case BuiltinType::ObjCClass:
5043 case BuiltinType::ObjCSel:
5044 llvm_unreachable("@encoding ObjC primitive type");
5045
5046 // OpenCL and placeholder types don't need @encodings.
5047 case BuiltinType::OCLImage1d:
5048 case BuiltinType::OCLImage1dArray:
5049 case BuiltinType::OCLImage1dBuffer:
5050 case BuiltinType::OCLImage2d:
5051 case BuiltinType::OCLImage2dArray:
5052 case BuiltinType::OCLImage3d:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005053 case BuiltinType::OCLEvent:
Guy Benyei21f18c42013-02-07 10:55:47 +00005054 case BuiltinType::OCLSampler:
John McCall3624e9e2012-12-20 02:45:14 +00005055 case BuiltinType::Dependent:
5056#define BUILTIN_TYPE(KIND, ID)
5057#define PLACEHOLDER_TYPE(KIND, ID) \
5058 case BuiltinType::KIND:
5059#include "clang/AST/BuiltinTypes.def"
5060 llvm_unreachable("invalid builtin type for @encode");
David Chisnall64fd7e82010-06-04 01:10:52 +00005061 }
David Blaikie719e53f2013-01-09 17:48:41 +00005062 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnall64fd7e82010-06-04 01:10:52 +00005063}
5064
Douglas Gregor5471bc82011-09-08 17:18:35 +00005065static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5066 EnumDecl *Enum = ET->getDecl();
5067
5068 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5069 if (!Enum->isFixed())
5070 return 'i';
5071
5072 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall3624e9e2012-12-20 02:45:14 +00005073 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5074 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor5471bc82011-09-08 17:18:35 +00005075}
5076
Jay Foad4ba2a172011-01-12 09:06:06 +00005077static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00005078 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005079 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00005080 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00005081 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5082 // The GNU runtime requires more information; bitfields are encoded as b,
5083 // then the offset (in bits) of the first element, then the type of the
5084 // bitfield, then the size in bits. For example, in this structure:
5085 //
5086 // struct
5087 // {
5088 // int integer;
5089 // int flags:2;
5090 // };
5091 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5092 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5093 // information is not especially sensible, but we're stuck with it for
5094 // compatibility with GCC, although providing it breaks anything that
5095 // actually uses runtime introspection and wants to work on both runtimes...
John McCall260611a2012-06-20 06:18:46 +00005096 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnall64fd7e82010-06-04 01:10:52 +00005097 const RecordDecl *RD = FD->getParent();
5098 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00005099 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00005100 if (const EnumType *ET = T->getAs<EnumType>())
5101 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall3624e9e2012-12-20 02:45:14 +00005102 else {
5103 const BuiltinType *BT = T->castAs<BuiltinType>();
5104 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5105 }
David Chisnall64fd7e82010-06-04 01:10:52 +00005106 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005107 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00005108}
5109
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00005110// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005111void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5112 bool ExpandPointedToStructures,
5113 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00005114 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00005115 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005116 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00005117 bool StructField,
5118 bool EncodeBlockParameters,
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005119 bool EncodeClassNames,
5120 bool EncodePointerToObjCTypedef) const {
John McCall3624e9e2012-12-20 02:45:14 +00005121 CanQualType CT = getCanonicalType(T);
5122 switch (CT->getTypeClass()) {
5123 case Type::Builtin:
5124 case Type::Enum:
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005125 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00005126 return EncodeBitField(this, S, T, FD);
John McCall3624e9e2012-12-20 02:45:14 +00005127 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5128 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5129 else
5130 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005131 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005132
John McCall3624e9e2012-12-20 02:45:14 +00005133 case Type::Complex: {
5134 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005135 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00005136 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005137 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005138 return;
5139 }
John McCall3624e9e2012-12-20 02:45:14 +00005140
5141 case Type::Atomic: {
5142 const AtomicType *AT = T->castAs<AtomicType>();
5143 S += 'A';
5144 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5145 false, false);
5146 return;
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00005147 }
John McCall3624e9e2012-12-20 02:45:14 +00005148
5149 // encoding for pointer or reference types.
5150 case Type::Pointer:
5151 case Type::LValueReference:
5152 case Type::RValueReference: {
5153 QualType PointeeTy;
5154 if (isa<PointerType>(CT)) {
5155 const PointerType *PT = T->castAs<PointerType>();
5156 if (PT->isObjCSelType()) {
5157 S += ':';
5158 return;
5159 }
5160 PointeeTy = PT->getPointeeType();
5161 } else {
5162 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5163 }
5164
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005165 bool isReadOnly = false;
5166 // For historical/compatibility reasons, the read-only qualifier of the
5167 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5168 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00005169 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00005170 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005171 if (OutermostType && T.isConstQualified()) {
5172 isReadOnly = true;
5173 S += 'r';
5174 }
Mike Stump9fdbab32009-07-31 02:02:20 +00005175 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005176 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00005177 while (P->getAs<PointerType>())
5178 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005179 if (P.isConstQualified()) {
5180 isReadOnly = true;
5181 S += 'r';
5182 }
5183 }
5184 if (isReadOnly) {
5185 // Another legacy compatibility encoding. Some ObjC qualifier and type
5186 // combinations need to be rearranged.
5187 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00005188 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00005189 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005190 }
Mike Stump1eb44332009-09-09 15:08:12 +00005191
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005192 if (PointeeTy->isCharType()) {
5193 // char pointer types should be encoded as '*' unless it is a
5194 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00005195 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005196 S += '*';
5197 return;
5198 }
Ted Kremenek6217b802009-07-29 21:53:49 +00005199 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00005200 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5201 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5202 S += '#';
5203 return;
5204 }
5205 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5206 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5207 S += '@';
5208 return;
5209 }
5210 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005211 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005212 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005213 getLegacyIntegralTypeEncoding(PointeeTy);
5214
Mike Stump1eb44332009-09-09 15:08:12 +00005215 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005216 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005217 return;
5218 }
John McCall3624e9e2012-12-20 02:45:14 +00005219
5220 case Type::ConstantArray:
5221 case Type::IncompleteArray:
5222 case Type::VariableArray: {
5223 const ArrayType *AT = cast<ArrayType>(CT);
5224
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005225 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00005226 // Incomplete arrays are encoded as a pointer to the array element.
5227 S += '^';
5228
Mike Stump1eb44332009-09-09 15:08:12 +00005229 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005230 false, ExpandStructures, FD);
5231 } else {
5232 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00005233
Fariborz Jahanian48eff6c2013-06-04 16:04:37 +00005234 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5235 S += llvm::utostr(CAT->getSize().getZExtValue());
5236 else {
Anders Carlsson559a8332009-02-22 01:38:57 +00005237 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005238 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5239 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00005240 S += '0';
5241 }
Mike Stump1eb44332009-09-09 15:08:12 +00005242
5243 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005244 false, ExpandStructures, FD);
5245 S += ']';
5246 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005247 return;
5248 }
Mike Stump1eb44332009-09-09 15:08:12 +00005249
John McCall3624e9e2012-12-20 02:45:14 +00005250 case Type::FunctionNoProto:
5251 case Type::FunctionProto:
Anders Carlssonc0a87b72007-10-30 00:06:20 +00005252 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005253 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005254
John McCall3624e9e2012-12-20 02:45:14 +00005255 case Type::Record: {
5256 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005257 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005258 // Anonymous structures print as '?'
5259 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5260 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005261 if (ClassTemplateSpecializationDecl *Spec
5262 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5263 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer5eada842013-02-22 15:46:01 +00005264 llvm::raw_string_ostream OS(S);
5265 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor910f8002010-11-07 23:05:16 +00005266 TemplateArgs.data(),
5267 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00005268 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005269 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005270 } else {
5271 S += '?';
5272 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00005273 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005274 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005275 if (!RDecl->isUnion()) {
5276 getObjCEncodingForStructureImpl(RDecl, S, FD);
5277 } else {
5278 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5279 FieldEnd = RDecl->field_end();
5280 Field != FieldEnd; ++Field) {
5281 if (FD) {
5282 S += '"';
5283 S += Field->getNameAsString();
5284 S += '"';
5285 }
Mike Stump1eb44332009-09-09 15:08:12 +00005286
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005287 // Special case bit-fields.
5288 if (Field->isBitField()) {
5289 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie581deb32012-06-06 20:45:41 +00005290 *Field);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005291 } else {
5292 QualType qt = Field->getType();
5293 getLegacyIntegralTypeEncoding(qt);
5294 getObjCEncodingForTypeImpl(qt, S, false, true,
5295 FD, /*OutermostType*/false,
5296 /*EncodingProperty*/false,
5297 /*StructField*/true);
5298 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005299 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005300 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00005301 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005302 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005303 return;
5304 }
Mike Stump1eb44332009-09-09 15:08:12 +00005305
John McCall3624e9e2012-12-20 02:45:14 +00005306 case Type::BlockPointer: {
5307 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff21a98b12009-02-02 18:24:29 +00005308 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00005309 if (EncodeBlockParameters) {
John McCall3624e9e2012-12-20 02:45:14 +00005310 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilsondc8dab62011-11-30 01:57:58 +00005311
5312 S += '<';
5313 // Block return type
5314 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5315 ExpandPointedToStructures, ExpandStructures,
5316 FD,
5317 false /* OutermostType */,
5318 EncodingProperty,
5319 false /* StructField */,
5320 EncodeBlockParameters,
5321 EncodeClassNames);
5322 // Block self
5323 S += "@?";
5324 // Block parameters
5325 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5326 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5327 E = FPT->arg_type_end(); I && (I != E); ++I) {
5328 getObjCEncodingForTypeImpl(*I, S,
5329 ExpandPointedToStructures,
5330 ExpandStructures,
5331 FD,
5332 false /* OutermostType */,
5333 EncodingProperty,
5334 false /* StructField */,
5335 EncodeBlockParameters,
5336 EncodeClassNames);
5337 }
5338 }
5339 S += '>';
5340 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005341 return;
5342 }
Mike Stump1eb44332009-09-09 15:08:12 +00005343
John McCall3624e9e2012-12-20 02:45:14 +00005344 case Type::ObjCObject:
5345 case Type::ObjCInterface: {
5346 // Ignore protocol qualifiers when mangling at this level.
5347 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCallc12c5bb2010-05-15 11:32:37 +00005348
John McCall3624e9e2012-12-20 02:45:14 +00005349 // The assumption seems to be that this assert will succeed
5350 // because nested levels will have filtered out 'id' and 'Class'.
5351 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005352 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00005353 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005354 S += '{';
5355 const IdentifierInfo *II = OI->getIdentifier();
5356 S += II->getName();
5357 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00005358 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005359 DeepCollectObjCIvars(OI, true, Ivars);
5360 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00005361 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005362 if (Field->isBitField())
5363 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005364 else
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005365 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5366 false, false, false, false, false,
5367 EncodePointerToObjCTypedef);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005368 }
5369 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005370 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005371 }
Mike Stump1eb44332009-09-09 15:08:12 +00005372
John McCall3624e9e2012-12-20 02:45:14 +00005373 case Type::ObjCObjectPointer: {
5374 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00005375 if (OPT->isObjCIdType()) {
5376 S += '@';
5377 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005378 }
Mike Stump1eb44332009-09-09 15:08:12 +00005379
Steve Naroff27d20a22009-10-28 22:03:49 +00005380 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5381 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5382 // Since this is a binary compatibility issue, need to consult with runtime
5383 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00005384 S += '#';
5385 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005386 }
Mike Stump1eb44332009-09-09 15:08:12 +00005387
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005388 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005389 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00005390 ExpandPointedToStructures,
5391 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00005392 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00005393 // Note that we do extended encoding of protocol qualifer list
5394 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00005395 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005396 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5397 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00005398 S += '<';
5399 S += (*I)->getNameAsString();
5400 S += '>';
5401 }
5402 S += '"';
5403 }
5404 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005405 }
Mike Stump1eb44332009-09-09 15:08:12 +00005406
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005407 QualType PointeeTy = OPT->getPointeeType();
5408 if (!EncodingProperty &&
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005409 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5410 !EncodePointerToObjCTypedef) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005411 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00005412 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005413 // {...};
5414 S += '^';
Fariborz Jahanian361a3292013-07-12 16:19:11 +00005415 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc1310462013-07-12 16:41:56 +00005416 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian361a3292013-07-12 16:19:11 +00005417 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5418 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5419 DeepCollectObjCIvars(OI, true, Ivars);
5420 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5421 if (cast<FieldDecl>(Ivars[i]) == FD) {
5422 S += '{';
5423 S += OI->getIdentifier()->getName();
5424 S += '}';
5425 return;
5426 }
5427 }
5428 }
Mike Stump1eb44332009-09-09 15:08:12 +00005429 getObjCEncodingForTypeImpl(PointeeTy, S,
5430 false, ExpandPointedToStructures,
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005431 NULL,
5432 false, false, false, false, false,
5433 /*EncodePointerToObjCTypedef*/true);
Steve Naroff14108da2009-07-10 23:34:53 +00005434 return;
5435 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005436
5437 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00005438 if (OPT->getInterfaceDecl() &&
5439 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005440 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00005441 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005442 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5443 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005444 S += '<';
5445 S += (*I)->getNameAsString();
5446 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00005447 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005448 S += '"';
5449 }
5450 return;
5451 }
Mike Stump1eb44332009-09-09 15:08:12 +00005452
John McCall532ec7b2010-05-17 23:56:34 +00005453 // gcc just blithely ignores member pointers.
John McCall3624e9e2012-12-20 02:45:14 +00005454 // FIXME: we shoul do better than that. 'M' is available.
5455 case Type::MemberPointer:
John McCall532ec7b2010-05-17 23:56:34 +00005456 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005457
John McCall3624e9e2012-12-20 02:45:14 +00005458 case Type::Vector:
5459 case Type::ExtVector:
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005460 // This matches gcc's encoding, even though technically it is
5461 // insufficient.
5462 // FIXME. We should do a better job than gcc.
5463 return;
John McCall3624e9e2012-12-20 02:45:14 +00005464
Richard Smithdc7a4f52013-04-30 13:56:41 +00005465 case Type::Auto:
5466 // We could see an undeduced auto type here during error recovery.
5467 // Just ignore it.
5468 return;
5469
John McCall3624e9e2012-12-20 02:45:14 +00005470#define ABSTRACT_TYPE(KIND, BASE)
5471#define TYPE(KIND, BASE)
5472#define DEPENDENT_TYPE(KIND, BASE) \
5473 case Type::KIND:
5474#define NON_CANONICAL_TYPE(KIND, BASE) \
5475 case Type::KIND:
5476#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5477 case Type::KIND:
5478#include "clang/AST/TypeNodes.def"
5479 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005480 }
John McCall3624e9e2012-12-20 02:45:14 +00005481 llvm_unreachable("bad type kind!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005482}
5483
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005484void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5485 std::string &S,
5486 const FieldDecl *FD,
5487 bool includeVBases) const {
5488 assert(RDecl && "Expected non-null RecordDecl");
5489 assert(!RDecl->isUnion() && "Should not be called for unions");
5490 if (!RDecl->getDefinition())
5491 return;
5492
5493 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5494 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5495 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5496
5497 if (CXXRec) {
5498 for (CXXRecordDecl::base_class_iterator
5499 BI = CXXRec->bases_begin(),
5500 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5501 if (!BI->isVirtual()) {
5502 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005503 if (base->isEmpty())
5504 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005505 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005506 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5507 std::make_pair(offs, base));
5508 }
5509 }
5510 }
5511
5512 unsigned i = 0;
5513 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5514 FieldEnd = RDecl->field_end();
5515 Field != FieldEnd; ++Field, ++i) {
5516 uint64_t offs = layout.getFieldOffset(i);
5517 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie581deb32012-06-06 20:45:41 +00005518 std::make_pair(offs, *Field));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005519 }
5520
5521 if (CXXRec && includeVBases) {
5522 for (CXXRecordDecl::base_class_iterator
5523 BI = CXXRec->vbases_begin(),
5524 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5525 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005526 if (base->isEmpty())
5527 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005528 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00005529 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5530 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5531 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005532 }
5533 }
5534
5535 CharUnits size;
5536 if (CXXRec) {
5537 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5538 } else {
5539 size = layout.getSize();
5540 }
5541
5542 uint64_t CurOffs = 0;
5543 std::multimap<uint64_t, NamedDecl *>::iterator
5544 CurLayObj = FieldOrBaseOffsets.begin();
5545
Douglas Gregor58db7a52012-04-27 22:30:01 +00005546 if (CXXRec && CXXRec->isDynamicClass() &&
5547 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005548 if (FD) {
5549 S += "\"_vptr$";
5550 std::string recname = CXXRec->getNameAsString();
5551 if (recname.empty()) recname = "?";
5552 S += recname;
5553 S += '"';
5554 }
5555 S += "^^?";
5556 CurOffs += getTypeSize(VoidPtrTy);
5557 }
5558
5559 if (!RDecl->hasFlexibleArrayMember()) {
5560 // Mark the end of the structure.
5561 uint64_t offs = toBits(size);
5562 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5563 std::make_pair(offs, (NamedDecl*)0));
5564 }
5565
5566 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5567 assert(CurOffs <= CurLayObj->first);
5568
5569 if (CurOffs < CurLayObj->first) {
5570 uint64_t padding = CurLayObj->first - CurOffs;
5571 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5572 // packing/alignment of members is different that normal, in which case
5573 // the encoding will be out-of-sync with the real layout.
5574 // If the runtime switches to just consider the size of types without
5575 // taking into account alignment, we could make padding explicit in the
5576 // encoding (e.g. using arrays of chars). The encoding strings would be
5577 // longer then though.
5578 CurOffs += padding;
5579 }
5580
5581 NamedDecl *dcl = CurLayObj->second;
5582 if (dcl == 0)
5583 break; // reached end of structure.
5584
5585 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5586 // We expand the bases without their virtual bases since those are going
5587 // in the initial structure. Note that this differs from gcc which
5588 // expands virtual bases each time one is encountered in the hierarchy,
5589 // making the encoding type bigger than it really is.
5590 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005591 assert(!base->isEmpty());
5592 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005593 } else {
5594 FieldDecl *field = cast<FieldDecl>(dcl);
5595 if (FD) {
5596 S += '"';
5597 S += field->getNameAsString();
5598 S += '"';
5599 }
5600
5601 if (field->isBitField()) {
5602 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005603 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005604 } else {
5605 QualType qt = field->getType();
5606 getLegacyIntegralTypeEncoding(qt);
5607 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5608 /*OutermostType*/false,
5609 /*EncodingProperty*/false,
5610 /*StructField*/true);
5611 CurOffs += getTypeSize(field->getType());
5612 }
5613 }
5614 }
5615}
5616
Mike Stump1eb44332009-09-09 15:08:12 +00005617void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00005618 std::string& S) const {
5619 if (QT & Decl::OBJC_TQ_In)
5620 S += 'n';
5621 if (QT & Decl::OBJC_TQ_Inout)
5622 S += 'N';
5623 if (QT & Decl::OBJC_TQ_Out)
5624 S += 'o';
5625 if (QT & Decl::OBJC_TQ_Bycopy)
5626 S += 'O';
5627 if (QT & Decl::OBJC_TQ_Byref)
5628 S += 'R';
5629 if (QT & Decl::OBJC_TQ_Oneway)
5630 S += 'V';
5631}
5632
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00005633TypedefDecl *ASTContext::getObjCIdDecl() const {
5634 if (!ObjCIdDecl) {
5635 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5636 T = getObjCObjectPointerType(T);
5637 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5638 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5639 getTranslationUnitDecl(),
5640 SourceLocation(), SourceLocation(),
5641 &Idents.get("id"), IdInfo);
5642 }
5643
5644 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00005645}
5646
Douglas Gregor7a27ea52011-08-12 06:17:30 +00005647TypedefDecl *ASTContext::getObjCSelDecl() const {
5648 if (!ObjCSelDecl) {
5649 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5650 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5651 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5652 getTranslationUnitDecl(),
5653 SourceLocation(), SourceLocation(),
5654 &Idents.get("SEL"), SelInfo);
5655 }
5656 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00005657}
5658
Douglas Gregor79d67262011-08-12 05:59:41 +00005659TypedefDecl *ASTContext::getObjCClassDecl() const {
5660 if (!ObjCClassDecl) {
5661 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5662 T = getObjCObjectPointerType(T);
5663 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5664 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5665 getTranslationUnitDecl(),
5666 SourceLocation(), SourceLocation(),
5667 &Idents.get("Class"), ClassInfo);
5668 }
5669
5670 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00005671}
5672
Douglas Gregora6ea10e2012-01-17 18:09:05 +00005673ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5674 if (!ObjCProtocolClassDecl) {
5675 ObjCProtocolClassDecl
5676 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5677 SourceLocation(),
5678 &Idents.get("Protocol"),
5679 /*PrevDecl=*/0,
5680 SourceLocation(), true);
5681 }
5682
5683 return ObjCProtocolClassDecl;
5684}
5685
Meador Ingec5613b22012-06-16 03:34:49 +00005686//===----------------------------------------------------------------------===//
5687// __builtin_va_list Construction Functions
5688//===----------------------------------------------------------------------===//
5689
5690static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5691 // typedef char* __builtin_va_list;
5692 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5693 TypeSourceInfo *TInfo
5694 = Context->getTrivialTypeSourceInfo(CharPtrType);
5695
5696 TypedefDecl *VaListTypeDecl
5697 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5698 Context->getTranslationUnitDecl(),
5699 SourceLocation(), SourceLocation(),
5700 &Context->Idents.get("__builtin_va_list"),
5701 TInfo);
5702 return VaListTypeDecl;
5703}
5704
5705static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5706 // typedef void* __builtin_va_list;
5707 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5708 TypeSourceInfo *TInfo
5709 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5710
5711 TypedefDecl *VaListTypeDecl
5712 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5713 Context->getTranslationUnitDecl(),
5714 SourceLocation(), SourceLocation(),
5715 &Context->Idents.get("__builtin_va_list"),
5716 TInfo);
5717 return VaListTypeDecl;
5718}
5719
Tim Northoverc264e162013-01-31 12:13:10 +00005720static TypedefDecl *
5721CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5722 RecordDecl *VaListTagDecl;
5723 if (Context->getLangOpts().CPlusPlus) {
5724 // namespace std { struct __va_list {
5725 NamespaceDecl *NS;
5726 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5727 Context->getTranslationUnitDecl(),
5728 /*Inline*/false, SourceLocation(),
5729 SourceLocation(), &Context->Idents.get("std"),
5730 /*PrevDecl*/0);
5731
5732 VaListTagDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5733 Context->getTranslationUnitDecl(),
5734 SourceLocation(), SourceLocation(),
5735 &Context->Idents.get("__va_list"));
5736 VaListTagDecl->setDeclContext(NS);
5737 } else {
5738 // struct __va_list
5739 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5740 Context->getTranslationUnitDecl(),
5741 &Context->Idents.get("__va_list"));
5742 }
5743
5744 VaListTagDecl->startDefinition();
5745
5746 const size_t NumFields = 5;
5747 QualType FieldTypes[NumFields];
5748 const char *FieldNames[NumFields];
5749
5750 // void *__stack;
5751 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5752 FieldNames[0] = "__stack";
5753
5754 // void *__gr_top;
5755 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5756 FieldNames[1] = "__gr_top";
5757
5758 // void *__vr_top;
5759 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5760 FieldNames[2] = "__vr_top";
5761
5762 // int __gr_offs;
5763 FieldTypes[3] = Context->IntTy;
5764 FieldNames[3] = "__gr_offs";
5765
5766 // int __vr_offs;
5767 FieldTypes[4] = Context->IntTy;
5768 FieldNames[4] = "__vr_offs";
5769
5770 // Create fields
5771 for (unsigned i = 0; i < NumFields; ++i) {
5772 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5773 VaListTagDecl,
5774 SourceLocation(),
5775 SourceLocation(),
5776 &Context->Idents.get(FieldNames[i]),
5777 FieldTypes[i], /*TInfo=*/0,
5778 /*BitWidth=*/0,
5779 /*Mutable=*/false,
5780 ICIS_NoInit);
5781 Field->setAccess(AS_public);
5782 VaListTagDecl->addDecl(Field);
5783 }
5784 VaListTagDecl->completeDefinition();
5785 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5786 Context->VaListTagTy = VaListTagType;
5787
5788 // } __builtin_va_list;
5789 TypedefDecl *VaListTypedefDecl
5790 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5791 Context->getTranslationUnitDecl(),
5792 SourceLocation(), SourceLocation(),
5793 &Context->Idents.get("__builtin_va_list"),
5794 Context->getTrivialTypeSourceInfo(VaListTagType));
5795
5796 return VaListTypedefDecl;
5797}
5798
Meador Ingec5613b22012-06-16 03:34:49 +00005799static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5800 // typedef struct __va_list_tag {
5801 RecordDecl *VaListTagDecl;
5802
5803 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5804 Context->getTranslationUnitDecl(),
5805 &Context->Idents.get("__va_list_tag"));
5806 VaListTagDecl->startDefinition();
5807
5808 const size_t NumFields = 5;
5809 QualType FieldTypes[NumFields];
5810 const char *FieldNames[NumFields];
5811
5812 // unsigned char gpr;
5813 FieldTypes[0] = Context->UnsignedCharTy;
5814 FieldNames[0] = "gpr";
5815
5816 // unsigned char fpr;
5817 FieldTypes[1] = Context->UnsignedCharTy;
5818 FieldNames[1] = "fpr";
5819
5820 // unsigned short reserved;
5821 FieldTypes[2] = Context->UnsignedShortTy;
5822 FieldNames[2] = "reserved";
5823
5824 // void* overflow_arg_area;
5825 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5826 FieldNames[3] = "overflow_arg_area";
5827
5828 // void* reg_save_area;
5829 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5830 FieldNames[4] = "reg_save_area";
5831
5832 // Create fields
5833 for (unsigned i = 0; i < NumFields; ++i) {
5834 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5835 SourceLocation(),
5836 SourceLocation(),
5837 &Context->Idents.get(FieldNames[i]),
5838 FieldTypes[i], /*TInfo=*/0,
5839 /*BitWidth=*/0,
5840 /*Mutable=*/false,
5841 ICIS_NoInit);
5842 Field->setAccess(AS_public);
5843 VaListTagDecl->addDecl(Field);
5844 }
5845 VaListTagDecl->completeDefinition();
5846 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005847 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005848
5849 // } __va_list_tag;
5850 TypedefDecl *VaListTagTypedefDecl
5851 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5852 Context->getTranslationUnitDecl(),
5853 SourceLocation(), SourceLocation(),
5854 &Context->Idents.get("__va_list_tag"),
5855 Context->getTrivialTypeSourceInfo(VaListTagType));
5856 QualType VaListTagTypedefType =
5857 Context->getTypedefType(VaListTagTypedefDecl);
5858
5859 // typedef __va_list_tag __builtin_va_list[1];
5860 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5861 QualType VaListTagArrayType
5862 = Context->getConstantArrayType(VaListTagTypedefType,
5863 Size, ArrayType::Normal, 0);
5864 TypeSourceInfo *TInfo
5865 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5866 TypedefDecl *VaListTypedefDecl
5867 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5868 Context->getTranslationUnitDecl(),
5869 SourceLocation(), SourceLocation(),
5870 &Context->Idents.get("__builtin_va_list"),
5871 TInfo);
5872
5873 return VaListTypedefDecl;
5874}
5875
5876static TypedefDecl *
5877CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5878 // typedef struct __va_list_tag {
5879 RecordDecl *VaListTagDecl;
5880 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5881 Context->getTranslationUnitDecl(),
5882 &Context->Idents.get("__va_list_tag"));
5883 VaListTagDecl->startDefinition();
5884
5885 const size_t NumFields = 4;
5886 QualType FieldTypes[NumFields];
5887 const char *FieldNames[NumFields];
5888
5889 // unsigned gp_offset;
5890 FieldTypes[0] = Context->UnsignedIntTy;
5891 FieldNames[0] = "gp_offset";
5892
5893 // unsigned fp_offset;
5894 FieldTypes[1] = Context->UnsignedIntTy;
5895 FieldNames[1] = "fp_offset";
5896
5897 // void* overflow_arg_area;
5898 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5899 FieldNames[2] = "overflow_arg_area";
5900
5901 // void* reg_save_area;
5902 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5903 FieldNames[3] = "reg_save_area";
5904
5905 // Create fields
5906 for (unsigned i = 0; i < NumFields; ++i) {
5907 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5908 VaListTagDecl,
5909 SourceLocation(),
5910 SourceLocation(),
5911 &Context->Idents.get(FieldNames[i]),
5912 FieldTypes[i], /*TInfo=*/0,
5913 /*BitWidth=*/0,
5914 /*Mutable=*/false,
5915 ICIS_NoInit);
5916 Field->setAccess(AS_public);
5917 VaListTagDecl->addDecl(Field);
5918 }
5919 VaListTagDecl->completeDefinition();
5920 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005921 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005922
5923 // } __va_list_tag;
5924 TypedefDecl *VaListTagTypedefDecl
5925 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5926 Context->getTranslationUnitDecl(),
5927 SourceLocation(), SourceLocation(),
5928 &Context->Idents.get("__va_list_tag"),
5929 Context->getTrivialTypeSourceInfo(VaListTagType));
5930 QualType VaListTagTypedefType =
5931 Context->getTypedefType(VaListTagTypedefDecl);
5932
5933 // typedef __va_list_tag __builtin_va_list[1];
5934 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5935 QualType VaListTagArrayType
5936 = Context->getConstantArrayType(VaListTagTypedefType,
5937 Size, ArrayType::Normal,0);
5938 TypeSourceInfo *TInfo
5939 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5940 TypedefDecl *VaListTypedefDecl
5941 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5942 Context->getTranslationUnitDecl(),
5943 SourceLocation(), SourceLocation(),
5944 &Context->Idents.get("__builtin_va_list"),
5945 TInfo);
5946
5947 return VaListTypedefDecl;
5948}
5949
5950static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5951 // typedef int __builtin_va_list[4];
5952 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5953 QualType IntArrayType
5954 = Context->getConstantArrayType(Context->IntTy,
5955 Size, ArrayType::Normal, 0);
5956 TypedefDecl *VaListTypedefDecl
5957 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5958 Context->getTranslationUnitDecl(),
5959 SourceLocation(), SourceLocation(),
5960 &Context->Idents.get("__builtin_va_list"),
5961 Context->getTrivialTypeSourceInfo(IntArrayType));
5962
5963 return VaListTypedefDecl;
5964}
5965
Logan Chieneae5a8202012-10-10 06:56:20 +00005966static TypedefDecl *
5967CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5968 RecordDecl *VaListDecl;
5969 if (Context->getLangOpts().CPlusPlus) {
5970 // namespace std { struct __va_list {
5971 NamespaceDecl *NS;
5972 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5973 Context->getTranslationUnitDecl(),
5974 /*Inline*/false, SourceLocation(),
5975 SourceLocation(), &Context->Idents.get("std"),
5976 /*PrevDecl*/0);
5977
5978 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5979 Context->getTranslationUnitDecl(),
5980 SourceLocation(), SourceLocation(),
5981 &Context->Idents.get("__va_list"));
5982
5983 VaListDecl->setDeclContext(NS);
5984
5985 } else {
5986 // struct __va_list {
5987 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
5988 Context->getTranslationUnitDecl(),
5989 &Context->Idents.get("__va_list"));
5990 }
5991
5992 VaListDecl->startDefinition();
5993
5994 // void * __ap;
5995 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5996 VaListDecl,
5997 SourceLocation(),
5998 SourceLocation(),
5999 &Context->Idents.get("__ap"),
6000 Context->getPointerType(Context->VoidTy),
6001 /*TInfo=*/0,
6002 /*BitWidth=*/0,
6003 /*Mutable=*/false,
6004 ICIS_NoInit);
6005 Field->setAccess(AS_public);
6006 VaListDecl->addDecl(Field);
6007
6008 // };
6009 VaListDecl->completeDefinition();
6010
6011 // typedef struct __va_list __builtin_va_list;
6012 TypeSourceInfo *TInfo
6013 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
6014
6015 TypedefDecl *VaListTypeDecl
6016 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6017 Context->getTranslationUnitDecl(),
6018 SourceLocation(), SourceLocation(),
6019 &Context->Idents.get("__builtin_va_list"),
6020 TInfo);
6021
6022 return VaListTypeDecl;
6023}
6024
Ulrich Weigandb8409212013-05-06 16:26:41 +00006025static TypedefDecl *
6026CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6027 // typedef struct __va_list_tag {
6028 RecordDecl *VaListTagDecl;
6029 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
6030 Context->getTranslationUnitDecl(),
6031 &Context->Idents.get("__va_list_tag"));
6032 VaListTagDecl->startDefinition();
6033
6034 const size_t NumFields = 4;
6035 QualType FieldTypes[NumFields];
6036 const char *FieldNames[NumFields];
6037
6038 // long __gpr;
6039 FieldTypes[0] = Context->LongTy;
6040 FieldNames[0] = "__gpr";
6041
6042 // long __fpr;
6043 FieldTypes[1] = Context->LongTy;
6044 FieldNames[1] = "__fpr";
6045
6046 // void *__overflow_arg_area;
6047 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6048 FieldNames[2] = "__overflow_arg_area";
6049
6050 // void *__reg_save_area;
6051 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6052 FieldNames[3] = "__reg_save_area";
6053
6054 // Create fields
6055 for (unsigned i = 0; i < NumFields; ++i) {
6056 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6057 VaListTagDecl,
6058 SourceLocation(),
6059 SourceLocation(),
6060 &Context->Idents.get(FieldNames[i]),
6061 FieldTypes[i], /*TInfo=*/0,
6062 /*BitWidth=*/0,
6063 /*Mutable=*/false,
6064 ICIS_NoInit);
6065 Field->setAccess(AS_public);
6066 VaListTagDecl->addDecl(Field);
6067 }
6068 VaListTagDecl->completeDefinition();
6069 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6070 Context->VaListTagTy = VaListTagType;
6071
6072 // } __va_list_tag;
6073 TypedefDecl *VaListTagTypedefDecl
6074 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6075 Context->getTranslationUnitDecl(),
6076 SourceLocation(), SourceLocation(),
6077 &Context->Idents.get("__va_list_tag"),
6078 Context->getTrivialTypeSourceInfo(VaListTagType));
6079 QualType VaListTagTypedefType =
6080 Context->getTypedefType(VaListTagTypedefDecl);
6081
6082 // typedef __va_list_tag __builtin_va_list[1];
6083 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6084 QualType VaListTagArrayType
6085 = Context->getConstantArrayType(VaListTagTypedefType,
6086 Size, ArrayType::Normal,0);
6087 TypeSourceInfo *TInfo
6088 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
6089 TypedefDecl *VaListTypedefDecl
6090 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6091 Context->getTranslationUnitDecl(),
6092 SourceLocation(), SourceLocation(),
6093 &Context->Idents.get("__builtin_va_list"),
6094 TInfo);
6095
6096 return VaListTypedefDecl;
6097}
6098
Meador Ingec5613b22012-06-16 03:34:49 +00006099static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6100 TargetInfo::BuiltinVaListKind Kind) {
6101 switch (Kind) {
6102 case TargetInfo::CharPtrBuiltinVaList:
6103 return CreateCharPtrBuiltinVaListDecl(Context);
6104 case TargetInfo::VoidPtrBuiltinVaList:
6105 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northoverc264e162013-01-31 12:13:10 +00006106 case TargetInfo::AArch64ABIBuiltinVaList:
6107 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00006108 case TargetInfo::PowerABIBuiltinVaList:
6109 return CreatePowerABIBuiltinVaListDecl(Context);
6110 case TargetInfo::X86_64ABIBuiltinVaList:
6111 return CreateX86_64ABIBuiltinVaListDecl(Context);
6112 case TargetInfo::PNaClABIBuiltinVaList:
6113 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chieneae5a8202012-10-10 06:56:20 +00006114 case TargetInfo::AAPCSABIBuiltinVaList:
6115 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigandb8409212013-05-06 16:26:41 +00006116 case TargetInfo::SystemZBuiltinVaList:
6117 return CreateSystemZBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00006118 }
6119
6120 llvm_unreachable("Unhandled __builtin_va_list type kind");
6121}
6122
6123TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6124 if (!BuiltinVaListDecl)
6125 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6126
6127 return BuiltinVaListDecl;
6128}
6129
Meador Ingefb40e3f2012-07-01 15:57:25 +00006130QualType ASTContext::getVaListTagType() const {
6131 // Force the creation of VaListTagTy by building the __builtin_va_list
6132 // declaration.
6133 if (VaListTagTy.isNull())
6134 (void) getBuiltinVaListDecl();
6135
6136 return VaListTagTy;
6137}
6138
Ted Kremeneka526c5c2008-01-07 19:49:32 +00006139void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00006140 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00006141 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00006142
Ted Kremeneka526c5c2008-01-07 19:49:32 +00006143 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00006144}
6145
John McCall0bd6feb2009-12-02 08:04:21 +00006146/// \brief Retrieve the template name that corresponds to a non-empty
6147/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00006148TemplateName
6149ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6150 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00006151 unsigned size = End - Begin;
6152 assert(size > 1 && "set is not overloaded!");
6153
6154 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6155 size * sizeof(FunctionTemplateDecl*));
6156 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6157
6158 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00006159 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00006160 NamedDecl *D = *I;
6161 assert(isa<FunctionTemplateDecl>(D) ||
6162 (isa<UsingShadowDecl>(D) &&
6163 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6164 *Storage++ = D;
6165 }
6166
6167 return TemplateName(OT);
6168}
6169
Douglas Gregor7532dc62009-03-30 22:58:21 +00006170/// \brief Retrieve the template name that represents a qualified
6171/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00006172TemplateName
6173ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6174 bool TemplateKeyword,
6175 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00006176 assert(NNS && "Missing nested-name-specifier in qualified template name");
6177
Douglas Gregor789b1f62010-02-04 18:10:26 +00006178 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00006179 llvm::FoldingSetNodeID ID;
6180 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6181
6182 void *InsertPos = 0;
6183 QualifiedTemplateName *QTN =
6184 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6185 if (!QTN) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006186 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6187 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregor7532dc62009-03-30 22:58:21 +00006188 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6189 }
6190
6191 return TemplateName(QTN);
6192}
6193
6194/// \brief Retrieve the template name that represents a dependent
6195/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00006196TemplateName
6197ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6198 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00006199 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00006200 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00006201
6202 llvm::FoldingSetNodeID ID;
6203 DependentTemplateName::Profile(ID, NNS, Name);
6204
6205 void *InsertPos = 0;
6206 DependentTemplateName *QTN =
6207 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6208
6209 if (QTN)
6210 return TemplateName(QTN);
6211
6212 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6213 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006214 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6215 DependentTemplateName(NNS, Name);
Douglas Gregor7532dc62009-03-30 22:58:21 +00006216 } else {
6217 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smith2f47cab2012-08-16 01:19:31 +00006218 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6219 DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00006220 DependentTemplateName *CheckQTN =
6221 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6222 assert(!CheckQTN && "Dependent type name canonicalization broken");
6223 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00006224 }
6225
6226 DependentTemplateNames.InsertNode(QTN, InsertPos);
6227 return TemplateName(QTN);
6228}
6229
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006230/// \brief Retrieve the template name that represents a dependent
6231/// template name such as \c MetaFun::template operator+.
6232TemplateName
6233ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00006234 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006235 assert((!NNS || NNS->isDependent()) &&
6236 "Nested name specifier must be dependent");
6237
6238 llvm::FoldingSetNodeID ID;
6239 DependentTemplateName::Profile(ID, NNS, Operator);
6240
6241 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00006242 DependentTemplateName *QTN
6243 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006244
6245 if (QTN)
6246 return TemplateName(QTN);
6247
6248 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6249 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006250 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6251 DependentTemplateName(NNS, Operator);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006252 } else {
6253 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smith2f47cab2012-08-16 01:19:31 +00006254 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6255 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00006256
6257 DependentTemplateName *CheckQTN
6258 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6259 assert(!CheckQTN && "Dependent template name canonicalization broken");
6260 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006261 }
6262
6263 DependentTemplateNames.InsertNode(QTN, InsertPos);
6264 return TemplateName(QTN);
6265}
6266
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006267TemplateName
John McCall14606042011-06-30 08:33:18 +00006268ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6269 TemplateName replacement) const {
6270 llvm::FoldingSetNodeID ID;
6271 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6272
6273 void *insertPos = 0;
6274 SubstTemplateTemplateParmStorage *subst
6275 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6276
6277 if (!subst) {
6278 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6279 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6280 }
6281
6282 return TemplateName(subst);
6283}
6284
6285TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006286ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6287 const TemplateArgument &ArgPack) const {
6288 ASTContext &Self = const_cast<ASTContext &>(*this);
6289 llvm::FoldingSetNodeID ID;
6290 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6291
6292 void *InsertPos = 0;
6293 SubstTemplateTemplateParmPackStorage *Subst
6294 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6295
6296 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00006297 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006298 ArgPack.pack_size(),
6299 ArgPack.pack_begin());
6300 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6301 }
6302
6303 return TemplateName(Subst);
6304}
6305
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006306/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00006307/// TargetInfo, produce the corresponding type. The unsigned @p Type
6308/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00006309CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006310 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00006311 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006312 case TargetInfo::SignedShort: return ShortTy;
6313 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6314 case TargetInfo::SignedInt: return IntTy;
6315 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6316 case TargetInfo::SignedLong: return LongTy;
6317 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6318 case TargetInfo::SignedLongLong: return LongLongTy;
6319 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6320 }
6321
David Blaikieb219cfc2011-09-23 05:06:16 +00006322 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006323}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00006324
6325//===----------------------------------------------------------------------===//
6326// Type Predicates.
6327//===----------------------------------------------------------------------===//
6328
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006329/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6330/// garbage collection attribute.
6331///
John McCallae278a32011-01-12 00:34:59 +00006332Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006333 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00006334 return Qualifiers::GCNone;
6335
David Blaikie4e4d0842012-03-11 07:00:24 +00006336 assert(getLangOpts().ObjC1);
John McCallae278a32011-01-12 00:34:59 +00006337 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6338
6339 // Default behaviour under objective-C's gc is for ObjC pointers
6340 // (or pointers to them) be treated as though they were declared
6341 // as __strong.
6342 if (GCAttrs == Qualifiers::GCNone) {
6343 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6344 return Qualifiers::Strong;
6345 else if (Ty->isPointerType())
6346 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6347 } else {
6348 // It's not valid to set GC attributes on anything that isn't a
6349 // pointer.
6350#ifndef NDEBUG
6351 QualType CT = Ty->getCanonicalTypeInternal();
6352 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6353 CT = AT->getElementType();
6354 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6355#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006356 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00006357 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006358}
6359
Chris Lattner6ac46a42008-04-07 06:51:04 +00006360//===----------------------------------------------------------------------===//
6361// Type Compatibility Testing
6362//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00006363
Mike Stump1eb44332009-09-09 15:08:12 +00006364/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006365/// compatible.
6366static bool areCompatVectorTypes(const VectorType *LHS,
6367 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00006368 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00006369 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00006370 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00006371}
6372
Douglas Gregor255210e2010-08-06 10:14:59 +00006373bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6374 QualType SecondVec) {
6375 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6376 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6377
6378 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6379 return true;
6380
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006381 // Treat Neon vector types and most AltiVec vector types as if they are the
6382 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00006383 const VectorType *First = FirstVec->getAs<VectorType>();
6384 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006385 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00006386 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006387 First->getVectorKind() != VectorType::AltiVecPixel &&
6388 First->getVectorKind() != VectorType::AltiVecBool &&
6389 Second->getVectorKind() != VectorType::AltiVecPixel &&
6390 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00006391 return true;
6392
6393 return false;
6394}
6395
Steve Naroff4084c302009-07-23 01:01:38 +00006396//===----------------------------------------------------------------------===//
6397// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6398//===----------------------------------------------------------------------===//
6399
6400/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6401/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00006402bool
6403ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6404 ObjCProtocolDecl *rProto) const {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00006405 if (declaresSameEntity(lProto, rProto))
Steve Naroff4084c302009-07-23 01:01:38 +00006406 return true;
6407 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6408 E = rProto->protocol_end(); PI != E; ++PI)
6409 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6410 return true;
6411 return false;
6412}
6413
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00006414/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6415/// Class<pr1, ...>.
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006416bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6417 QualType rhs) {
6418 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6419 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6420 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6421
6422 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6423 E = lhsQID->qual_end(); I != E; ++I) {
6424 bool match = false;
6425 ObjCProtocolDecl *lhsProto = *I;
6426 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6427 E = rhsOPT->qual_end(); J != E; ++J) {
6428 ObjCProtocolDecl *rhsProto = *J;
6429 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6430 match = true;
6431 break;
6432 }
6433 }
6434 if (!match)
6435 return false;
6436 }
6437 return true;
6438}
6439
Steve Naroff4084c302009-07-23 01:01:38 +00006440/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6441/// ObjCQualifiedIDType.
6442bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6443 bool compare) {
6444 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00006445 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006446 lhs->isObjCIdType() || lhs->isObjCClassType())
6447 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006448 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006449 rhs->isObjCIdType() || rhs->isObjCClassType())
6450 return true;
6451
6452 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00006453 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006454
Steve Naroff4084c302009-07-23 01:01:38 +00006455 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006456
Steve Naroff4084c302009-07-23 01:01:38 +00006457 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006458 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00006459 // make sure we check the class hierarchy.
6460 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6461 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6462 E = lhsQID->qual_end(); I != E; ++I) {
6463 // when comparing an id<P> on lhs with a static type on rhs,
6464 // see if static class implements all of id's protocols, directly or
6465 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006466 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00006467 return false;
6468 }
6469 }
6470 // If there are no qualifiers and no interface, we have an 'id'.
6471 return true;
6472 }
Mike Stump1eb44332009-09-09 15:08:12 +00006473 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006474 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6475 E = lhsQID->qual_end(); I != E; ++I) {
6476 ObjCProtocolDecl *lhsProto = *I;
6477 bool match = false;
6478
6479 // when comparing an id<P> on lhs with a static type on rhs,
6480 // see if static class implements all of id's protocols, directly or
6481 // through its super class and categories.
6482 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6483 E = rhsOPT->qual_end(); J != E; ++J) {
6484 ObjCProtocolDecl *rhsProto = *J;
6485 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6486 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6487 match = true;
6488 break;
6489 }
6490 }
Mike Stump1eb44332009-09-09 15:08:12 +00006491 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00006492 // make sure we check the class hierarchy.
6493 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6494 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6495 E = lhsQID->qual_end(); I != E; ++I) {
6496 // when comparing an id<P> on lhs with a static type on rhs,
6497 // see if static class implements all of id's protocols, directly or
6498 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006499 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00006500 match = true;
6501 break;
6502 }
6503 }
6504 }
6505 if (!match)
6506 return false;
6507 }
Mike Stump1eb44332009-09-09 15:08:12 +00006508
Steve Naroff4084c302009-07-23 01:01:38 +00006509 return true;
6510 }
Mike Stump1eb44332009-09-09 15:08:12 +00006511
Steve Naroff4084c302009-07-23 01:01:38 +00006512 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6513 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6514
Mike Stump1eb44332009-09-09 15:08:12 +00006515 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00006516 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006517 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006518 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6519 E = lhsOPT->qual_end(); I != E; ++I) {
6520 ObjCProtocolDecl *lhsProto = *I;
6521 bool match = false;
6522
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006523 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00006524 // see if static class implements all of id's protocols, directly or
6525 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006526 // First, lhs protocols in the qualifier list must be found, direct
6527 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00006528 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6529 E = rhsQID->qual_end(); J != E; ++J) {
6530 ObjCProtocolDecl *rhsProto = *J;
6531 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6532 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6533 match = true;
6534 break;
6535 }
6536 }
6537 if (!match)
6538 return false;
6539 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006540
6541 // Static class's protocols, or its super class or category protocols
6542 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6543 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6544 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6545 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6546 // This is rather dubious but matches gcc's behavior. If lhs has
6547 // no type qualifier and its class has no static protocol(s)
6548 // assume that it is mismatch.
6549 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6550 return false;
6551 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6552 LHSInheritedProtocols.begin(),
6553 E = LHSInheritedProtocols.end(); I != E; ++I) {
6554 bool match = false;
6555 ObjCProtocolDecl *lhsProto = (*I);
6556 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6557 E = rhsQID->qual_end(); J != E; ++J) {
6558 ObjCProtocolDecl *rhsProto = *J;
6559 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6560 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6561 match = true;
6562 break;
6563 }
6564 }
6565 if (!match)
6566 return false;
6567 }
6568 }
Steve Naroff4084c302009-07-23 01:01:38 +00006569 return true;
6570 }
6571 return false;
6572}
6573
Eli Friedman3d815e72008-08-22 00:56:42 +00006574/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006575/// compatible for assignment from RHS to LHS. This handles validation of any
6576/// protocol qualifiers on the LHS or RHS.
6577///
Steve Naroff14108da2009-07-10 23:34:53 +00006578bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6579 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00006580 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6581 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6582
Steve Naroffde2e22d2009-07-15 18:40:39 +00006583 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00006584 if (LHS->isObjCUnqualifiedIdOrClass() ||
6585 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00006586 return true;
6587
John McCallc12c5bb2010-05-15 11:32:37 +00006588 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00006589 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6590 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00006591 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006592
6593 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6594 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6595 QualType(RHSOPT,0));
6596
John McCallc12c5bb2010-05-15 11:32:37 +00006597 // If we have 2 user-defined types, fall into that path.
6598 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00006599 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006600
Steve Naroff4084c302009-07-23 01:01:38 +00006601 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006602}
6603
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006604/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00006605/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006606/// arguments in block literals. When passed as arguments, passing 'A*' where
6607/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6608/// not OK. For the return type, the opposite is not OK.
6609bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6610 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006611 const ObjCObjectPointerType *RHSOPT,
6612 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006613 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006614 return true;
6615
6616 if (LHSOPT->isObjCBuiltinType()) {
6617 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6618 }
6619
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006620 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006621 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6622 QualType(RHSOPT,0),
6623 false);
6624
6625 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6626 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6627 if (LHS && RHS) { // We have 2 user-defined types.
6628 if (LHS != RHS) {
6629 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006630 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006631 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006632 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006633 }
6634 else
6635 return true;
6636 }
6637 return false;
6638}
6639
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006640/// getIntersectionOfProtocols - This routine finds the intersection of set
6641/// of protocols inherited from two distinct objective-c pointer objects.
6642/// It is used to build composite qualifier list of the composite type of
6643/// the conditional expression involving two objective-c pointer objects.
6644static
6645void getIntersectionOfProtocols(ASTContext &Context,
6646 const ObjCObjectPointerType *LHSOPT,
6647 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006648 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006649
John McCallc12c5bb2010-05-15 11:32:37 +00006650 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6651 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6652 assert(LHS->getInterface() && "LHS must have an interface base");
6653 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006654
6655 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6656 unsigned LHSNumProtocols = LHS->getNumProtocols();
6657 if (LHSNumProtocols > 0)
6658 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6659 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006660 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006661 Context.CollectInheritedProtocols(LHS->getInterface(),
6662 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006663 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6664 LHSInheritedProtocols.end());
6665 }
6666
6667 unsigned RHSNumProtocols = RHS->getNumProtocols();
6668 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00006669 ObjCProtocolDecl **RHSProtocols =
6670 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006671 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6672 if (InheritedProtocolSet.count(RHSProtocols[i]))
6673 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00006674 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006675 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006676 Context.CollectInheritedProtocols(RHS->getInterface(),
6677 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006678 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6679 RHSInheritedProtocols.begin(),
6680 E = RHSInheritedProtocols.end(); I != E; ++I)
6681 if (InheritedProtocolSet.count((*I)))
6682 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006683 }
6684}
6685
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006686/// areCommonBaseCompatible - Returns common base class of the two classes if
6687/// one found. Note that this is O'2 algorithm. But it will be called as the
6688/// last type comparison in a ?-exp of ObjC pointer types before a
6689/// warning is issued. So, its invokation is extremely rare.
6690QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00006691 const ObjCObjectPointerType *Lptr,
6692 const ObjCObjectPointerType *Rptr) {
6693 const ObjCObjectType *LHS = Lptr->getObjectType();
6694 const ObjCObjectType *RHS = Rptr->getObjectType();
6695 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6696 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor60ef3082011-12-15 00:29:59 +00006697 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006698 return QualType();
6699
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006700 do {
John McCallc12c5bb2010-05-15 11:32:37 +00006701 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006702 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006703 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006704 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6705
6706 QualType Result = QualType(LHS, 0);
6707 if (!Protocols.empty())
6708 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6709 Result = getObjCObjectPointerType(Result);
6710 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006711 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006712 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006713
6714 return QualType();
6715}
6716
John McCallc12c5bb2010-05-15 11:32:37 +00006717bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6718 const ObjCObjectType *RHS) {
6719 assert(LHS->getInterface() && "LHS is not an interface type");
6720 assert(RHS->getInterface() && "RHS is not an interface type");
6721
Chris Lattner6ac46a42008-04-07 06:51:04 +00006722 // Verify that the base decls are compatible: the RHS must be a subclass of
6723 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00006724 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00006725 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006726
Chris Lattner6ac46a42008-04-07 06:51:04 +00006727 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6728 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00006729 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00006730 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006731
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006732 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6733 // more detailed analysis is required.
6734 if (RHS->getNumProtocols() == 0) {
6735 // OK, if LHS is a superclass of RHS *and*
6736 // this superclass is assignment compatible with LHS.
6737 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006738 bool IsSuperClass =
6739 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6740 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006741 // OK if conversion of LHS to SuperClass results in narrowing of types
6742 // ; i.e., SuperClass may implement at least one of the protocols
6743 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6744 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6745 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006746 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006747 // If super class has no protocols, it is not a match.
6748 if (SuperClassInheritedProtocols.empty())
6749 return false;
6750
6751 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6752 LHSPE = LHS->qual_end();
6753 LHSPI != LHSPE; LHSPI++) {
6754 bool SuperImplementsProtocol = false;
6755 ObjCProtocolDecl *LHSProto = (*LHSPI);
6756
6757 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6758 SuperClassInheritedProtocols.begin(),
6759 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6760 ObjCProtocolDecl *SuperClassProto = (*I);
6761 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6762 SuperImplementsProtocol = true;
6763 break;
6764 }
6765 }
6766 if (!SuperImplementsProtocol)
6767 return false;
6768 }
6769 return true;
6770 }
6771 return false;
6772 }
Mike Stump1eb44332009-09-09 15:08:12 +00006773
John McCallc12c5bb2010-05-15 11:32:37 +00006774 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6775 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006776 LHSPI != LHSPE; LHSPI++) {
6777 bool RHSImplementsProtocol = false;
6778
6779 // If the RHS doesn't implement the protocol on the left, the types
6780 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00006781 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6782 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00006783 RHSPI != RHSPE; RHSPI++) {
6784 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006785 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00006786 break;
6787 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006788 }
6789 // FIXME: For better diagnostics, consider passing back the protocol name.
6790 if (!RHSImplementsProtocol)
6791 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006792 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006793 // The RHS implements all protocols listed on the LHS.
6794 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006795}
6796
Steve Naroff389bf462009-02-12 17:52:19 +00006797bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6798 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00006799 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6800 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006801
Steve Naroff14108da2009-07-10 23:34:53 +00006802 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00006803 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006804
6805 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6806 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00006807}
6808
Douglas Gregor569c3162010-08-07 11:51:51 +00006809bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6810 return canAssignObjCInterfaces(
6811 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6812 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6813}
6814
Mike Stump1eb44332009-09-09 15:08:12 +00006815/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00006816/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00006817/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00006818/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00006819bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6820 bool CompareUnqualified) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006821 if (getLangOpts().CPlusPlus)
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006822 return hasSameType(LHS, RHS);
6823
Douglas Gregor447234d2010-07-29 15:18:02 +00006824 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00006825}
6826
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006827bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00006828 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006829}
6830
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006831bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6832 return !mergeTypes(LHS, RHS, true).isNull();
6833}
6834
Peter Collingbourne48466752010-10-24 18:30:18 +00006835/// mergeTransparentUnionType - if T is a transparent union type and a member
6836/// of T is compatible with SubType, return the merged type, else return
6837/// QualType()
6838QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6839 bool OfBlockPointer,
6840 bool Unqualified) {
6841 if (const RecordType *UT = T->getAsUnionType()) {
6842 RecordDecl *UD = UT->getDecl();
6843 if (UD->hasAttr<TransparentUnionAttr>()) {
6844 for (RecordDecl::field_iterator it = UD->field_begin(),
6845 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00006846 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006847 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6848 if (!MT.isNull())
6849 return MT;
6850 }
6851 }
6852 }
6853
6854 return QualType();
6855}
6856
6857/// mergeFunctionArgumentTypes - merge two types which appear as function
6858/// argument types
6859QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6860 bool OfBlockPointer,
6861 bool Unqualified) {
6862 // GNU extension: two types are compatible if they appear as a function
6863 // argument, one of the types is a transparent union type and the other
6864 // type is compatible with a union member
6865 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6866 Unqualified);
6867 if (!lmerge.isNull())
6868 return lmerge;
6869
6870 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6871 Unqualified);
6872 if (!rmerge.isNull())
6873 return rmerge;
6874
6875 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6876}
6877
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006878QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00006879 bool OfBlockPointer,
6880 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00006881 const FunctionType *lbase = lhs->getAs<FunctionType>();
6882 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00006883 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6884 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00006885 bool allLTypes = true;
6886 bool allRTypes = true;
6887
6888 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006889 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006890 if (OfBlockPointer) {
6891 QualType RHS = rbase->getResultType();
6892 QualType LHS = lbase->getResultType();
6893 bool UnqualifiedResult = Unqualified;
6894 if (!UnqualifiedResult)
6895 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006896 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006897 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006898 else
John McCall8cc246c2010-12-15 01:06:38 +00006899 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6900 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006901 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006902
6903 if (Unqualified)
6904 retType = retType.getUnqualifiedType();
6905
6906 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6907 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6908 if (Unqualified) {
6909 LRetType = LRetType.getUnqualifiedType();
6910 RRetType = RRetType.getUnqualifiedType();
6911 }
6912
6913 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006914 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00006915 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006916 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00006917
Daniel Dunbar6a15c852010-04-28 16:20:58 +00006918 // FIXME: double check this
6919 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6920 // rbase->getRegParmAttr() != 0 &&
6921 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00006922 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6923 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00006924
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006925 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00006926 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006927 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006928
John McCall8cc246c2010-12-15 01:06:38 +00006929 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00006930 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6931 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00006932 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6933 return QualType();
6934
John McCallf85e1932011-06-15 23:02:42 +00006935 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6936 return QualType();
6937
John McCall8cc246c2010-12-15 01:06:38 +00006938 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6939 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00006940
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00006941 if (lbaseInfo.getNoReturn() != NoReturn)
6942 allLTypes = false;
6943 if (rbaseInfo.getNoReturn() != NoReturn)
6944 allRTypes = false;
6945
John McCallf85e1932011-06-15 23:02:42 +00006946 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00006947
Eli Friedman3d815e72008-08-22 00:56:42 +00006948 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00006949 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6950 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006951 unsigned lproto_nargs = lproto->getNumArgs();
6952 unsigned rproto_nargs = rproto->getNumArgs();
6953
6954 // Compatible functions must have the same number of arguments
6955 if (lproto_nargs != rproto_nargs)
6956 return QualType();
6957
6958 // Variadic and non-variadic functions aren't compatible
6959 if (lproto->isVariadic() != rproto->isVariadic())
6960 return QualType();
6961
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00006962 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6963 return QualType();
6964
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006965 if (LangOpts.ObjCAutoRefCount &&
6966 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6967 return QualType();
6968
Eli Friedman3d815e72008-08-22 00:56:42 +00006969 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00006970 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00006971 for (unsigned i = 0; i < lproto_nargs; i++) {
6972 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6973 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006974 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6975 OfBlockPointer,
6976 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006977 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006978
6979 if (Unqualified)
6980 argtype = argtype.getUnqualifiedType();
6981
Eli Friedman3d815e72008-08-22 00:56:42 +00006982 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00006983 if (Unqualified) {
6984 largtype = largtype.getUnqualifiedType();
6985 rargtype = rargtype.getUnqualifiedType();
6986 }
6987
Chris Lattner61710852008-10-05 17:34:18 +00006988 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6989 allLTypes = false;
6990 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6991 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00006992 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006993
Eli Friedman3d815e72008-08-22 00:56:42 +00006994 if (allLTypes) return lhs;
6995 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00006996
6997 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6998 EPI.ExtInfo = einfo;
Jordan Rosebea522f2013-03-08 21:51:21 +00006999 return getFunctionType(retType, types, EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00007000 }
7001
7002 if (lproto) allRTypes = false;
7003 if (rproto) allLTypes = false;
7004
Douglas Gregor72564e72009-02-26 23:50:07 +00007005 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00007006 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00007007 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00007008 if (proto->isVariadic()) return QualType();
7009 // Check that the types are compatible with the types that
7010 // would result from default argument promotions (C99 6.7.5.3p15).
7011 // The only types actually affected are promotable integer
7012 // types and floats, which would be passed as a different
7013 // type depending on whether the prototype is visible.
7014 unsigned proto_nargs = proto->getNumArgs();
7015 for (unsigned i = 0; i < proto_nargs; ++i) {
7016 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007017
Eli Friedmanc586d5d2012-08-30 00:44:15 +00007018 // Look at the converted type of enum types, since that is the type used
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007019 // to pass enum values.
Eli Friedmanc586d5d2012-08-30 00:44:15 +00007020 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
7021 argTy = Enum->getDecl()->getIntegerType();
7022 if (argTy.isNull())
7023 return QualType();
7024 }
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007025
Eli Friedman3d815e72008-08-22 00:56:42 +00007026 if (argTy->isPromotableIntegerType() ||
7027 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
7028 return QualType();
7029 }
7030
7031 if (allLTypes) return lhs;
7032 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00007033
7034 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7035 EPI.ExtInfo = einfo;
Reid Kleckner0567a792013-06-10 20:51:09 +00007036 return getFunctionType(retType, proto->getArgTypes(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00007037 }
7038
7039 if (allLTypes) return lhs;
7040 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00007041 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00007042}
7043
John McCallb9da7132013-03-21 00:10:07 +00007044/// Given that we have an enum type and a non-enum type, try to merge them.
7045static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7046 QualType other, bool isBlockReturnType) {
7047 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7048 // a signed integer type, or an unsigned integer type.
7049 // Compatibility is based on the underlying type, not the promotion
7050 // type.
7051 QualType underlyingType = ET->getDecl()->getIntegerType();
7052 if (underlyingType.isNull()) return QualType();
7053 if (Context.hasSameType(underlyingType, other))
7054 return other;
7055
7056 // In block return types, we're more permissive and accept any
7057 // integral type of the same size.
7058 if (isBlockReturnType && other->isIntegerType() &&
7059 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7060 return other;
7061
7062 return QualType();
7063}
7064
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007065QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00007066 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00007067 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00007068 // C++ [expr]: If an expression initially has the type "reference to T", the
7069 // type is adjusted to "T" prior to any further analysis, the expression
7070 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00007071 // expression is an lvalue unless the reference is an rvalue reference and
7072 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00007073 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7074 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00007075
7076 if (Unqualified) {
7077 LHS = LHS.getUnqualifiedType();
7078 RHS = RHS.getUnqualifiedType();
7079 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00007080
Eli Friedman3d815e72008-08-22 00:56:42 +00007081 QualType LHSCan = getCanonicalType(LHS),
7082 RHSCan = getCanonicalType(RHS);
7083
7084 // If two types are identical, they are compatible.
7085 if (LHSCan == RHSCan)
7086 return LHS;
7087
John McCall0953e762009-09-24 19:53:00 +00007088 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00007089 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7090 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00007091 if (LQuals != RQuals) {
7092 // If any of these qualifiers are different, we have a type
7093 // mismatch.
7094 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00007095 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7096 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00007097 return QualType();
7098
7099 // Exactly one GC qualifier difference is allowed: __strong is
7100 // okay if the other type has no GC qualifier but is an Objective
7101 // C object pointer (i.e. implicitly strong by default). We fix
7102 // this by pretending that the unqualified type was actually
7103 // qualified __strong.
7104 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7105 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7106 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7107
7108 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7109 return QualType();
7110
7111 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7112 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7113 }
7114 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7115 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7116 }
Eli Friedman3d815e72008-08-22 00:56:42 +00007117 return QualType();
John McCall0953e762009-09-24 19:53:00 +00007118 }
7119
7120 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00007121
Eli Friedman852d63b2009-06-01 01:22:52 +00007122 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7123 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00007124
Chris Lattner1adb8832008-01-14 05:45:46 +00007125 // We want to consider the two function types to be the same for these
7126 // comparisons, just force one to the other.
7127 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7128 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00007129
7130 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00007131 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7132 LHSClass = Type::ConstantArray;
7133 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7134 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00007135
John McCallc12c5bb2010-05-15 11:32:37 +00007136 // ObjCInterfaces are just specialized ObjCObjects.
7137 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7138 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7139
Nate Begeman213541a2008-04-18 23:10:10 +00007140 // Canonicalize ExtVector -> Vector.
7141 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7142 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00007143
Chris Lattnera36a61f2008-04-07 05:43:21 +00007144 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00007145 if (LHSClass != RHSClass) {
John McCallb9da7132013-03-21 00:10:07 +00007146 // Note that we only have special rules for turning block enum
7147 // returns into block int returns, not vice-versa.
John McCall183700f2009-09-21 23:43:11 +00007148 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCallb9da7132013-03-21 00:10:07 +00007149 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmanbab96962008-02-12 08:46:17 +00007150 }
John McCall183700f2009-09-21 23:43:11 +00007151 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCallb9da7132013-03-21 00:10:07 +00007152 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmanbab96962008-02-12 08:46:17 +00007153 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00007154 // allow block pointer type to match an 'id' type.
Fariborz Jahanian41963632012-01-26 17:08:50 +00007155 if (OfBlockPointer && !BlockReturnType) {
7156 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7157 return LHS;
7158 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7159 return RHS;
7160 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00007161
Eli Friedman3d815e72008-08-22 00:56:42 +00007162 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00007163 }
Eli Friedman3d815e72008-08-22 00:56:42 +00007164
Steve Naroff4a746782008-01-09 22:43:08 +00007165 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00007166 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00007167#define TYPE(Class, Base)
7168#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00007169#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00007170#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7171#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7172#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00007173 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00007174
Richard Smithdc7a4f52013-04-30 13:56:41 +00007175 case Type::Auto:
Sebastian Redl7c80bd62009-03-16 23:22:08 +00007176 case Type::LValueReference:
7177 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00007178 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00007179 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00007180
John McCallc12c5bb2010-05-15 11:32:37 +00007181 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00007182 case Type::IncompleteArray:
7183 case Type::VariableArray:
7184 case Type::FunctionProto:
7185 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00007186 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00007187
Chris Lattner1adb8832008-01-14 05:45:46 +00007188 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00007189 {
7190 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00007191 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7192 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007193 if (Unqualified) {
7194 LHSPointee = LHSPointee.getUnqualifiedType();
7195 RHSPointee = RHSPointee.getUnqualifiedType();
7196 }
7197 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7198 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00007199 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00007200 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00007201 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00007202 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00007203 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00007204 return getPointerType(ResultType);
7205 }
Steve Naroffc0febd52008-12-10 17:49:55 +00007206 case Type::BlockPointer:
7207 {
7208 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00007209 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7210 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007211 if (Unqualified) {
7212 LHSPointee = LHSPointee.getUnqualifiedType();
7213 RHSPointee = RHSPointee.getUnqualifiedType();
7214 }
7215 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7216 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00007217 if (ResultType.isNull()) return QualType();
7218 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7219 return LHS;
7220 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7221 return RHS;
7222 return getBlockPointerType(ResultType);
7223 }
Eli Friedmanb001de72011-10-06 23:00:33 +00007224 case Type::Atomic:
7225 {
7226 // Merge two pointer types, while trying to preserve typedef info
7227 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7228 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7229 if (Unqualified) {
7230 LHSValue = LHSValue.getUnqualifiedType();
7231 RHSValue = RHSValue.getUnqualifiedType();
7232 }
7233 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7234 Unqualified);
7235 if (ResultType.isNull()) return QualType();
7236 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7237 return LHS;
7238 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7239 return RHS;
7240 return getAtomicType(ResultType);
7241 }
Chris Lattner1adb8832008-01-14 05:45:46 +00007242 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00007243 {
7244 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7245 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7246 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7247 return QualType();
7248
7249 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7250 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007251 if (Unqualified) {
7252 LHSElem = LHSElem.getUnqualifiedType();
7253 RHSElem = RHSElem.getUnqualifiedType();
7254 }
7255
7256 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00007257 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00007258 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7259 return LHS;
7260 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7261 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00007262 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7263 ArrayType::ArraySizeModifier(), 0);
7264 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7265 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00007266 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7267 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00007268 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7269 return LHS;
7270 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7271 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00007272 if (LVAT) {
7273 // FIXME: This isn't correct! But tricky to implement because
7274 // the array's size has to be the size of LHS, but the type
7275 // has to be different.
7276 return LHS;
7277 }
7278 if (RVAT) {
7279 // FIXME: This isn't correct! But tricky to implement because
7280 // the array's size has to be the size of RHS, but the type
7281 // has to be different.
7282 return RHS;
7283 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00007284 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7285 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00007286 return getIncompleteArrayType(ResultType,
7287 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00007288 }
Chris Lattner1adb8832008-01-14 05:45:46 +00007289 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00007290 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00007291 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00007292 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00007293 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00007294 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00007295 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00007296 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00007297 case Type::Complex:
7298 // Distinct complex types are incompatible.
7299 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00007300 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00007301 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00007302 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7303 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00007304 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00007305 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00007306 case Type::ObjCObject: {
7307 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00007308 // FIXME: This should be type compatibility, e.g. whether
7309 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00007310 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7311 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7312 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00007313 return LHS;
7314
Eli Friedman3d815e72008-08-22 00:56:42 +00007315 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00007316 }
Steve Naroff14108da2009-07-10 23:34:53 +00007317 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007318 if (OfBlockPointer) {
7319 if (canAssignObjCInterfacesInBlockPointer(
7320 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00007321 RHS->getAs<ObjCObjectPointerType>(),
7322 BlockReturnType))
David Blaikie7530c032012-01-17 06:56:22 +00007323 return LHS;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007324 return QualType();
7325 }
John McCall183700f2009-09-21 23:43:11 +00007326 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7327 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00007328 return LHS;
7329
Steve Naroffbc76dd02008-12-10 22:14:21 +00007330 return QualType();
David Blaikie7530c032012-01-17 06:56:22 +00007331 }
Steve Naroffec0550f2007-10-15 20:41:53 +00007332 }
Douglas Gregor72564e72009-02-26 23:50:07 +00007333
David Blaikie7530c032012-01-17 06:56:22 +00007334 llvm_unreachable("Invalid Type::Class!");
Steve Naroffec0550f2007-10-15 20:41:53 +00007335}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00007336
Fariborz Jahanian78213e42011-09-28 21:52:05 +00007337bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7338 const FunctionProtoType *FromFunctionType,
7339 const FunctionProtoType *ToFunctionType) {
7340 if (FromFunctionType->hasAnyConsumedArgs() !=
7341 ToFunctionType->hasAnyConsumedArgs())
7342 return false;
7343 FunctionProtoType::ExtProtoInfo FromEPI =
7344 FromFunctionType->getExtProtoInfo();
7345 FunctionProtoType::ExtProtoInfo ToEPI =
7346 ToFunctionType->getExtProtoInfo();
7347 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
7348 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
7349 ArgIdx != NumArgs; ++ArgIdx) {
7350 if (FromEPI.ConsumedArguments[ArgIdx] !=
7351 ToEPI.ConsumedArguments[ArgIdx])
7352 return false;
7353 }
7354 return true;
7355}
7356
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007357/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7358/// 'RHS' attributes and returns the merged version; including for function
7359/// return types.
7360QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7361 QualType LHSCan = getCanonicalType(LHS),
7362 RHSCan = getCanonicalType(RHS);
7363 // If two types are identical, they are compatible.
7364 if (LHSCan == RHSCan)
7365 return LHS;
7366 if (RHSCan->isFunctionType()) {
7367 if (!LHSCan->isFunctionType())
7368 return QualType();
7369 QualType OldReturnType =
7370 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7371 QualType NewReturnType =
7372 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7373 QualType ResReturnType =
7374 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7375 if (ResReturnType.isNull())
7376 return QualType();
7377 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7378 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7379 // In either case, use OldReturnType to build the new function type.
7380 const FunctionType *F = LHS->getAs<FunctionType>();
7381 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00007382 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7383 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner0567a792013-06-10 20:51:09 +00007384 QualType ResultType =
7385 getFunctionType(OldReturnType, FPT->getArgTypes(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007386 return ResultType;
7387 }
7388 }
7389 return QualType();
7390 }
7391
7392 // If the qualifiers are different, the types can still be merged.
7393 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7394 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7395 if (LQuals != RQuals) {
7396 // If any of these qualifiers are different, we have a type mismatch.
7397 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7398 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7399 return QualType();
7400
7401 // Exactly one GC qualifier difference is allowed: __strong is
7402 // okay if the other type has no GC qualifier but is an Objective
7403 // C object pointer (i.e. implicitly strong by default). We fix
7404 // this by pretending that the unqualified type was actually
7405 // qualified __strong.
7406 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7407 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7408 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7409
7410 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7411 return QualType();
7412
7413 if (GC_L == Qualifiers::Strong)
7414 return LHS;
7415 if (GC_R == Qualifiers::Strong)
7416 return RHS;
7417 return QualType();
7418 }
7419
7420 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7421 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7422 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7423 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7424 if (ResQT == LHSBaseQT)
7425 return LHS;
7426 if (ResQT == RHSBaseQT)
7427 return RHS;
7428 }
7429 return QualType();
7430}
7431
Chris Lattner5426bf62008-04-07 07:01:58 +00007432//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00007433// Integer Predicates
7434//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00007435
Jay Foad4ba2a172011-01-12 09:06:06 +00007436unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00007437 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00007438 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007439 if (T->isBooleanType())
7440 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00007441 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00007442 return (unsigned)getTypeSize(T);
7443}
7444
Abramo Bagnara762f1592012-09-09 10:21:24 +00007445QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregorf6094622010-07-23 15:58:24 +00007446 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00007447
7448 // Turn <4 x signed int> -> <4 x unsigned int>
7449 if (const VectorType *VTy = T->getAs<VectorType>())
7450 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00007451 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00007452
7453 // For enums, we return the unsigned version of the base type.
7454 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00007455 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00007456
7457 const BuiltinType *BTy = T->getAs<BuiltinType>();
7458 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007459 switch (BTy->getKind()) {
7460 case BuiltinType::Char_S:
7461 case BuiltinType::SChar:
7462 return UnsignedCharTy;
7463 case BuiltinType::Short:
7464 return UnsignedShortTy;
7465 case BuiltinType::Int:
7466 return UnsignedIntTy;
7467 case BuiltinType::Long:
7468 return UnsignedLongTy;
7469 case BuiltinType::LongLong:
7470 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00007471 case BuiltinType::Int128:
7472 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00007473 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00007474 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007475 }
7476}
7477
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00007478ASTMutationListener::~ASTMutationListener() { }
7479
Richard Smith9dadfab2013-05-11 05:45:24 +00007480void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7481 QualType ReturnType) {}
Chris Lattner86df27b2009-06-14 00:45:47 +00007482
7483//===----------------------------------------------------------------------===//
7484// Builtin Type Computation
7485//===----------------------------------------------------------------------===//
7486
7487/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00007488/// pointer over the consumed characters. This returns the resultant type. If
7489/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7490/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7491/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00007492///
7493/// RequiresICE is filled in on return to indicate whether the value is required
7494/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00007495static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00007496 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00007497 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00007498 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00007499 // Modifiers.
7500 int HowLong = 0;
7501 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00007502 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007503
Chris Lattner33daae62010-10-01 22:42:38 +00007504 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00007505 bool Done = false;
7506 while (!Done) {
7507 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00007508 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007509 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00007510 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007511 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007512 case 'S':
7513 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7514 assert(!Signed && "Can't use 'S' modifier multiple times!");
7515 Signed = true;
7516 break;
7517 case 'U':
7518 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7519 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7520 Unsigned = true;
7521 break;
7522 case 'L':
7523 assert(HowLong <= 2 && "Can't have LLLL modifier");
7524 ++HowLong;
7525 break;
7526 }
7527 }
7528
7529 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00007530
Chris Lattner86df27b2009-06-14 00:45:47 +00007531 // Read the base type.
7532 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00007533 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00007534 case 'v':
7535 assert(HowLong == 0 && !Signed && !Unsigned &&
7536 "Bad modifiers used with 'v'!");
7537 Type = Context.VoidTy;
7538 break;
7539 case 'f':
7540 assert(HowLong == 0 && !Signed && !Unsigned &&
7541 "Bad modifiers used with 'f'!");
7542 Type = Context.FloatTy;
7543 break;
7544 case 'd':
7545 assert(HowLong < 2 && !Signed && !Unsigned &&
7546 "Bad modifiers used with 'd'!");
7547 if (HowLong)
7548 Type = Context.LongDoubleTy;
7549 else
7550 Type = Context.DoubleTy;
7551 break;
7552 case 's':
7553 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7554 if (Unsigned)
7555 Type = Context.UnsignedShortTy;
7556 else
7557 Type = Context.ShortTy;
7558 break;
7559 case 'i':
7560 if (HowLong == 3)
7561 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7562 else if (HowLong == 2)
7563 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7564 else if (HowLong == 1)
7565 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7566 else
7567 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7568 break;
7569 case 'c':
7570 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7571 if (Signed)
7572 Type = Context.SignedCharTy;
7573 else if (Unsigned)
7574 Type = Context.UnsignedCharTy;
7575 else
7576 Type = Context.CharTy;
7577 break;
7578 case 'b': // boolean
7579 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7580 Type = Context.BoolTy;
7581 break;
7582 case 'z': // size_t.
7583 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7584 Type = Context.getSizeType();
7585 break;
7586 case 'F':
7587 Type = Context.getCFConstantStringType();
7588 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00007589 case 'G':
7590 Type = Context.getObjCIdType();
7591 break;
7592 case 'H':
7593 Type = Context.getObjCSelType();
7594 break;
Fariborz Jahanianf7992132013-01-04 18:45:40 +00007595 case 'M':
7596 Type = Context.getObjCSuperType();
7597 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007598 case 'a':
7599 Type = Context.getBuiltinVaListType();
7600 assert(!Type.isNull() && "builtin va list type not initialized!");
7601 break;
7602 case 'A':
7603 // This is a "reference" to a va_list; however, what exactly
7604 // this means depends on how va_list is defined. There are two
7605 // different kinds of va_list: ones passed by value, and ones
7606 // passed by reference. An example of a by-value va_list is
7607 // x86, where va_list is a char*. An example of by-ref va_list
7608 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7609 // we want this argument to be a char*&; for x86-64, we want
7610 // it to be a __va_list_tag*.
7611 Type = Context.getBuiltinVaListType();
7612 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00007613 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00007614 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00007615 else
Chris Lattner86df27b2009-06-14 00:45:47 +00007616 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00007617 break;
7618 case 'V': {
7619 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00007620 unsigned NumElements = strtoul(Str, &End, 10);
7621 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00007622 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00007623
Chris Lattner14e0e742010-10-01 22:53:11 +00007624 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7625 RequiresICE, false);
7626 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00007627
7628 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00007629 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00007630 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00007631 break;
7632 }
Douglas Gregorb4bc99b2012-06-07 18:08:25 +00007633 case 'E': {
7634 char *End;
7635
7636 unsigned NumElements = strtoul(Str, &End, 10);
7637 assert(End != Str && "Missing vector size");
7638
7639 Str = End;
7640
7641 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7642 false);
7643 Type = Context.getExtVectorType(ElementType, NumElements);
7644 break;
7645 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00007646 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00007647 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7648 false);
7649 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00007650 Type = Context.getComplexType(ElementType);
7651 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00007652 }
7653 case 'Y' : {
7654 Type = Context.getPointerDiffType();
7655 break;
7656 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007657 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00007658 Type = Context.getFILEType();
7659 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007660 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00007661 return QualType();
7662 }
Mike Stumpfd612db2009-07-28 23:47:15 +00007663 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007664 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00007665 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00007666 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00007667 else
7668 Type = Context.getjmp_bufType();
7669
Mike Stumpfd612db2009-07-28 23:47:15 +00007670 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007671 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00007672 return QualType();
7673 }
7674 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00007675 case 'K':
7676 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7677 Type = Context.getucontext_tType();
7678
7679 if (Type.isNull()) {
7680 Error = ASTContext::GE_Missing_ucontext;
7681 return QualType();
7682 }
7683 break;
Eli Friedman6902e412012-11-27 02:58:24 +00007684 case 'p':
7685 Type = Context.getProcessIDType();
7686 break;
Mike Stump782fa302009-07-28 02:25:19 +00007687 }
Mike Stump1eb44332009-09-09 15:08:12 +00007688
Chris Lattner33daae62010-10-01 22:42:38 +00007689 // If there are modifiers and if we're allowed to parse them, go for it.
7690 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00007691 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00007692 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00007693 default: Done = true; --Str; break;
7694 case '*':
7695 case '&': {
7696 // Both pointers and references can have their pointee types
7697 // qualified with an address space.
7698 char *End;
7699 unsigned AddrSpace = strtoul(Str, &End, 10);
7700 if (End != Str && AddrSpace != 0) {
7701 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7702 Str = End;
7703 }
7704 if (c == '*')
7705 Type = Context.getPointerType(Type);
7706 else
7707 Type = Context.getLValueReferenceType(Type);
7708 break;
7709 }
7710 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7711 case 'C':
7712 Type = Type.withConst();
7713 break;
7714 case 'D':
7715 Type = Context.getVolatileType(Type);
7716 break;
Ted Kremenek18932a02012-01-20 21:40:12 +00007717 case 'R':
7718 Type = Type.withRestrict();
7719 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007720 }
7721 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00007722
Chris Lattner14e0e742010-10-01 22:53:11 +00007723 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00007724 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00007725
Chris Lattner86df27b2009-06-14 00:45:47 +00007726 return Type;
7727}
7728
7729/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00007730QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00007731 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00007732 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00007733 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00007734
Chris Lattner5f9e2722011-07-23 10:55:15 +00007735 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00007736
Chris Lattner14e0e742010-10-01 22:53:11 +00007737 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00007738 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00007739 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7740 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007741 if (Error != GE_None)
7742 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00007743
7744 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7745
Chris Lattner86df27b2009-06-14 00:45:47 +00007746 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00007747 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007748 if (Error != GE_None)
7749 return QualType();
7750
Chris Lattner14e0e742010-10-01 22:53:11 +00007751 // If this argument is required to be an IntegerConstantExpression and the
7752 // caller cares, fill in the bitmask we return.
7753 if (RequiresICE && IntegerConstantArgs)
7754 *IntegerConstantArgs |= 1 << ArgTypes.size();
7755
Chris Lattner86df27b2009-06-14 00:45:47 +00007756 // Do array -> pointer decay. The builtin should use the decayed type.
7757 if (Ty->isArrayType())
7758 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00007759
Chris Lattner86df27b2009-06-14 00:45:47 +00007760 ArgTypes.push_back(Ty);
7761 }
7762
7763 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7764 "'.' should only occur at end of builtin type list!");
7765
John McCall00ccbef2010-12-21 00:44:39 +00007766 FunctionType::ExtInfo EI;
7767 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7768
7769 bool Variadic = (TypeStr[0] == '.');
7770
7771 // We really shouldn't be making a no-proto type here, especially in C++.
7772 if (ArgTypes.empty() && Variadic)
7773 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00007774
John McCalle23cf432010-12-14 08:05:40 +00007775 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00007776 EPI.ExtInfo = EI;
7777 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00007778
Jordan Rosebea522f2013-03-08 21:51:21 +00007779 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00007780}
Eli Friedmana95d7572009-08-19 07:44:53 +00007781
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007782GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007783 if (!FD->isExternallyVisible())
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007784 return GVA_Internal;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007785
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007786 GVALinkage External = GVA_StrongExternal;
7787 switch (FD->getTemplateSpecializationKind()) {
7788 case TSK_Undeclared:
7789 case TSK_ExplicitSpecialization:
7790 External = GVA_StrongExternal;
7791 break;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007792
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007793 case TSK_ExplicitInstantiationDefinition:
7794 return GVA_ExplicitTemplateInstantiation;
7795
7796 case TSK_ExplicitInstantiationDeclaration:
7797 case TSK_ImplicitInstantiation:
7798 External = GVA_TemplateInstantiation;
7799 break;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007800 }
7801
7802 if (!FD->isInlined())
7803 return External;
7804
David Blaikie4e4d0842012-03-11 07:00:24 +00007805 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007806 // GNU or C99 inline semantics. Determine whether this symbol should be
7807 // externally visible.
7808 if (FD->isInlineDefinitionExternallyVisible())
7809 return External;
7810
7811 // C99 inline semantics, where the symbol is not externally visible.
7812 return GVA_C99Inline;
7813 }
7814
7815 // C++0x [temp.explicit]p9:
7816 // [ Note: The intent is that an inline function that is the subject of
7817 // an explicit instantiation declaration will still be implicitly
7818 // instantiated when used so that the body can be considered for
7819 // inlining, but that no out-of-line copy of the inline function would be
7820 // generated in the translation unit. -- end note ]
7821 if (FD->getTemplateSpecializationKind()
7822 == TSK_ExplicitInstantiationDeclaration)
7823 return GVA_C99Inline;
7824
7825 return GVA_CXXInline;
7826}
7827
7828GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007829 if (!VD->isExternallyVisible())
7830 return GVA_Internal;
7831
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007832 // If this is a static data member, compute the kind of template
7833 // specialization. Otherwise, this variable is not part of a
7834 // template.
7835 TemplateSpecializationKind TSK = TSK_Undeclared;
7836 if (VD->isStaticDataMember())
7837 TSK = VD->getTemplateSpecializationKind();
7838
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007839 switch (TSK) {
7840 case TSK_Undeclared:
7841 case TSK_ExplicitSpecialization:
7842 return GVA_StrongExternal;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007843
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007844 case TSK_ExplicitInstantiationDeclaration:
7845 llvm_unreachable("Variable should not be instantiated");
7846 // Fall through to treat this like any other instantiation.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007847
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007848 case TSK_ExplicitInstantiationDefinition:
7849 return GVA_ExplicitTemplateInstantiation;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007850
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007851 case TSK_ImplicitInstantiation:
7852 return GVA_TemplateInstantiation;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007853 }
Rafael Espindola77b50252013-05-13 14:05:53 +00007854
7855 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007856}
7857
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00007858bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007859 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7860 if (!VD->isFileVarDecl())
7861 return false;
Richard Smithf396ad92013-04-01 20:22:16 +00007862 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7863 // We never need to emit an uninstantiated function template.
7864 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7865 return false;
7866 } else
7867 return false;
7868
7869 // If this is a member of a class template, we do not need to emit it.
7870 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007871 return false;
7872
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007873 // Weak references don't produce any output by themselves.
7874 if (D->hasAttr<WeakRefAttr>())
7875 return false;
7876
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007877 // Aliases and used decls are required.
7878 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7879 return true;
7880
7881 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7882 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00007883 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00007884 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007885
7886 // Constructors and destructors are required.
7887 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7888 return true;
7889
John McCalld5617ee2013-01-25 22:31:03 +00007890 // The key function for a class is required. This rule only comes
7891 // into play when inline functions can be key functions, though.
7892 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7893 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7894 const CXXRecordDecl *RD = MD->getParent();
7895 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7896 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7897 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7898 return true;
7899 }
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007900 }
7901 }
7902
7903 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7904
7905 // static, static inline, always_inline, and extern inline functions can
7906 // always be deferred. Normal inline functions can be deferred in C99/C++.
7907 // Implicit template instantiations can also be deferred in C++.
7908 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev3a5aca82012-02-02 06:06:34 +00007909 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007910 return false;
7911 return true;
7912 }
Douglas Gregor94da1582011-09-10 00:22:34 +00007913
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007914 const VarDecl *VD = cast<VarDecl>(D);
7915 assert(VD->isFileVarDecl() && "Expected file scoped var");
7916
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007917 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7918 return false;
7919
Richard Smith5f9a7e32012-11-12 21:38:00 +00007920 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007921 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smith5f9a7e32012-11-12 21:38:00 +00007922 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7923 return true;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007924
Richard Smith5f9a7e32012-11-12 21:38:00 +00007925 // Variables that have destruction with side-effects are required.
7926 if (VD->getType().isDestructedType())
7927 return true;
7928
7929 // Variables that have initialization with side-effects are required.
7930 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7931 return true;
7932
7933 return false;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007934}
Charles Davis071cc7d2010-08-16 03:33:14 +00007935
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007936CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davisee743f92010-11-09 18:04:24 +00007937 // Pass through to the C++ ABI object
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007938 return ABI->getDefaultMethodCallConv(isVariadic);
7939}
7940
7941CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
John McCallb8b2c9d2013-01-25 22:30:49 +00007942 if (CC == CC_C && !LangOpts.MRTD &&
7943 getTargetInfo().getCXXABI().isMemberFunctionCCDefault())
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007944 return CC_Default;
7945 return CC;
Charles Davisee743f92010-11-09 18:04:24 +00007946}
7947
Jay Foad4ba2a172011-01-12 09:06:06 +00007948bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00007949 // Pass through to the C++ ABI object
7950 return ABI->isNearlyEmpty(RD);
7951}
7952
Peter Collingbourne14110472011-01-13 18:57:25 +00007953MangleContext *ASTContext::createMangleContext() {
John McCallb8b2c9d2013-01-25 22:30:49 +00007954 switch (Target->getCXXABI().getKind()) {
Tim Northoverc264e162013-01-31 12:13:10 +00007955 case TargetCXXABI::GenericAArch64:
John McCallb8b2c9d2013-01-25 22:30:49 +00007956 case TargetCXXABI::GenericItanium:
7957 case TargetCXXABI::GenericARM:
7958 case TargetCXXABI::iOS:
Peter Collingbourne14110472011-01-13 18:57:25 +00007959 return createItaniumMangleContext(*this, getDiagnostics());
John McCallb8b2c9d2013-01-25 22:30:49 +00007960 case TargetCXXABI::Microsoft:
Peter Collingbourne14110472011-01-13 18:57:25 +00007961 return createMicrosoftMangleContext(*this, getDiagnostics());
7962 }
David Blaikieb219cfc2011-09-23 05:06:16 +00007963 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00007964}
7965
Charles Davis071cc7d2010-08-16 03:33:14 +00007966CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00007967
7968size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00007969 return ASTRecordLayouts.getMemorySize()
7970 + llvm::capacity_in_bytes(ObjCLayouts)
7971 + llvm::capacity_in_bytes(KeyFunctions)
7972 + llvm::capacity_in_bytes(ObjCImpls)
7973 + llvm::capacity_in_bytes(BlockVarCopyInits)
7974 + llvm::capacity_in_bytes(DeclAttrs)
7975 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7976 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7977 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7978 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7979 + llvm::capacity_in_bytes(OverriddenMethods)
7980 + llvm::capacity_in_bytes(Types)
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007981 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet0d95f0d2011-08-14 14:28:49 +00007982 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00007983}
Ted Kremenekd211cb72011-10-06 05:00:56 +00007984
Eli Friedman5e867c82013-07-10 00:30:46 +00007985void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
7986 if (Number > 1)
7987 MangleNumbers[ND] = Number;
David Blaikie66cff722012-11-14 01:52:05 +00007988}
7989
Eli Friedman5e867c82013-07-10 00:30:46 +00007990unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
7991 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
7992 MangleNumbers.find(ND);
7993 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie66cff722012-11-14 01:52:05 +00007994}
7995
Eli Friedman5e867c82013-07-10 00:30:46 +00007996MangleNumberingContext &
7997ASTContext::getManglingNumberContext(const DeclContext *DC) {
Eli Friedman07369dd2013-07-01 20:22:57 +00007998 return MangleNumberingContexts[DC];
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00007999}
8000
Ted Kremenekd211cb72011-10-06 05:00:56 +00008001void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8002 ParamIndices[D] = index;
8003}
8004
8005unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8006 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8007 assert(I != ParamIndices.end() &&
8008 "ParmIndices lacks entry set by ParmVarDecl");
8009 return I->second;
8010}
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00008011
Richard Smith211c8dd2013-06-05 00:46:14 +00008012APValue *
8013ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8014 bool MayCreate) {
8015 assert(E && E->getStorageDuration() == SD_Static &&
8016 "don't need to cache the computed value for this temporary");
8017 if (MayCreate)
8018 return &MaterializedTemporaryValues[E];
8019
8020 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8021 MaterializedTemporaryValues.find(E);
8022 return I == MaterializedTemporaryValues.end() ? 0 : &I->second;
8023}
8024
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00008025bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8026 const llvm::Triple &T = getTargetInfo().getTriple();
8027 if (!T.isOSDarwin())
8028 return false;
8029
8030 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8031 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8032 uint64_t Size = sizeChars.getQuantity();
8033 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8034 unsigned Align = alignChars.getQuantity();
8035 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8036 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8037}
Reid Klecknercff15122013-06-17 12:56:08 +00008038
8039namespace {
8040
8041 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8042 /// parents as defined by the \c RecursiveASTVisitor.
8043 ///
8044 /// Note that the relationship described here is purely in terms of AST
8045 /// traversal - there are other relationships (for example declaration context)
8046 /// in the AST that are better modeled by special matchers.
8047 ///
8048 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8049 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8050
8051 public:
8052 /// \brief Builds and returns the translation unit's parent map.
8053 ///
8054 /// The caller takes ownership of the returned \c ParentMap.
8055 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8056 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8057 Visitor.TraverseDecl(&TU);
8058 return Visitor.Parents;
8059 }
8060
8061 private:
8062 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8063
8064 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8065 }
8066
8067 bool shouldVisitTemplateInstantiations() const {
8068 return true;
8069 }
8070 bool shouldVisitImplicitCode() const {
8071 return true;
8072 }
8073 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8074 // are not triggered during data recursion.
8075 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8076 return false;
8077 }
8078
8079 template <typename T>
8080 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
8081 if (Node == NULL)
8082 return true;
8083 if (ParentStack.size() > 0)
8084 // FIXME: Currently we add the same parent multiple times, for example
8085 // when we visit all subexpressions of template instantiations; this is
8086 // suboptimal, bug benign: the only way to visit those is with
8087 // hasAncestor / hasParent, and those do not create new matches.
8088 // The plan is to enable DynTypedNode to be storable in a map or hash
8089 // map. The main problem there is to implement hash functions /
8090 // comparison operators for all types that DynTypedNode supports that
8091 // do not have pointer identity.
8092 (*Parents)[Node].push_back(ParentStack.back());
8093 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8094 bool Result = (this ->* traverse) (Node);
8095 ParentStack.pop_back();
8096 return Result;
8097 }
8098
8099 bool TraverseDecl(Decl *DeclNode) {
8100 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8101 }
8102
8103 bool TraverseStmt(Stmt *StmtNode) {
8104 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8105 }
8106
8107 ASTContext::ParentMap *Parents;
8108 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8109
8110 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8111 };
8112
8113} // end namespace
8114
8115ASTContext::ParentVector
8116ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8117 assert(Node.getMemoizationData() &&
8118 "Invariant broken: only nodes that support memoization may be "
8119 "used in the parent map.");
8120 if (!AllParents) {
8121 // We always need to run over the whole translation unit, as
8122 // hasAncestor can escape any subtree.
8123 AllParents.reset(
8124 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8125 }
8126 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8127 if (I == AllParents->end()) {
8128 return ParentVector();
8129 }
8130 return I->second;
8131}