blob: 870e09cc674ab8c7802d3aa1631d6df14c5625ac [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 {
861 if (!Float128StubDecl) {
862 Float128StubDecl = RecordDecl::Create(const_cast<ASTContext &>(*this),
863 TTK_Struct,
864 getTranslationUnitDecl(),
865 SourceLocation(),
866 SourceLocation(),
867 &Idents.get("__float128"));
868 }
869
870 return Float128StubDecl;
871}
872
John McCalle27ec8a2009-10-23 23:03:21 +0000873void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000874 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000875 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000876 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000877}
878
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000879void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
880 assert((!this->Target || this->Target == &Target) &&
881 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000882 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000883
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000884 this->Target = &Target;
885
886 ABI.reset(createCXXABI(Target));
887 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
888
Reid Spencer5f016e22007-07-11 17:01:13 +0000889 // C99 6.2.5p19.
890 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000891
Reid Spencer5f016e22007-07-11 17:01:13 +0000892 // C99 6.2.5p2.
893 InitBuiltinType(BoolTy, BuiltinType::Bool);
894 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000895 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000896 InitBuiltinType(CharTy, BuiltinType::Char_S);
897 else
898 InitBuiltinType(CharTy, BuiltinType::Char_U);
899 // C99 6.2.5p4.
900 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
901 InitBuiltinType(ShortTy, BuiltinType::Short);
902 InitBuiltinType(IntTy, BuiltinType::Int);
903 InitBuiltinType(LongTy, BuiltinType::Long);
904 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000905
Reid Spencer5f016e22007-07-11 17:01:13 +0000906 // C99 6.2.5p6.
907 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
908 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
909 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
910 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
911 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000912
Reid Spencer5f016e22007-07-11 17:01:13 +0000913 // C99 6.2.5p10.
914 InitBuiltinType(FloatTy, BuiltinType::Float);
915 InitBuiltinType(DoubleTy, BuiltinType::Double);
916 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000917
Chris Lattner2df9ced2009-04-30 02:43:43 +0000918 // GNU extension, 128-bit integers.
919 InitBuiltinType(Int128Ty, BuiltinType::Int128);
920 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
921
Hans Wennborg15f92ba2013-05-10 10:08:40 +0000922 // C++ 3.9.1p5
923 if (TargetInfo::isTypeSigned(Target.getWCharType()))
924 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
925 else // -fshort-wchar makes wchar_t be unsigned.
926 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
927 if (LangOpts.CPlusPlus && LangOpts.WChar)
928 WideCharTy = WCharTy;
929 else {
930 // C99 (or C++ using -fno-wchar).
931 WideCharTy = getFromTargetType(Target.getWCharType());
932 }
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000933
James Molloy392da482012-05-04 10:55:22 +0000934 WIntTy = getFromTargetType(Target.getWIntType());
935
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000936 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
937 InitBuiltinType(Char16Ty, BuiltinType::Char16);
938 else // C99
939 Char16Ty = getFromTargetType(Target.getChar16Type());
940
941 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
942 InitBuiltinType(Char32Ty, BuiltinType::Char32);
943 else // C99
944 Char32Ty = getFromTargetType(Target.getChar32Type());
945
Douglas Gregor898574e2008-12-05 23:32:09 +0000946 // Placeholder type for type-dependent expressions whose type is
947 // completely unknown. No code should ever check a type against
948 // DependentTy and users should never see it; however, it is here to
949 // help diagnose failures to properly check for type-dependent
950 // expressions.
951 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000952
John McCall2a984ca2010-10-12 00:20:44 +0000953 // Placeholder type for functions.
954 InitBuiltinType(OverloadTy, BuiltinType::Overload);
955
John McCall864c0412011-04-26 20:42:42 +0000956 // Placeholder type for bound members.
957 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
958
John McCall3c3b7f92011-10-25 17:37:35 +0000959 // Placeholder type for pseudo-objects.
960 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
961
John McCall1de4d4e2011-04-07 08:22:57 +0000962 // "any" type; useful for debugger-like clients.
963 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
964
John McCall0ddaeb92011-10-17 18:09:15 +0000965 // Placeholder type for unbridged ARC casts.
966 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
967
Eli Friedmana6c66ce2012-08-31 00:14:07 +0000968 // Placeholder type for builtin functions.
969 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
970
Reid Spencer5f016e22007-07-11 17:01:13 +0000971 // C99 6.2.5p11.
972 FloatComplexTy = getComplexType(FloatTy);
973 DoubleComplexTy = getComplexType(DoubleTy);
974 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000975
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000976 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000977 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
978 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000979 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeib13621d2012-12-18 14:38:23 +0000980
981 if (LangOpts.OpenCL) {
982 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
983 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
984 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
985 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
986 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
987 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000988
Guy Benyei21f18c42013-02-07 10:55:47 +0000989 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000990 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeib13621d2012-12-18 14:38:23 +0000991 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000992
993 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian93a49942012-04-16 21:03:30 +0000994 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
995 SignedCharTy : BoolTy);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000996
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000997 ObjCConstantStringType = QualType();
Fariborz Jahanianf7992132013-01-04 18:45:40 +0000998
999 ObjCSuperType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001000
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001001 // void * type
1002 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001003
1004 // nullptr type (C++0x 2.14.7)
1005 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001006
1007 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1008 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingefb40e3f2012-07-01 15:57:25 +00001009
1010 // Builtin type used to help define __builtin_va_list.
1011 VaListTagTy = QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001012}
1013
David Blaikied6471f72011-09-25 23:23:43 +00001014DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001015 return SourceMgr.getDiagnostics();
1016}
1017
Douglas Gregor63200642010-08-30 16:49:28 +00001018AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1019 AttrVec *&Result = DeclAttrs[D];
1020 if (!Result) {
1021 void *Mem = Allocate(sizeof(AttrVec));
1022 Result = new (Mem) AttrVec;
1023 }
1024
1025 return *Result;
1026}
1027
1028/// \brief Erase the attributes corresponding to the given declaration.
1029void ASTContext::eraseDeclAttrs(const Decl *D) {
1030 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1031 if (Pos != DeclAttrs.end()) {
1032 Pos->second->~AttrVec();
1033 DeclAttrs.erase(Pos);
1034 }
1035}
1036
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001037MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +00001038ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001039 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +00001040 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +00001041 = InstantiatedFromStaticDataMember.find(Var);
1042 if (Pos == InstantiatedFromStaticDataMember.end())
1043 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001044
Douglas Gregor7caa6822009-07-24 20:34:43 +00001045 return Pos->second;
1046}
1047
Mike Stump1eb44332009-09-09 15:08:12 +00001048void
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001049ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +00001050 TemplateSpecializationKind TSK,
1051 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001052 assert(Inst->isStaticDataMember() && "Not a static data member");
1053 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1054 assert(!InstantiatedFromStaticDataMember[Inst] &&
1055 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001056 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +00001057 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +00001058}
1059
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001060FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1061 const FunctionDecl *FD){
1062 assert(FD && "Specialization is 0");
1063 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +00001064 = ClassScopeSpecializationPattern.find(FD);
1065 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001066 return 0;
1067
1068 return Pos->second;
1069}
1070
1071void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1072 FunctionDecl *Pattern) {
1073 assert(FD && "Specialization is 0");
1074 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +00001075 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001076}
1077
John McCall7ba107a2009-11-18 02:36:19 +00001078NamedDecl *
John McCalled976492009-12-04 22:46:56 +00001079ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +00001080 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +00001081 = InstantiatedFromUsingDecl.find(UUD);
1082 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +00001083 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001084
Anders Carlsson0d8df782009-08-29 19:37:28 +00001085 return Pos->second;
1086}
1087
1088void
John McCalled976492009-12-04 22:46:56 +00001089ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1090 assert((isa<UsingDecl>(Pattern) ||
1091 isa<UnresolvedUsingValueDecl>(Pattern) ||
1092 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1093 "pattern decl is not a using decl");
1094 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1095 InstantiatedFromUsingDecl[Inst] = Pattern;
1096}
1097
1098UsingShadowDecl *
1099ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1100 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1101 = InstantiatedFromUsingShadowDecl.find(Inst);
1102 if (Pos == InstantiatedFromUsingShadowDecl.end())
1103 return 0;
1104
1105 return Pos->second;
1106}
1107
1108void
1109ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1110 UsingShadowDecl *Pattern) {
1111 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1112 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00001113}
1114
Anders Carlssond8b285f2009-09-01 04:26:58 +00001115FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1116 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1117 = InstantiatedFromUnnamedFieldDecl.find(Field);
1118 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1119 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001120
Anders Carlssond8b285f2009-09-01 04:26:58 +00001121 return Pos->second;
1122}
1123
1124void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1125 FieldDecl *Tmpl) {
1126 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1127 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1128 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1129 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +00001130
Anders Carlssond8b285f2009-09-01 04:26:58 +00001131 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1132}
1133
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +00001134bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
1135 const FieldDecl *LastFD) const {
1136 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001137 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +00001138}
1139
Fariborz Jahanian340fa242011-05-02 17:20:56 +00001140bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
1141 const FieldDecl *LastFD) const {
1142 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001143 FD->getBitWidthValue(*this) == 0 &&
1144 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +00001145}
1146
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001147bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
1148 const FieldDecl *LastFD) const {
1149 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001150 FD->getBitWidthValue(*this) &&
1151 LastFD->getBitWidthValue(*this));
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001152}
1153
Chad Rosierdd7fddb2011-08-04 23:34:15 +00001154bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001155 const FieldDecl *LastFD) const {
1156 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001157 LastFD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001158}
1159
Chad Rosierdd7fddb2011-08-04 23:34:15 +00001160bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001161 const FieldDecl *LastFD) const {
1162 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001163 FD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001164}
1165
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001166ASTContext::overridden_cxx_method_iterator
1167ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1168 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001169 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001170 if (Pos == OverriddenMethods.end())
1171 return 0;
1172
1173 return Pos->second.begin();
1174}
1175
1176ASTContext::overridden_cxx_method_iterator
1177ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1178 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001179 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001180 if (Pos == OverriddenMethods.end())
1181 return 0;
1182
1183 return Pos->second.end();
1184}
1185
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001186unsigned
1187ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1188 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001189 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001190 if (Pos == OverriddenMethods.end())
1191 return 0;
1192
1193 return Pos->second.size();
1194}
1195
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001196void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1197 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001198 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001199 OverriddenMethods[Method].push_back(Overridden);
1200}
1201
Dmitri Gribenko1e905da2012-11-03 14:24:57 +00001202void ASTContext::getOverriddenMethods(
1203 const NamedDecl *D,
1204 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001205 assert(D);
1206
1207 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis685d1042013-04-17 00:09:03 +00001208 Overridden.append(overridden_methods_begin(CXXMethod),
1209 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001210 return;
1211 }
1212
1213 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1214 if (!Method)
1215 return;
1216
Argyrios Kyrtzidis740ae672012-10-09 18:19:01 +00001217 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1218 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisbc0a2bb2012-10-09 20:08:43 +00001219 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001220}
1221
Douglas Gregore6649772011-12-03 00:30:27 +00001222void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1223 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1224 assert(!Import->isFromASTFile() && "Non-local import declaration");
1225 if (!FirstLocalImport) {
1226 FirstLocalImport = Import;
1227 LastLocalImport = Import;
1228 return;
1229 }
1230
1231 LastLocalImport->NextLocalImport = Import;
1232 LastLocalImport = Import;
1233}
1234
Chris Lattner464175b2007-07-18 17:52:12 +00001235//===----------------------------------------------------------------------===//
1236// Type Sizing and Analysis
1237//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +00001238
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001239/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1240/// scalar floating point type.
1241const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +00001242 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001243 assert(BT && "Not a floating point type!");
1244 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001245 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001246 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001247 case BuiltinType::Float: return Target->getFloatFormat();
1248 case BuiltinType::Double: return Target->getDoubleFormat();
1249 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001250 }
1251}
1252
Ken Dyck8b752f12010-01-27 17:10:57 +00001253/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +00001254/// specified decl. Note that bitfields do not have a valid alignment, so
1255/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +00001256/// If @p RefAsPointee, references are treated like their underlying type
1257/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +00001258CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001259 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +00001260
John McCall4081a5c2010-10-08 18:24:19 +00001261 bool UseAlignAttrOnly = false;
1262 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1263 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +00001264
John McCall4081a5c2010-10-08 18:24:19 +00001265 // __attribute__((aligned)) can increase or decrease alignment
1266 // *except* on a struct or struct member, where it only increases
1267 // alignment unless 'packed' is also specified.
1268 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +00001269 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +00001270 // ignore that possibility; Sema should diagnose it.
1271 if (isa<FieldDecl>(D)) {
1272 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1273 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1274 } else {
1275 UseAlignAttrOnly = true;
1276 }
1277 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +00001278 else if (isa<FieldDecl>(D))
1279 UseAlignAttrOnly =
1280 D->hasAttr<PackedAttr>() ||
1281 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +00001282
John McCallba4f5d52011-01-20 07:57:12 +00001283 // If we're using the align attribute only, just ignore everything
1284 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +00001285 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +00001286 // do nothing
1287
John McCall4081a5c2010-10-08 18:24:19 +00001288 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001289 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001290 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001291 if (RefAsPointee)
1292 T = RT->getPointeeType();
1293 else
1294 T = getPointerType(RT->getPointeeType());
1295 }
1296 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +00001297 // Adjust alignments of declarations with array type by the
1298 // large-array alignment on the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001299 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +00001300 const ArrayType *arrayType;
1301 if (MinWidth && (arrayType = getAsArrayType(T))) {
1302 if (isa<VariableArrayType>(arrayType))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001303 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall3b657512011-01-19 10:06:00 +00001304 else if (isa<ConstantArrayType>(arrayType) &&
1305 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001306 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +00001307
John McCall3b657512011-01-19 10:06:00 +00001308 // Walk through any array types while we're at it.
1309 T = getBaseElementType(arrayType);
1310 }
Chad Rosier9f1210c2011-07-26 07:03:04 +00001311 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigand6b203512013-05-06 16:23:57 +00001312 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1313 if (VD->hasGlobalStorage())
1314 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1315 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001316 }
John McCallba4f5d52011-01-20 07:57:12 +00001317
1318 // Fields can be subject to extra alignment constraints, like if
1319 // the field is packed, the struct is packed, or the struct has a
1320 // a max-field-alignment constraint (#pragma pack). So calculate
1321 // the actual alignment of the field within the struct, and then
1322 // (as we're expected to) constrain that by the alignment of the type.
1323 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1324 // So calculate the alignment of the field.
1325 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1326
1327 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +00001328 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +00001329
1330 // Use the GCD of that and the offset within the record.
1331 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1332 if (offset > 0) {
1333 // Alignment is always a power of 2, so the GCD will be a power of 2,
1334 // which means we get to do this crazy thing instead of Euclid's.
1335 uint64_t lowBitOfOffset = offset & (~offset + 1);
1336 if (lowBitOfOffset < fieldAlign)
1337 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1338 }
1339
1340 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +00001341 }
Chris Lattneraf707ab2009-01-24 21:53:27 +00001342 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001343
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001344 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001345}
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001346
John McCall929bbfb2012-08-21 04:10:00 +00001347// getTypeInfoDataSizeInChars - Return the size of a type, in
1348// chars. If the type is a record, its data size is returned. This is
1349// the size of the memcpy that's performed when assigning this type
1350// using a trivial copy/move assignment operator.
1351std::pair<CharUnits, CharUnits>
1352ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1353 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1354
1355 // In C++, objects can sometimes be allocated into the tail padding
1356 // of a base-class subobject. We decide whether that's possible
1357 // during class layout, so here we can just trust the layout results.
1358 if (getLangOpts().CPlusPlus) {
1359 if (const RecordType *RT = T->getAs<RecordType>()) {
1360 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1361 sizeAndAlign.first = layout.getDataSize();
1362 }
1363 }
1364
1365 return sizeAndAlign;
1366}
1367
Richard Trieu910f17e2013-05-14 21:59:17 +00001368/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1369/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1370std::pair<CharUnits, CharUnits>
1371static getConstantArrayInfoInChars(const ASTContext &Context,
1372 const ConstantArrayType *CAT) {
1373 std::pair<CharUnits, CharUnits> EltInfo =
1374 Context.getTypeInfoInChars(CAT->getElementType());
1375 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieu1069b732013-05-14 23:41:50 +00001376 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1377 (uint64_t)(-1)/Size) &&
Richard Trieu910f17e2013-05-14 21:59:17 +00001378 "Overflow in array type char size evaluation");
1379 uint64_t Width = EltInfo.first.getQuantity() * Size;
1380 unsigned Align = EltInfo.second.getQuantity();
1381 Width = llvm::RoundUpToAlignment(Width, Align);
1382 return std::make_pair(CharUnits::fromQuantity(Width),
1383 CharUnits::fromQuantity(Align));
1384}
1385
John McCallea1471e2010-05-20 01:18:31 +00001386std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001387ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001388 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1389 return getConstantArrayInfoInChars(*this, CAT);
John McCallea1471e2010-05-20 01:18:31 +00001390 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001391 return std::make_pair(toCharUnitsFromBits(Info.first),
1392 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +00001393}
1394
1395std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001396ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +00001397 return getTypeInfoInChars(T.getTypePtr());
1398}
1399
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001400std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1401 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1402 if (it != MemoizedTypeInfo.end())
1403 return it->second;
1404
1405 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1406 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1407 return Info;
1408}
1409
1410/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1411/// method does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +00001412///
1413/// FIXME: Pointers into different addr spaces could have different sizes and
1414/// alignment requirements: getPointerInfo should take an AddrSpace, this
1415/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001416std::pair<uint64_t, unsigned>
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001417ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +00001418 uint64_t Width=0;
1419 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +00001420 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001421#define TYPE(Class, Base)
1422#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +00001423#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +00001424#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1425#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +00001426 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +00001427
Chris Lattner692233e2007-07-13 22:27:08 +00001428 case Type::FunctionNoProto:
1429 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +00001430 // GCC extension: alignof(function) = 32 bits
1431 Width = 0;
1432 Align = 32;
1433 break;
1434
Douglas Gregor72564e72009-02-26 23:50:07 +00001435 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +00001436 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +00001437 Width = 0;
1438 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1439 break;
1440
Steve Narofffb22d962007-08-30 01:06:46 +00001441 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001442 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001443
Chris Lattner98be4942008-03-05 18:54:05 +00001444 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001445 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001446 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1447 "Overflow in array type bit size evaluation");
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001448 Width = EltInfo.first*Size;
Chris Lattner030d8842007-07-19 22:06:24 +00001449 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +00001450 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +00001451 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +00001452 }
Nate Begeman213541a2008-04-18 23:10:10 +00001453 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +00001454 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001455 const VectorType *VT = cast<VectorType>(T);
1456 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1457 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +00001458 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001459 // If the alignment is not a power of 2, round up to the next power of 2.
1460 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +00001461 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001462 Align = llvm::NextPowerOf2(Align);
1463 Width = llvm::RoundUpToAlignment(Width, Align);
1464 }
Chad Rosierf9e9af72012-07-13 23:57:43 +00001465 // Adjust the alignment based on the target max.
1466 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1467 if (TargetVectorAlign && TargetVectorAlign < Align)
1468 Align = TargetVectorAlign;
Chris Lattner030d8842007-07-19 22:06:24 +00001469 break;
1470 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001471
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001472 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +00001473 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001474 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001475 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +00001476 // GCC extension: alignof(void) = 8 bits.
1477 Width = 0;
1478 Align = 8;
1479 break;
1480
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001481 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001482 Width = Target->getBoolWidth();
1483 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001484 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001485 case BuiltinType::Char_S:
1486 case BuiltinType::Char_U:
1487 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001488 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001489 Width = Target->getCharWidth();
1490 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001491 break;
Chris Lattner3f59c972010-12-25 23:25:43 +00001492 case BuiltinType::WChar_S:
1493 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001494 Width = Target->getWCharWidth();
1495 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001496 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001497 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001498 Width = Target->getChar16Width();
1499 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001500 break;
1501 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001502 Width = Target->getChar32Width();
1503 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001504 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001505 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001506 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001507 Width = Target->getShortWidth();
1508 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001509 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001510 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001511 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001512 Width = Target->getIntWidth();
1513 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001514 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001515 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001516 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001517 Width = Target->getLongWidth();
1518 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001519 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001520 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001521 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001522 Width = Target->getLongLongWidth();
1523 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001524 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +00001525 case BuiltinType::Int128:
1526 case BuiltinType::UInt128:
1527 Width = 128;
1528 Align = 128; // int128_t is 128-bit aligned on all targets.
1529 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001530 case BuiltinType::Half:
1531 Width = Target->getHalfWidth();
1532 Align = Target->getHalfAlign();
1533 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001534 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001535 Width = Target->getFloatWidth();
1536 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001537 break;
1538 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001539 Width = Target->getDoubleWidth();
1540 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001541 break;
1542 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001543 Width = Target->getLongDoubleWidth();
1544 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001545 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001546 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001547 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1548 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +00001549 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001550 case BuiltinType::ObjCId:
1551 case BuiltinType::ObjCClass:
1552 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001553 Width = Target->getPointerWidth(0);
1554 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001555 break;
Guy Benyei21f18c42013-02-07 10:55:47 +00001556 case BuiltinType::OCLSampler:
1557 // Samplers are modeled as integers.
1558 Width = Target->getIntWidth();
1559 Align = Target->getIntAlign();
1560 break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00001561 case BuiltinType::OCLEvent:
Guy Benyeib13621d2012-12-18 14:38:23 +00001562 case BuiltinType::OCLImage1d:
1563 case BuiltinType::OCLImage1dArray:
1564 case BuiltinType::OCLImage1dBuffer:
1565 case BuiltinType::OCLImage2d:
1566 case BuiltinType::OCLImage2dArray:
1567 case BuiltinType::OCLImage3d:
1568 // Currently these types are pointers to opaque types.
1569 Width = Target->getPointerWidth(0);
1570 Align = Target->getPointerAlign(0);
1571 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001572 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +00001573 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001574 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001575 Width = Target->getPointerWidth(0);
1576 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001577 break;
Steve Naroff485eeff2008-09-24 15:05:44 +00001578 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001579 unsigned AS = getTargetAddressSpace(
1580 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001581 Width = Target->getPointerWidth(AS);
1582 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +00001583 break;
1584 }
Sebastian Redl5d484e82009-11-23 17:18:46 +00001585 case Type::LValueReference:
1586 case Type::RValueReference: {
1587 // alignof and sizeof should never enter this code path here, so we go
1588 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001589 unsigned AS = getTargetAddressSpace(
1590 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001591 Width = Target->getPointerWidth(AS);
1592 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +00001593 break;
1594 }
Chris Lattnerf72a4432008-03-08 08:34:58 +00001595 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001596 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001597 Width = Target->getPointerWidth(AS);
1598 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +00001599 break;
1600 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00001601 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +00001602 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Reid Kleckner84e9ab42013-03-28 20:02:56 +00001603 llvm::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001604 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001605 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001606 case Type::Complex: {
1607 // Complex types have the same alignment as their elements, but twice the
1608 // size.
Mike Stump1eb44332009-09-09 15:08:12 +00001609 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +00001610 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001611 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +00001612 Align = EltInfo.second;
1613 break;
1614 }
John McCallc12c5bb2010-05-15 11:32:37 +00001615 case Type::ObjCObject:
1616 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +00001617 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001618 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +00001619 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001620 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001621 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +00001622 break;
1623 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001624 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001625 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001626 const TagType *TT = cast<TagType>(T);
1627
1628 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001629 Width = 8;
1630 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001631 break;
1632 }
Mike Stump1eb44332009-09-09 15:08:12 +00001633
Daniel Dunbar1d751182008-11-08 05:48:37 +00001634 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001635 return getTypeInfo(ET->getDecl()->getIntegerType());
1636
Daniel Dunbar1d751182008-11-08 05:48:37 +00001637 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001638 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001639 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001640 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001641 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001642 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001643
Chris Lattner9fcfe922009-10-22 05:17:15 +00001644 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001645 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1646 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001647
Richard Smith34b41d92011-02-20 03:19:35 +00001648 case Type::Auto: {
1649 const AutoType *A = cast<AutoType>(T);
Richard Smithdc7a4f52013-04-30 13:56:41 +00001650 assert(!A->getDeducedType().isNull() &&
1651 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001652 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001653 }
1654
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001655 case Type::Paren:
1656 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1657
Douglas Gregor18857642009-04-30 17:32:17 +00001658 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001659 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001660 std::pair<uint64_t, unsigned> Info
1661 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001662 // If the typedef has an aligned attribute on it, it overrides any computed
1663 // alignment we have. This violates the GCC documentation (which says that
1664 // attribute(aligned) can only round up) but matches its implementation.
1665 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1666 Align = AttrAlign;
1667 else
1668 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001669 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001670 break;
Chris Lattner71763312008-04-06 22:05:18 +00001671 }
Douglas Gregor18857642009-04-30 17:32:17 +00001672
1673 case Type::TypeOfExpr:
1674 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1675 .getTypePtr());
1676
1677 case Type::TypeOf:
1678 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1679
Anders Carlsson395b4752009-06-24 19:06:50 +00001680 case Type::Decltype:
1681 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1682 .getTypePtr());
1683
Sean Huntca63c202011-05-24 22:41:36 +00001684 case Type::UnaryTransform:
1685 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1686
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001687 case Type::Elaborated:
1688 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001689
John McCall9d156a72011-01-06 01:58:22 +00001690 case Type::Attributed:
1691 return getTypeInfo(
1692 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1693
Richard Smith3e4c6c42011-05-05 21:57:07 +00001694 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00001695 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +00001696 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +00001697 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1698 // A type alias template specialization may refer to a typedef with the
1699 // aligned attribute on it.
1700 if (TST->isTypeAlias())
1701 return getTypeInfo(TST->getAliasedType().getTypePtr());
1702 else
1703 return getTypeInfo(getCanonicalType(T));
1704 }
1705
Eli Friedmanb001de72011-10-06 23:00:33 +00001706 case Type::Atomic: {
John McCall9eda3ab2013-03-07 21:37:17 +00001707 // Start with the base type information.
Eli Friedman2be46072011-10-14 20:59:01 +00001708 std::pair<uint64_t, unsigned> Info
1709 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1710 Width = Info.first;
1711 Align = Info.second;
John McCall9eda3ab2013-03-07 21:37:17 +00001712
1713 // If the size of the type doesn't exceed the platform's max
1714 // atomic promotion width, make the size and alignment more
1715 // favorable to atomic operations:
1716 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1717 // Round the size up to a power of 2.
1718 if (!llvm::isPowerOf2_64(Width))
1719 Width = llvm::NextPowerOf2(Width);
1720
1721 // Set the alignment equal to the size.
Eli Friedman2be46072011-10-14 20:59:01 +00001722 Align = static_cast<unsigned>(Width);
1723 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001724 }
1725
Douglas Gregor18857642009-04-30 17:32:17 +00001726 }
Mike Stump1eb44332009-09-09 15:08:12 +00001727
Eli Friedman2be46072011-10-14 20:59:01 +00001728 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001729 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001730}
1731
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001732/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1733CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1734 return CharUnits::fromQuantity(BitSize / getCharWidth());
1735}
1736
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001737/// toBits - Convert a size in characters to a size in characters.
1738int64_t ASTContext::toBits(CharUnits CharSize) const {
1739 return CharSize.getQuantity() * getCharWidth();
1740}
1741
Ken Dyckbdc601b2009-12-22 14:23:30 +00001742/// getTypeSizeInChars - Return the size of the specified type, in characters.
1743/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001744CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001745 return getTypeInfoInChars(T).first;
Ken Dyckbdc601b2009-12-22 14:23:30 +00001746}
Jay Foad4ba2a172011-01-12 09:06:06 +00001747CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001748 return getTypeInfoInChars(T).first;
Ken Dyckbdc601b2009-12-22 14:23:30 +00001749}
1750
Ken Dyck16e20cc2010-01-26 17:25:18 +00001751/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001752/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001753CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001754 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001755}
Jay Foad4ba2a172011-01-12 09:06:06 +00001756CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001757 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001758}
1759
Chris Lattner34ebde42009-01-27 18:08:34 +00001760/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1761/// type for the current target in bits. This can be different than the ABI
1762/// alignment in cases where it is beneficial for performance to overalign
1763/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001764unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001765 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001766
1767 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001768 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001769 T = CT->getElementType().getTypePtr();
1770 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosiercde7a1d2012-03-21 20:20:47 +00001771 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1772 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman1eed6022009-05-25 21:27:19 +00001773 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1774
Chris Lattner34ebde42009-01-27 18:08:34 +00001775 return ABIAlign;
1776}
1777
Ulrich Weigand6b203512013-05-06 16:23:57 +00001778/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1779/// to a global variable of the specified type.
1780unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1781 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1782}
1783
1784/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1785/// should be given to a global variable of the specified type.
1786CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1787 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1788}
1789
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001790/// DeepCollectObjCIvars -
1791/// This routine first collects all declared, but not synthesized, ivars in
1792/// super class and then collects all ivars, including those synthesized for
1793/// current class. This routine is used for implementation of current class
1794/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001795///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001796void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1797 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001798 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001799 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1800 DeepCollectObjCIvars(SuperClass, false, Ivars);
1801 if (!leafClass) {
1802 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1803 E = OI->ivar_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001804 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001805 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001806 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001807 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001808 Iv= Iv->getNextIvar())
1809 Ivars.push_back(Iv);
1810 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001811}
1812
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001813/// CollectInheritedProtocols - Collect all protocols in current class and
1814/// those inherited by it.
1815void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001816 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001817 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001818 // We can use protocol_iterator here instead of
1819 // all_referenced_protocol_iterator since we are walking all categories.
1820 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1821 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001822 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001823 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001824 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001825 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001826 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001827 CollectInheritedProtocols(*P, Protocols);
1828 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001829 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001830
1831 // Categories of this Interface.
Douglas Gregord3297242013-01-16 23:00:23 +00001832 for (ObjCInterfaceDecl::visible_categories_iterator
1833 Cat = OI->visible_categories_begin(),
1834 CatEnd = OI->visible_categories_end();
1835 Cat != CatEnd; ++Cat) {
1836 CollectInheritedProtocols(*Cat, Protocols);
1837 }
1838
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001839 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1840 while (SD) {
1841 CollectInheritedProtocols(SD, Protocols);
1842 SD = SD->getSuperClass();
1843 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001844 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001845 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001846 PE = OC->protocol_end(); P != PE; ++P) {
1847 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001848 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001849 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1850 PE = Proto->protocol_end(); P != PE; ++P)
1851 CollectInheritedProtocols(*P, Protocols);
1852 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001853 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001854 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1855 PE = OP->protocol_end(); P != PE; ++P) {
1856 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001857 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001858 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1859 PE = Proto->protocol_end(); P != PE; ++P)
1860 CollectInheritedProtocols(*P, Protocols);
1861 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001862 }
1863}
1864
Jay Foad4ba2a172011-01-12 09:06:06 +00001865unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001866 unsigned count = 0;
1867 // Count ivars declared in class extension.
Douglas Gregord3297242013-01-16 23:00:23 +00001868 for (ObjCInterfaceDecl::known_extensions_iterator
1869 Ext = OI->known_extensions_begin(),
1870 ExtEnd = OI->known_extensions_end();
1871 Ext != ExtEnd; ++Ext) {
1872 count += Ext->ivar_size();
1873 }
1874
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001875 // Count ivar defined in this class's implementation. This
1876 // includes synthesized ivars.
1877 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001878 count += ImplDecl->ivar_size();
1879
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001880 return count;
1881}
1882
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +00001883bool ASTContext::isSentinelNullExpr(const Expr *E) {
1884 if (!E)
1885 return false;
1886
1887 // nullptr_t is always treated as null.
1888 if (E->getType()->isNullPtrType()) return true;
1889
1890 if (E->getType()->isAnyPointerType() &&
1891 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1892 Expr::NPC_ValueDependentIsNull))
1893 return true;
1894
1895 // Unfortunately, __null has type 'int'.
1896 if (isa<GNUNullExpr>(E)) return true;
1897
1898 return false;
1899}
1900
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001901/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1902ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1903 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1904 I = ObjCImpls.find(D);
1905 if (I != ObjCImpls.end())
1906 return cast<ObjCImplementationDecl>(I->second);
1907 return 0;
1908}
1909/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1910ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1911 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1912 I = ObjCImpls.find(D);
1913 if (I != ObjCImpls.end())
1914 return cast<ObjCCategoryImplDecl>(I->second);
1915 return 0;
1916}
1917
1918/// \brief Set the implementation of ObjCInterfaceDecl.
1919void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1920 ObjCImplementationDecl *ImplD) {
1921 assert(IFaceD && ImplD && "Passed null params");
1922 ObjCImpls[IFaceD] = ImplD;
1923}
1924/// \brief Set the implementation of ObjCCategoryDecl.
1925void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1926 ObjCCategoryImplDecl *ImplD) {
1927 assert(CatD && ImplD && "Passed null params");
1928 ObjCImpls[CatD] = ImplD;
1929}
1930
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001931const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1932 const NamedDecl *ND) const {
1933 if (const ObjCInterfaceDecl *ID =
1934 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001935 return ID;
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001936 if (const ObjCCategoryDecl *CD =
1937 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001938 return CD->getClassInterface();
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001939 if (const ObjCImplDecl *IMD =
1940 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001941 return IMD->getClassInterface();
1942
1943 return 0;
1944}
1945
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001946/// \brief Get the copy initialization expression of VarDecl,or NULL if
1947/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001948Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001949 assert(VD && "Passed null params");
1950 assert(VD->hasAttr<BlocksAttr>() &&
1951 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001952 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001953 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001954 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1955}
1956
1957/// \brief Set the copy inialization expression of a block var decl.
1958void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1959 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001960 assert(VD->hasAttr<BlocksAttr>() &&
1961 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001962 BlockVarCopyInits[VD] = Init;
1963}
1964
John McCalla93c9342009-12-07 02:54:59 +00001965TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001966 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001967 if (!DataSize)
1968 DataSize = TypeLoc::getFullDataSizeForType(T);
1969 else
1970 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001971 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001972
John McCalla93c9342009-12-07 02:54:59 +00001973 TypeSourceInfo *TInfo =
1974 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1975 new (TInfo) TypeSourceInfo(T);
1976 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001977}
1978
John McCalla93c9342009-12-07 02:54:59 +00001979TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001980 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001981 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001982 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001983 return DI;
1984}
1985
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001986const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001987ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001988 return getObjCLayout(D, 0);
1989}
1990
1991const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001992ASTContext::getASTObjCImplementationLayout(
1993 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001994 return getObjCLayout(D->getClassInterface(), D);
1995}
1996
Chris Lattnera7674d82007-07-13 22:13:22 +00001997//===----------------------------------------------------------------------===//
1998// Type creation/memoization methods
1999//===----------------------------------------------------------------------===//
2000
Jay Foad4ba2a172011-01-12 09:06:06 +00002001QualType
John McCall3b657512011-01-19 10:06:00 +00002002ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2003 unsigned fastQuals = quals.getFastQualifiers();
2004 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00002005
2006 // Check if we've already instantiated this type.
2007 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002008 ExtQuals::Profile(ID, baseType, quals);
2009 void *insertPos = 0;
2010 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2011 assert(eq->getQualifiers() == quals);
2012 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00002013 }
2014
John McCall3b657512011-01-19 10:06:00 +00002015 // If the base type is not canonical, make the appropriate canonical type.
2016 QualType canon;
2017 if (!baseType->isCanonicalUnqualified()) {
2018 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall200fa532012-02-08 00:46:36 +00002019 canonSplit.Quals.addConsistentQualifiers(quals);
2020 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00002021
2022 // Re-find the insert position.
2023 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2024 }
2025
2026 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2027 ExtQualNodes.InsertNode(eq, insertPos);
2028 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00002029}
2030
Jay Foad4ba2a172011-01-12 09:06:06 +00002031QualType
2032ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002033 QualType CanT = getCanonicalType(T);
2034 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00002035 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00002036
John McCall0953e762009-09-24 19:53:00 +00002037 // If we are composing extended qualifiers together, merge together
2038 // into one ExtQuals node.
2039 QualifierCollector Quals;
2040 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002041
John McCall0953e762009-09-24 19:53:00 +00002042 // If this type already has an address space specified, it cannot get
2043 // another one.
2044 assert(!Quals.hasAddressSpace() &&
2045 "Type cannot be in multiple addr spaces!");
2046 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002047
John McCall0953e762009-09-24 19:53:00 +00002048 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00002049}
2050
Chris Lattnerb7d25532009-02-18 22:53:11 +00002051QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00002052 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002053 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00002054 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002055 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00002056
John McCall7f040a92010-12-24 02:08:15 +00002057 if (const PointerType *ptr = T->getAs<PointerType>()) {
2058 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00002059 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00002060 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2061 return getPointerType(ResultType);
2062 }
2063 }
Mike Stump1eb44332009-09-09 15:08:12 +00002064
John McCall0953e762009-09-24 19:53:00 +00002065 // If we are composing extended qualifiers together, merge together
2066 // into one ExtQuals node.
2067 QualifierCollector Quals;
2068 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002069
John McCall0953e762009-09-24 19:53:00 +00002070 // If this type already has an ObjCGC specified, it cannot get
2071 // another one.
2072 assert(!Quals.hasObjCGCAttr() &&
2073 "Type cannot have multiple ObjCGCs!");
2074 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00002075
John McCall0953e762009-09-24 19:53:00 +00002076 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002077}
Chris Lattnera7674d82007-07-13 22:13:22 +00002078
John McCalle6a365d2010-12-19 02:44:49 +00002079const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2080 FunctionType::ExtInfo Info) {
2081 if (T->getExtInfo() == Info)
2082 return T;
2083
2084 QualType Result;
2085 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2086 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
2087 } else {
2088 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2089 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2090 EPI.ExtInfo = Info;
Reid Kleckner0567a792013-06-10 20:51:09 +00002091 Result = getFunctionType(FPT->getResultType(), FPT->getArgTypes(), EPI);
John McCalle6a365d2010-12-19 02:44:49 +00002092 }
2093
2094 return cast<FunctionType>(Result.getTypePtr());
2095}
2096
Richard Smith60e141e2013-05-04 07:00:32 +00002097void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2098 QualType ResultType) {
Richard Smith9dadfab2013-05-11 05:45:24 +00002099 FD = FD->getMostRecentDecl();
2100 while (true) {
Richard Smith60e141e2013-05-04 07:00:32 +00002101 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2102 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2103 FD->setType(getFunctionType(ResultType, FPT->getArgTypes(), EPI));
Richard Smith9dadfab2013-05-11 05:45:24 +00002104 if (FunctionDecl *Next = FD->getPreviousDecl())
2105 FD = Next;
2106 else
2107 break;
Richard Smith60e141e2013-05-04 07:00:32 +00002108 }
Richard Smith9dadfab2013-05-11 05:45:24 +00002109 if (ASTMutationListener *L = getASTMutationListener())
2110 L->DeducedReturnType(FD, ResultType);
Richard Smith60e141e2013-05-04 07:00:32 +00002111}
2112
Reid Spencer5f016e22007-07-11 17:01:13 +00002113/// getComplexType - Return the uniqued reference to the type for a complex
2114/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002115QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002116 // Unique pointers, to guarantee there is only one pointer of a particular
2117 // structure.
2118 llvm::FoldingSetNodeID ID;
2119 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002120
Reid Spencer5f016e22007-07-11 17:01:13 +00002121 void *InsertPos = 0;
2122 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2123 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002124
Reid Spencer5f016e22007-07-11 17:01:13 +00002125 // If the pointee type isn't canonical, this won't be a canonical type either,
2126 // so fill in the canonical type field.
2127 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002128 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002129 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002130
Reid Spencer5f016e22007-07-11 17:01:13 +00002131 // Get the new insert position for the node we care about.
2132 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002133 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002134 }
John McCall6b304a02009-09-24 23:30:46 +00002135 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002136 Types.push_back(New);
2137 ComplexTypes.InsertNode(New, InsertPos);
2138 return QualType(New, 0);
2139}
2140
Reid Spencer5f016e22007-07-11 17:01:13 +00002141/// getPointerType - Return the uniqued reference to the type for a pointer to
2142/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002143QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002144 // Unique pointers, to guarantee there is only one pointer of a particular
2145 // structure.
2146 llvm::FoldingSetNodeID ID;
2147 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002148
Reid Spencer5f016e22007-07-11 17:01:13 +00002149 void *InsertPos = 0;
2150 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2151 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002152
Reid Spencer5f016e22007-07-11 17:01:13 +00002153 // If the pointee type isn't canonical, this won't be a canonical type either,
2154 // so fill in the canonical type field.
2155 QualType Canonical;
Bob Wilsonc90cc932013-03-15 17:12:43 +00002156 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002157 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002158
Bob Wilsonc90cc932013-03-15 17:12:43 +00002159 // Get the new insert position for the node we care about.
2160 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2161 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2162 }
John McCall6b304a02009-09-24 23:30:46 +00002163 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002164 Types.push_back(New);
2165 PointerTypes.InsertNode(New, InsertPos);
2166 return QualType(New, 0);
2167}
2168
Mike Stump1eb44332009-09-09 15:08:12 +00002169/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00002170/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00002171QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00002172 assert(T->isFunctionType() && "block of function types only");
2173 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00002174 // structure.
2175 llvm::FoldingSetNodeID ID;
2176 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002177
Steve Naroff5618bd42008-08-27 16:04:49 +00002178 void *InsertPos = 0;
2179 if (BlockPointerType *PT =
2180 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2181 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002182
2183 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00002184 // type either so fill in the canonical type field.
2185 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002186 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00002187 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002188
Steve Naroff5618bd42008-08-27 16:04:49 +00002189 // Get the new insert position for the node we care about.
2190 BlockPointerType *NewIP =
2191 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002192 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00002193 }
John McCall6b304a02009-09-24 23:30:46 +00002194 BlockPointerType *New
2195 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00002196 Types.push_back(New);
2197 BlockPointerTypes.InsertNode(New, InsertPos);
2198 return QualType(New, 0);
2199}
2200
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002201/// getLValueReferenceType - Return the uniqued reference to the type for an
2202/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002203QualType
2204ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00002205 assert(getCanonicalType(T) != OverloadTy &&
2206 "Unresolved overloaded function type");
2207
Reid Spencer5f016e22007-07-11 17:01:13 +00002208 // Unique pointers, to guarantee there is only one pointer of a particular
2209 // structure.
2210 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002211 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002212
2213 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002214 if (LValueReferenceType *RT =
2215 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002216 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002217
John McCall54e14c42009-10-22 22:37:11 +00002218 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2219
Reid Spencer5f016e22007-07-11 17:01:13 +00002220 // If the referencee type isn't canonical, this won't be a canonical type
2221 // either, so fill in the canonical type field.
2222 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002223 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2224 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2225 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002226
Reid Spencer5f016e22007-07-11 17:01:13 +00002227 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002228 LValueReferenceType *NewIP =
2229 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002230 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002231 }
2232
John McCall6b304a02009-09-24 23:30:46 +00002233 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00002234 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2235 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002236 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002237 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00002238
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002239 return QualType(New, 0);
2240}
2241
2242/// getRValueReferenceType - Return the uniqued reference to the type for an
2243/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002244QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002245 // Unique pointers, to guarantee there is only one pointer of a particular
2246 // structure.
2247 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002248 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002249
2250 void *InsertPos = 0;
2251 if (RValueReferenceType *RT =
2252 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2253 return QualType(RT, 0);
2254
John McCall54e14c42009-10-22 22:37:11 +00002255 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2256
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002257 // If the referencee type isn't canonical, this won't be a canonical type
2258 // either, so fill in the canonical type field.
2259 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002260 if (InnerRef || !T.isCanonical()) {
2261 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2262 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002263
2264 // Get the new insert position for the node we care about.
2265 RValueReferenceType *NewIP =
2266 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002267 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002268 }
2269
John McCall6b304a02009-09-24 23:30:46 +00002270 RValueReferenceType *New
2271 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002272 Types.push_back(New);
2273 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002274 return QualType(New, 0);
2275}
2276
Sebastian Redlf30208a2009-01-24 21:16:55 +00002277/// getMemberPointerType - Return the uniqued reference to the type for a
2278/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00002279QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002280 // Unique pointers, to guarantee there is only one pointer of a particular
2281 // structure.
2282 llvm::FoldingSetNodeID ID;
2283 MemberPointerType::Profile(ID, T, Cls);
2284
2285 void *InsertPos = 0;
2286 if (MemberPointerType *PT =
2287 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2288 return QualType(PT, 0);
2289
2290 // If the pointee or class type isn't canonical, this won't be a canonical
2291 // type either, so fill in the canonical type field.
2292 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00002293 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002294 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2295
2296 // Get the new insert position for the node we care about.
2297 MemberPointerType *NewIP =
2298 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002299 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00002300 }
John McCall6b304a02009-09-24 23:30:46 +00002301 MemberPointerType *New
2302 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002303 Types.push_back(New);
2304 MemberPointerTypes.InsertNode(New, InsertPos);
2305 return QualType(New, 0);
2306}
2307
Mike Stump1eb44332009-09-09 15:08:12 +00002308/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00002309/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002310QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00002311 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00002312 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002313 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00002314 assert((EltTy->isDependentType() ||
2315 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00002316 "Constant array of VLAs is illegal!");
2317
Chris Lattner38aeec72009-05-13 04:12:56 +00002318 // Convert the array size into a canonical width matching the pointer size for
2319 // the target.
2320 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002321 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002322 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00002323
Reid Spencer5f016e22007-07-11 17:01:13 +00002324 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002325 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00002326
Reid Spencer5f016e22007-07-11 17:01:13 +00002327 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002328 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002329 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002330 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002331
John McCall3b657512011-01-19 10:06:00 +00002332 // If the element type isn't canonical or has qualifiers, this won't
2333 // be a canonical type either, so fill in the canonical type field.
2334 QualType Canon;
2335 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2336 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002337 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002338 ASM, IndexTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002339 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00002340
Reid Spencer5f016e22007-07-11 17:01:13 +00002341 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00002342 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002343 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002344 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002345 }
Mike Stump1eb44332009-09-09 15:08:12 +00002346
John McCall6b304a02009-09-24 23:30:46 +00002347 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002348 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002349 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002350 Types.push_back(New);
2351 return QualType(New, 0);
2352}
2353
John McCallce889032011-01-18 08:40:38 +00002354/// getVariableArrayDecayedType - Turns the given type, which may be
2355/// variably-modified, into the corresponding type with all the known
2356/// sizes replaced with [*].
2357QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2358 // Vastly most common case.
2359 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002360
John McCallce889032011-01-18 08:40:38 +00002361 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002362
John McCallce889032011-01-18 08:40:38 +00002363 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00002364 const Type *ty = split.Ty;
John McCallce889032011-01-18 08:40:38 +00002365 switch (ty->getTypeClass()) {
2366#define TYPE(Class, Base)
2367#define ABSTRACT_TYPE(Class, Base)
2368#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2369#include "clang/AST/TypeNodes.def"
2370 llvm_unreachable("didn't desugar past all non-canonical types?");
2371
2372 // These types should never be variably-modified.
2373 case Type::Builtin:
2374 case Type::Complex:
2375 case Type::Vector:
2376 case Type::ExtVector:
2377 case Type::DependentSizedExtVector:
2378 case Type::ObjCObject:
2379 case Type::ObjCInterface:
2380 case Type::ObjCObjectPointer:
2381 case Type::Record:
2382 case Type::Enum:
2383 case Type::UnresolvedUsing:
2384 case Type::TypeOfExpr:
2385 case Type::TypeOf:
2386 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00002387 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00002388 case Type::DependentName:
2389 case Type::InjectedClassName:
2390 case Type::TemplateSpecialization:
2391 case Type::DependentTemplateSpecialization:
2392 case Type::TemplateTypeParm:
2393 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00002394 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00002395 case Type::PackExpansion:
2396 llvm_unreachable("type should never be variably-modified");
2397
2398 // These types can be variably-modified but should never need to
2399 // further decay.
2400 case Type::FunctionNoProto:
2401 case Type::FunctionProto:
2402 case Type::BlockPointer:
2403 case Type::MemberPointer:
2404 return type;
2405
2406 // These types can be variably-modified. All these modifications
2407 // preserve structure except as noted by comments.
2408 // TODO: if we ever care about optimizing VLAs, there are no-op
2409 // optimizations available here.
2410 case Type::Pointer:
2411 result = getPointerType(getVariableArrayDecayedType(
2412 cast<PointerType>(ty)->getPointeeType()));
2413 break;
2414
2415 case Type::LValueReference: {
2416 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2417 result = getLValueReferenceType(
2418 getVariableArrayDecayedType(lv->getPointeeType()),
2419 lv->isSpelledAsLValue());
2420 break;
2421 }
2422
2423 case Type::RValueReference: {
2424 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2425 result = getRValueReferenceType(
2426 getVariableArrayDecayedType(lv->getPointeeType()));
2427 break;
2428 }
2429
Eli Friedmanb001de72011-10-06 23:00:33 +00002430 case Type::Atomic: {
2431 const AtomicType *at = cast<AtomicType>(ty);
2432 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2433 break;
2434 }
2435
John McCallce889032011-01-18 08:40:38 +00002436 case Type::ConstantArray: {
2437 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2438 result = getConstantArrayType(
2439 getVariableArrayDecayedType(cat->getElementType()),
2440 cat->getSize(),
2441 cat->getSizeModifier(),
2442 cat->getIndexTypeCVRQualifiers());
2443 break;
2444 }
2445
2446 case Type::DependentSizedArray: {
2447 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2448 result = getDependentSizedArrayType(
2449 getVariableArrayDecayedType(dat->getElementType()),
2450 dat->getSizeExpr(),
2451 dat->getSizeModifier(),
2452 dat->getIndexTypeCVRQualifiers(),
2453 dat->getBracketsRange());
2454 break;
2455 }
2456
2457 // Turn incomplete types into [*] types.
2458 case Type::IncompleteArray: {
2459 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2460 result = getVariableArrayType(
2461 getVariableArrayDecayedType(iat->getElementType()),
2462 /*size*/ 0,
2463 ArrayType::Normal,
2464 iat->getIndexTypeCVRQualifiers(),
2465 SourceRange());
2466 break;
2467 }
2468
2469 // Turn VLA types into [*] types.
2470 case Type::VariableArray: {
2471 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2472 result = getVariableArrayType(
2473 getVariableArrayDecayedType(vat->getElementType()),
2474 /*size*/ 0,
2475 ArrayType::Star,
2476 vat->getIndexTypeCVRQualifiers(),
2477 vat->getBracketsRange());
2478 break;
2479 }
2480 }
2481
2482 // Apply the top-level qualifiers from the original.
John McCall200fa532012-02-08 00:46:36 +00002483 return getQualifiedType(result, split.Quals);
John McCallce889032011-01-18 08:40:38 +00002484}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002485
Steve Naroffbdbf7b02007-08-30 18:14:25 +00002486/// getVariableArrayType - Returns a non-unique reference to the type for a
2487/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002488QualType ASTContext::getVariableArrayType(QualType EltTy,
2489 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00002490 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002491 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00002492 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002493 // Since we don't unique expressions, it isn't possible to unique VLA's
2494 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00002495 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00002496
John McCall3b657512011-01-19 10:06:00 +00002497 // Be sure to pull qualifiers off the element type.
2498 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2499 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002500 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002501 IndexTypeQuals, Brackets);
John McCall200fa532012-02-08 00:46:36 +00002502 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor715e9c82010-05-23 16:10:32 +00002503 }
2504
John McCall6b304a02009-09-24 23:30:46 +00002505 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002506 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002507
2508 VariableArrayTypes.push_back(New);
2509 Types.push_back(New);
2510 return QualType(New, 0);
2511}
2512
Douglas Gregor898574e2008-12-05 23:32:09 +00002513/// getDependentSizedArrayType - Returns a non-unique reference to
2514/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00002515/// type.
John McCall3b657512011-01-19 10:06:00 +00002516QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2517 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00002518 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002519 unsigned elementTypeQuals,
2520 SourceRange brackets) const {
2521 assert((!numElements || numElements->isTypeDependent() ||
2522 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00002523 "Size must be type- or value-dependent!");
2524
John McCall3b657512011-01-19 10:06:00 +00002525 // Dependently-sized array types that do not have a specified number
2526 // of elements will have their sizes deduced from a dependent
2527 // initializer. We do no canonicalization here at all, which is okay
2528 // because they can't be used in most locations.
2529 if (!numElements) {
2530 DependentSizedArrayType *newType
2531 = new (*this, TypeAlignment)
2532 DependentSizedArrayType(*this, elementType, QualType(),
2533 numElements, ASM, elementTypeQuals,
2534 brackets);
2535 Types.push_back(newType);
2536 return QualType(newType, 0);
2537 }
2538
2539 // Otherwise, we actually build a new type every time, but we
2540 // also build a canonical type.
2541
2542 SplitQualType canonElementType = getCanonicalType(elementType).split();
2543
2544 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00002545 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002546 DependentSizedArrayType::Profile(ID, *this,
John McCall200fa532012-02-08 00:46:36 +00002547 QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002548 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002549
John McCall3b657512011-01-19 10:06:00 +00002550 // Look for an existing type with these properties.
2551 DependentSizedArrayType *canonTy =
2552 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002553
John McCall3b657512011-01-19 10:06:00 +00002554 // If we don't have one, build one.
2555 if (!canonTy) {
2556 canonTy = new (*this, TypeAlignment)
John McCall200fa532012-02-08 00:46:36 +00002557 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002558 QualType(), numElements, ASM, elementTypeQuals,
2559 brackets);
2560 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2561 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002562 }
2563
John McCall3b657512011-01-19 10:06:00 +00002564 // Apply qualifiers from the element type to the array.
2565 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall200fa532012-02-08 00:46:36 +00002566 canonElementType.Quals);
Mike Stump1eb44332009-09-09 15:08:12 +00002567
John McCall3b657512011-01-19 10:06:00 +00002568 // If we didn't need extra canonicalization for the element type,
2569 // then just use that as our result.
John McCall200fa532012-02-08 00:46:36 +00002570 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall3b657512011-01-19 10:06:00 +00002571 return canon;
2572
2573 // Otherwise, we need to build a type which follows the spelling
2574 // of the element type.
2575 DependentSizedArrayType *sugaredType
2576 = new (*this, TypeAlignment)
2577 DependentSizedArrayType(*this, elementType, canon, numElements,
2578 ASM, elementTypeQuals, brackets);
2579 Types.push_back(sugaredType);
2580 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00002581}
2582
John McCall3b657512011-01-19 10:06:00 +00002583QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00002584 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002585 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002586 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002587 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002588
John McCall3b657512011-01-19 10:06:00 +00002589 void *insertPos = 0;
2590 if (IncompleteArrayType *iat =
2591 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2592 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002593
2594 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00002595 // either, so fill in the canonical type field. We also have to pull
2596 // qualifiers off the element type.
2597 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00002598
John McCall3b657512011-01-19 10:06:00 +00002599 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2600 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall200fa532012-02-08 00:46:36 +00002601 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002602 ASM, elementTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002603 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002604
2605 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00002606 IncompleteArrayType *existing =
2607 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2608 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00002609 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00002610
John McCall3b657512011-01-19 10:06:00 +00002611 IncompleteArrayType *newType = new (*this, TypeAlignment)
2612 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002613
John McCall3b657512011-01-19 10:06:00 +00002614 IncompleteArrayTypes.InsertNode(newType, insertPos);
2615 Types.push_back(newType);
2616 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00002617}
2618
Steve Naroff73322922007-07-18 18:00:27 +00002619/// getVectorType - Return the unique reference to a vector type of
2620/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00002621QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00002622 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00002623 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00002624
Reid Spencer5f016e22007-07-11 17:01:13 +00002625 // Check if we've already instantiated a vector of this type.
2626 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00002627 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00002628
Reid Spencer5f016e22007-07-11 17:01:13 +00002629 void *InsertPos = 0;
2630 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2631 return QualType(VTP, 0);
2632
2633 // If the element type isn't canonical, this won't be a canonical type either,
2634 // so fill in the canonical type field.
2635 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00002636 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00002637 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002638
Reid Spencer5f016e22007-07-11 17:01:13 +00002639 // Get the new insert position for the node we care about.
2640 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002641 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002642 }
John McCall6b304a02009-09-24 23:30:46 +00002643 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00002644 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002645 VectorTypes.InsertNode(New, InsertPos);
2646 Types.push_back(New);
2647 return QualType(New, 0);
2648}
2649
Nate Begeman213541a2008-04-18 23:10:10 +00002650/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00002651/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002652QualType
2653ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00002654 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00002655
Steve Naroff73322922007-07-18 18:00:27 +00002656 // Check if we've already instantiated a vector of this type.
2657 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00002658 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002659 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00002660 void *InsertPos = 0;
2661 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2662 return QualType(VTP, 0);
2663
2664 // If the element type isn't canonical, this won't be a canonical type either,
2665 // so fill in the canonical type field.
2666 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002667 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002668 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00002669
Steve Naroff73322922007-07-18 18:00:27 +00002670 // Get the new insert position for the node we care about.
2671 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002672 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00002673 }
John McCall6b304a02009-09-24 23:30:46 +00002674 ExtVectorType *New = new (*this, TypeAlignment)
2675 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00002676 VectorTypes.InsertNode(New, InsertPos);
2677 Types.push_back(New);
2678 return QualType(New, 0);
2679}
2680
Jay Foad4ba2a172011-01-12 09:06:06 +00002681QualType
2682ASTContext::getDependentSizedExtVectorType(QualType vecType,
2683 Expr *SizeExpr,
2684 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002685 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002686 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002687 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002688
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002689 void *InsertPos = 0;
2690 DependentSizedExtVectorType *Canon
2691 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2692 DependentSizedExtVectorType *New;
2693 if (Canon) {
2694 // We already have a canonical version of this array type; use it as
2695 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002696 New = new (*this, TypeAlignment)
2697 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2698 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002699 } else {
2700 QualType CanonVecTy = getCanonicalType(vecType);
2701 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002702 New = new (*this, TypeAlignment)
2703 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2704 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002705
2706 DependentSizedExtVectorType *CanonCheck
2707 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2708 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2709 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002710 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2711 } else {
2712 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2713 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002714 New = new (*this, TypeAlignment)
2715 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002716 }
2717 }
Mike Stump1eb44332009-09-09 15:08:12 +00002718
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002719 Types.push_back(New);
2720 return QualType(New, 0);
2721}
2722
Douglas Gregor72564e72009-02-26 23:50:07 +00002723/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002724///
Jay Foad4ba2a172011-01-12 09:06:06 +00002725QualType
2726ASTContext::getFunctionNoProtoType(QualType ResultTy,
2727 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00002728 const CallingConv DefaultCC = Info.getCC();
2729 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2730 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00002731 // Unique functions, to guarantee there is only one function of a particular
2732 // structure.
2733 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002734 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002735
Reid Spencer5f016e22007-07-11 17:01:13 +00002736 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002737 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002738 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002739 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002740
Reid Spencer5f016e22007-07-11 17:01:13 +00002741 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00002742 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00002743 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00002744 Canonical =
2745 getFunctionNoProtoType(getCanonicalType(ResultTy),
2746 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00002747
Reid Spencer5f016e22007-07-11 17:01:13 +00002748 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002749 FunctionNoProtoType *NewIP =
2750 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002751 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002752 }
Mike Stump1eb44332009-09-09 15:08:12 +00002753
Roman Divackycfe9af22011-03-01 17:40:53 +00002754 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002755 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002756 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002757 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002758 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002759 return QualType(New, 0);
2760}
2761
Douglas Gregor02dd7982013-01-17 23:36:45 +00002762/// \brief Determine whether \p T is canonical as the result type of a function.
2763static bool isCanonicalResultType(QualType T) {
2764 return T.isCanonical() &&
2765 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2766 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2767}
2768
Reid Spencer5f016e22007-07-11 17:01:13 +00002769/// getFunctionType - Return a normal function type with a typed argument
2770/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002771QualType
Jordan Rosebea522f2013-03-08 21:51:21 +00002772ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad4ba2a172011-01-12 09:06:06 +00002773 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rosebea522f2013-03-08 21:51:21 +00002774 size_t NumArgs = ArgArray.size();
2775
Reid Spencer5f016e22007-07-11 17:01:13 +00002776 // Unique functions, to guarantee there is only one function of a particular
2777 // structure.
2778 llvm::FoldingSetNodeID ID;
Jordan Rosebea522f2013-03-08 21:51:21 +00002779 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2780 *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002781
2782 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002783 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002784 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002785 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002786
2787 // Determine whether the type being created is already canonical or not.
Richard Smitheefb3d52012-02-10 09:58:53 +00002788 bool isCanonical =
Douglas Gregor02dd7982013-01-17 23:36:45 +00002789 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smitheefb3d52012-02-10 09:58:53 +00002790 !EPI.HasTrailingReturn;
Reid Spencer5f016e22007-07-11 17:01:13 +00002791 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002792 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002793 isCanonical = false;
2794
Roman Divackycfe9af22011-03-01 17:40:53 +00002795 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2796 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2797 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002798
Reid Spencer5f016e22007-07-11 17:01:13 +00002799 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002800 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002801 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002802 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002803 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002804 CanonicalArgs.reserve(NumArgs);
2805 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002806 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002807
John McCalle23cf432010-12-14 08:05:40 +00002808 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +00002809 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002810 CanonicalEPI.ExceptionSpecType = EST_None;
2811 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002812 CanonicalEPI.ExtInfo
2813 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2814
Douglas Gregor02dd7982013-01-17 23:36:45 +00002815 // Result types do not have ARC lifetime qualifiers.
2816 QualType CanResultTy = getCanonicalType(ResultTy);
2817 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2818 Qualifiers Qs = CanResultTy.getQualifiers();
2819 Qs.removeObjCLifetime();
2820 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2821 }
2822
Jordan Rosebea522f2013-03-08 21:51:21 +00002823 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002824
Reid Spencer5f016e22007-07-11 17:01:13 +00002825 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002826 FunctionProtoType *NewIP =
2827 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002828 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002829 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002830
John McCallf85e1932011-06-15 23:02:42 +00002831 // FunctionProtoType objects are allocated with extra bytes after
2832 // them for three variable size arrays at the end:
2833 // - parameter types
2834 // - exception types
2835 // - consumed-arguments flags
2836 // Instead of the exception types, there could be a noexcept
Richard Smithb9d0b762012-07-27 04:22:15 +00002837 // expression, or information used to resolve the exception
2838 // specification.
John McCalle23cf432010-12-14 08:05:40 +00002839 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002840 NumArgs * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002841 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00002842 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002843 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002844 Size += sizeof(Expr*);
Richard Smithe6975e92012-04-17 00:58:00 +00002845 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smith13bffc52012-04-19 00:08:28 +00002846 Size += 2 * sizeof(FunctionDecl*);
Richard Smithb9d0b762012-07-27 04:22:15 +00002847 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2848 Size += sizeof(FunctionDecl*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002849 }
John McCallf85e1932011-06-15 23:02:42 +00002850 if (EPI.ConsumedArguments)
2851 Size += NumArgs * sizeof(bool);
2852
John McCalle23cf432010-12-14 08:05:40 +00002853 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002854 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2855 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Jordan Rosebea522f2013-03-08 21:51:21 +00002856 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002857 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002858 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002859 return QualType(FTP, 0);
2860}
2861
John McCall3cb0ebd2010-03-10 03:28:59 +00002862#ifndef NDEBUG
2863static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2864 if (!isa<CXXRecordDecl>(D)) return false;
2865 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2866 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2867 return true;
2868 if (RD->getDescribedClassTemplate() &&
2869 !isa<ClassTemplateSpecializationDecl>(RD))
2870 return true;
2871 return false;
2872}
2873#endif
2874
2875/// getInjectedClassNameType - Return the unique reference to the
2876/// injected class name type for the specified templated declaration.
2877QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002878 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002879 assert(NeedsInjectedClassNameType(Decl));
2880 if (Decl->TypeForDecl) {
2881 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregoref96ee02012-01-14 16:38:05 +00002882 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002883 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2884 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2885 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2886 } else {
John McCallf4c73712011-01-19 06:33:43 +00002887 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002888 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002889 Decl->TypeForDecl = newType;
2890 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002891 }
2892 return QualType(Decl->TypeForDecl, 0);
2893}
2894
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002895/// getTypeDeclType - Return the unique reference to the type for the
2896/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002897QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002898 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002899 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002900
Richard Smith162e1c12011-04-15 14:24:37 +00002901 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002902 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002903
John McCallbecb8d52010-03-10 06:48:02 +00002904 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2905 "Template type parameter types are always available.");
2906
John McCall19c85762010-02-16 03:57:14 +00002907 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002908 assert(!Record->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002909 "struct/union has previous declaration");
2910 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002911 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002912 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002913 assert(!Enum->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002914 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002915 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002916 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002917 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002918 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2919 Decl->TypeForDecl = newType;
2920 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002921 } else
John McCallbecb8d52010-03-10 06:48:02 +00002922 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002923
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002924 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002925}
2926
Reid Spencer5f016e22007-07-11 17:01:13 +00002927/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002928/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002929QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002930ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2931 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002932 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002933
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002934 if (Canonical.isNull())
2935 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002936 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002937 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002938 Decl->TypeForDecl = newType;
2939 Types.push_back(newType);
2940 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002941}
2942
Jay Foad4ba2a172011-01-12 09:06:06 +00002943QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002944 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2945
Douglas Gregoref96ee02012-01-14 16:38:05 +00002946 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002947 if (PrevDecl->TypeForDecl)
2948 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2949
John McCallf4c73712011-01-19 06:33:43 +00002950 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2951 Decl->TypeForDecl = newType;
2952 Types.push_back(newType);
2953 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002954}
2955
Jay Foad4ba2a172011-01-12 09:06:06 +00002956QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002957 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2958
Douglas Gregoref96ee02012-01-14 16:38:05 +00002959 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002960 if (PrevDecl->TypeForDecl)
2961 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2962
John McCallf4c73712011-01-19 06:33:43 +00002963 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2964 Decl->TypeForDecl = newType;
2965 Types.push_back(newType);
2966 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002967}
2968
John McCall9d156a72011-01-06 01:58:22 +00002969QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2970 QualType modifiedType,
2971 QualType equivalentType) {
2972 llvm::FoldingSetNodeID id;
2973 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2974
2975 void *insertPos = 0;
2976 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2977 if (type) return QualType(type, 0);
2978
2979 QualType canon = getCanonicalType(equivalentType);
2980 type = new (*this, TypeAlignment)
2981 AttributedType(canon, attrKind, modifiedType, equivalentType);
2982
2983 Types.push_back(type);
2984 AttributedTypes.InsertNode(type, insertPos);
2985
2986 return QualType(type, 0);
2987}
2988
2989
John McCall49a832b2009-10-18 09:09:24 +00002990/// \brief Retrieve a substitution-result type.
2991QualType
2992ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002993 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002994 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002995 && "replacement types must always be canonical");
2996
2997 llvm::FoldingSetNodeID ID;
2998 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2999 void *InsertPos = 0;
3000 SubstTemplateTypeParmType *SubstParm
3001 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3002
3003 if (!SubstParm) {
3004 SubstParm = new (*this, TypeAlignment)
3005 SubstTemplateTypeParmType(Parm, Replacement);
3006 Types.push_back(SubstParm);
3007 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3008 }
3009
3010 return QualType(SubstParm, 0);
3011}
3012
Douglas Gregorc3069d62011-01-14 02:55:32 +00003013/// \brief Retrieve a
3014QualType ASTContext::getSubstTemplateTypeParmPackType(
3015 const TemplateTypeParmType *Parm,
3016 const TemplateArgument &ArgPack) {
3017#ifndef NDEBUG
3018 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
3019 PEnd = ArgPack.pack_end();
3020 P != PEnd; ++P) {
3021 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3022 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
3023 }
3024#endif
3025
3026 llvm::FoldingSetNodeID ID;
3027 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3028 void *InsertPos = 0;
3029 if (SubstTemplateTypeParmPackType *SubstParm
3030 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3031 return QualType(SubstParm, 0);
3032
3033 QualType Canon;
3034 if (!Parm->isCanonicalUnqualified()) {
3035 Canon = getCanonicalType(QualType(Parm, 0));
3036 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3037 ArgPack);
3038 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3039 }
3040
3041 SubstTemplateTypeParmPackType *SubstParm
3042 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3043 ArgPack);
3044 Types.push_back(SubstParm);
3045 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3046 return QualType(SubstParm, 0);
3047}
3048
Douglas Gregorfab9d672009-02-05 23:33:38 +00003049/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00003050/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003051/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00003052QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003053 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003054 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00003055 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003056 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00003057 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003058 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00003059 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3060
3061 if (TypeParm)
3062 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003063
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003064 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003065 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003066 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003067
3068 TemplateTypeParmType *TypeCheck
3069 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3070 assert(!TypeCheck && "Template type parameter canonical type broken");
3071 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003072 } else
John McCall6b304a02009-09-24 23:30:46 +00003073 TypeParm = new (*this, TypeAlignment)
3074 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00003075
3076 Types.push_back(TypeParm);
3077 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3078
3079 return QualType(TypeParm, 0);
3080}
3081
John McCall3cb0ebd2010-03-10 03:28:59 +00003082TypeSourceInfo *
3083ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3084 SourceLocation NameLoc,
3085 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003086 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003087 assert(!Name.getAsDependentTemplateName() &&
3088 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00003089 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00003090
3091 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie39e6ab42013-02-18 22:06:02 +00003092 TemplateSpecializationTypeLoc TL =
3093 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara55d23c92012-02-06 14:41:24 +00003094 TL.setTemplateKeywordLoc(SourceLocation());
John McCall3cb0ebd2010-03-10 03:28:59 +00003095 TL.setTemplateNameLoc(NameLoc);
3096 TL.setLAngleLoc(Args.getLAngleLoc());
3097 TL.setRAngleLoc(Args.getRAngleLoc());
3098 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3099 TL.setArgLocInfo(i, Args[i].getLocInfo());
3100 return DI;
3101}
3102
Mike Stump1eb44332009-09-09 15:08:12 +00003103QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00003104ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00003105 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003106 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003107 assert(!Template.getAsDependentTemplateName() &&
3108 "No dependent template names here!");
3109
John McCalld5532b62009-11-23 01:53:49 +00003110 unsigned NumArgs = Args.size();
3111
Chris Lattner5f9e2722011-07-23 10:55:15 +00003112 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00003113 ArgVec.reserve(NumArgs);
3114 for (unsigned i = 0; i != NumArgs; ++i)
3115 ArgVec.push_back(Args[i].getArgument());
3116
John McCall31f17ec2010-04-27 00:57:59 +00003117 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003118 Underlying);
John McCall833ca992009-10-29 08:12:44 +00003119}
3120
Douglas Gregorb70126a2012-02-03 17:16:23 +00003121#ifndef NDEBUG
3122static bool hasAnyPackExpansions(const TemplateArgument *Args,
3123 unsigned NumArgs) {
3124 for (unsigned I = 0; I != NumArgs; ++I)
3125 if (Args[I].isPackExpansion())
3126 return true;
3127
3128 return true;
3129}
3130#endif
3131
John McCall833ca992009-10-29 08:12:44 +00003132QualType
3133ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003134 const TemplateArgument *Args,
3135 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003136 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003137 assert(!Template.getAsDependentTemplateName() &&
3138 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003139 // Look through qualified template names.
3140 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3141 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003142
Douglas Gregorb70126a2012-02-03 17:16:23 +00003143 bool IsTypeAlias =
Richard Smith3e4c6c42011-05-05 21:57:07 +00003144 Template.getAsTemplateDecl() &&
3145 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00003146 QualType CanonType;
3147 if (!Underlying.isNull())
3148 CanonType = getCanonicalType(Underlying);
3149 else {
Douglas Gregorb70126a2012-02-03 17:16:23 +00003150 // We can get here with an alias template when the specialization contains
3151 // a pack expansion that does not match up with a parameter pack.
3152 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3153 "Caller must compute aliased type");
3154 IsTypeAlias = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00003155 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3156 NumArgs);
3157 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00003158
Douglas Gregor1275ae02009-07-28 23:00:59 +00003159 // Allocate the (non-canonical) template specialization type, but don't
3160 // try to unique it: these types typically have location information that
3161 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00003162 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3163 sizeof(TemplateArgument) * NumArgs +
Douglas Gregorb70126a2012-02-03 17:16:23 +00003164 (IsTypeAlias? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00003165 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00003166 TemplateSpecializationType *Spec
Douglas Gregorb70126a2012-02-03 17:16:23 +00003167 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3168 IsTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00003169
Douglas Gregor55f6b142009-02-09 18:46:07 +00003170 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00003171 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00003172}
3173
Mike Stump1eb44332009-09-09 15:08:12 +00003174QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003175ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3176 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00003177 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003178 assert(!Template.getAsDependentTemplateName() &&
3179 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00003180
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003181 // Look through qualified template names.
3182 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3183 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003184
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003185 // Build the canonical template specialization type.
3186 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003187 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003188 CanonArgs.reserve(NumArgs);
3189 for (unsigned I = 0; I != NumArgs; ++I)
3190 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3191
3192 // Determine whether this canonical template specialization type already
3193 // exists.
3194 llvm::FoldingSetNodeID ID;
3195 TemplateSpecializationType::Profile(ID, CanonTemplate,
3196 CanonArgs.data(), NumArgs, *this);
3197
3198 void *InsertPos = 0;
3199 TemplateSpecializationType *Spec
3200 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3201
3202 if (!Spec) {
3203 // Allocate a new canonical template specialization type.
3204 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3205 sizeof(TemplateArgument) * NumArgs),
3206 TypeAlignment);
3207 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3208 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003209 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003210 Types.push_back(Spec);
3211 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3212 }
3213
3214 assert(Spec->isDependentType() &&
3215 "Non-dependent template-id type must have a canonical type");
3216 return QualType(Spec, 0);
3217}
3218
3219QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003220ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3221 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00003222 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00003223 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003224 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003225
3226 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003227 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003228 if (T)
3229 return QualType(T, 0);
3230
Douglas Gregor789b1f62010-02-04 18:10:26 +00003231 QualType Canon = NamedType;
3232 if (!Canon.isCanonical()) {
3233 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003234 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3235 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00003236 (void)CheckT;
3237 }
3238
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003239 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003240 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003241 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003242 return QualType(T, 0);
3243}
3244
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003245QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00003246ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003247 llvm::FoldingSetNodeID ID;
3248 ParenType::Profile(ID, InnerType);
3249
3250 void *InsertPos = 0;
3251 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3252 if (T)
3253 return QualType(T, 0);
3254
3255 QualType Canon = InnerType;
3256 if (!Canon.isCanonical()) {
3257 Canon = getCanonicalType(InnerType);
3258 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3259 assert(!CheckT && "Paren canonical type broken");
3260 (void)CheckT;
3261 }
3262
3263 T = new (*this) ParenType(InnerType, Canon);
3264 Types.push_back(T);
3265 ParenTypes.InsertNode(T, InsertPos);
3266 return QualType(T, 0);
3267}
3268
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003269QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3270 NestedNameSpecifier *NNS,
3271 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003272 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00003273 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3274
3275 if (Canon.isNull()) {
3276 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003277 ElaboratedTypeKeyword CanonKeyword = Keyword;
3278 if (Keyword == ETK_None)
3279 CanonKeyword = ETK_Typename;
3280
3281 if (CanonNNS != NNS || CanonKeyword != Keyword)
3282 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003283 }
3284
3285 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003286 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003287
3288 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00003289 DependentNameType *T
3290 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00003291 if (T)
3292 return QualType(T, 0);
3293
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003294 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00003295 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00003296 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003297 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00003298}
3299
Mike Stump1eb44332009-09-09 15:08:12 +00003300QualType
John McCall33500952010-06-11 00:33:02 +00003301ASTContext::getDependentTemplateSpecializationType(
3302 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003303 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00003304 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003305 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00003306 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00003307 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00003308 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3309 ArgCopy.push_back(Args[I].getArgument());
3310 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3311 ArgCopy.size(),
3312 ArgCopy.data());
3313}
3314
3315QualType
3316ASTContext::getDependentTemplateSpecializationType(
3317 ElaboratedTypeKeyword Keyword,
3318 NestedNameSpecifier *NNS,
3319 const IdentifierInfo *Name,
3320 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00003321 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003322 assert((!NNS || NNS->isDependent()) &&
3323 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00003324
Douglas Gregor789b1f62010-02-04 18:10:26 +00003325 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00003326 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3327 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003328
3329 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00003330 DependentTemplateSpecializationType *T
3331 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003332 if (T)
3333 return QualType(T, 0);
3334
John McCall33500952010-06-11 00:33:02 +00003335 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003336
John McCall33500952010-06-11 00:33:02 +00003337 ElaboratedTypeKeyword CanonKeyword = Keyword;
3338 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3339
3340 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003341 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00003342 for (unsigned I = 0; I != NumArgs; ++I) {
3343 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3344 if (!CanonArgs[I].structurallyEquals(Args[I]))
3345 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00003346 }
3347
John McCall33500952010-06-11 00:33:02 +00003348 QualType Canon;
3349 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3350 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3351 Name, NumArgs,
3352 CanonArgs.data());
3353
3354 // Find the insert position again.
3355 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3356 }
3357
3358 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3359 sizeof(TemplateArgument) * NumArgs),
3360 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00003361 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00003362 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00003363 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00003364 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003365 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00003366}
3367
Douglas Gregorcded4f62011-01-14 17:04:44 +00003368QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikiedc84cd52013-02-20 22:23:23 +00003369 Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00003370 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00003371 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003372
3373 assert(Pattern->containsUnexpandedParameterPack() &&
3374 "Pack expansions must expand one or more parameter packs");
3375 void *InsertPos = 0;
3376 PackExpansionType *T
3377 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3378 if (T)
3379 return QualType(T, 0);
3380
3381 QualType Canon;
3382 if (!Pattern.isCanonical()) {
Richard Smithd8672ef2012-07-16 00:20:35 +00003383 Canon = getCanonicalType(Pattern);
3384 // The canonical type might not contain an unexpanded parameter pack, if it
3385 // contains an alias template specialization which ignores one of its
3386 // parameters.
3387 if (Canon->containsUnexpandedParameterPack()) {
3388 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003389
Richard Smithd8672ef2012-07-16 00:20:35 +00003390 // Find the insert position again, in case we inserted an element into
3391 // PackExpansionTypes and invalidated our insert position.
3392 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3393 }
Douglas Gregor7536dd52010-12-20 02:24:11 +00003394 }
3395
Douglas Gregorcded4f62011-01-14 17:04:44 +00003396 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003397 Types.push_back(T);
3398 PackExpansionTypes.InsertNode(T, InsertPos);
3399 return QualType(T, 0);
3400}
3401
Chris Lattner88cb27a2008-04-07 04:56:42 +00003402/// CmpProtocolNames - Comparison predicate for sorting protocols
3403/// alphabetically.
3404static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3405 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003406 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00003407}
3408
John McCallc12c5bb2010-05-15 11:32:37 +00003409static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00003410 unsigned NumProtocols) {
3411 if (NumProtocols == 0) return true;
3412
Douglas Gregor61cc2962012-01-02 02:00:30 +00003413 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3414 return false;
3415
John McCall54e14c42009-10-22 22:37:11 +00003416 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregor61cc2962012-01-02 02:00:30 +00003417 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3418 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCall54e14c42009-10-22 22:37:11 +00003419 return false;
3420 return true;
3421}
3422
3423static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00003424 unsigned &NumProtocols) {
3425 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00003426
Chris Lattner88cb27a2008-04-07 04:56:42 +00003427 // Sort protocols, keyed by name.
3428 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3429
Douglas Gregor61cc2962012-01-02 02:00:30 +00003430 // Canonicalize.
3431 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3432 Protocols[I] = Protocols[I]->getCanonicalDecl();
3433
Chris Lattner88cb27a2008-04-07 04:56:42 +00003434 // Remove duplicates.
3435 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3436 NumProtocols = ProtocolsEnd-Protocols;
3437}
3438
John McCallc12c5bb2010-05-15 11:32:37 +00003439QualType ASTContext::getObjCObjectType(QualType BaseType,
3440 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00003441 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003442 // If the base type is an interface and there aren't any protocols
3443 // to add, then the interface type will do just fine.
3444 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3445 return BaseType;
3446
3447 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003448 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00003449 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003450 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00003451 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3452 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003453
John McCallc12c5bb2010-05-15 11:32:37 +00003454 // Build the canonical type, which has the canonical base type and
3455 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00003456 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00003457 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3458 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3459 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003460 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00003461 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003462 unsigned UniqueCount = NumProtocols;
3463
John McCall54e14c42009-10-22 22:37:11 +00003464 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00003465 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3466 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00003467 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00003468 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3469 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003470 }
3471
3472 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00003473 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3474 }
3475
3476 unsigned Size = sizeof(ObjCObjectTypeImpl);
3477 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3478 void *Mem = Allocate(Size, TypeAlignment);
3479 ObjCObjectTypeImpl *T =
3480 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3481
3482 Types.push_back(T);
3483 ObjCObjectTypes.InsertNode(T, InsertPos);
3484 return QualType(T, 0);
3485}
3486
3487/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3488/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003489QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003490 llvm::FoldingSetNodeID ID;
3491 ObjCObjectPointerType::Profile(ID, ObjectT);
3492
3493 void *InsertPos = 0;
3494 if (ObjCObjectPointerType *QT =
3495 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3496 return QualType(QT, 0);
3497
3498 // Find the canonical object type.
3499 QualType Canonical;
3500 if (!ObjectT.isCanonical()) {
3501 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3502
3503 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00003504 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3505 }
3506
Douglas Gregorfd6a0882010-02-08 22:59:26 +00003507 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00003508 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3509 ObjCObjectPointerType *QType =
3510 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00003511
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003512 Types.push_back(QType);
3513 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00003514 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003515}
Chris Lattner88cb27a2008-04-07 04:56:42 +00003516
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003517/// getObjCInterfaceType - Return the unique reference to the type for the
3518/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00003519QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3520 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003521 if (Decl->TypeForDecl)
3522 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003523
Douglas Gregor0af55012011-12-16 03:12:41 +00003524 if (PrevDecl) {
3525 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3526 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3527 return QualType(PrevDecl->TypeForDecl, 0);
3528 }
3529
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00003530 // Prefer the definition, if there is one.
3531 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3532 Decl = Def;
3533
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003534 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3535 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3536 Decl->TypeForDecl = T;
3537 Types.push_back(T);
3538 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00003539}
3540
Douglas Gregor72564e72009-02-26 23:50:07 +00003541/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3542/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00003543/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00003544/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003545/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003546QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003547 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00003548 if (tofExpr->isTypeDependent()) {
3549 llvm::FoldingSetNodeID ID;
3550 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00003551
Douglas Gregorb1975722009-07-30 23:18:24 +00003552 void *InsertPos = 0;
3553 DependentTypeOfExprType *Canon
3554 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3555 if (Canon) {
3556 // We already have a "canonical" version of an identical, dependent
3557 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00003558 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00003559 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003560 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00003561 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003562 Canon
3563 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00003564 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3565 toe = Canon;
3566 }
3567 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003568 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00003569 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00003570 }
Steve Naroff9752f252007-08-01 18:02:17 +00003571 Types.push_back(toe);
3572 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003573}
3574
Steve Naroff9752f252007-08-01 18:02:17 +00003575/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3576/// TypeOfType AST's. The only motivation to unique these nodes would be
3577/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003578/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003579/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003580QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00003581 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00003582 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00003583 Types.push_back(tot);
3584 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003585}
3586
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00003587
Anders Carlsson395b4752009-06-24 19:06:50 +00003588/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3589/// DecltypeType AST's. The only motivation to unique these nodes would be
3590/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003591/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00003592/// on canonical types (which are always unique).
Douglas Gregorf8af9822012-02-12 18:42:33 +00003593QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003594 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00003595
3596 // C++0x [temp.type]p2:
3597 // If an expression e involves a template parameter, decltype(e) denotes a
3598 // unique dependent type. Two such decltype-specifiers refer to the same
3599 // type only if their expressions are equivalent (14.5.6.1).
3600 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003601 llvm::FoldingSetNodeID ID;
3602 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00003603
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003604 void *InsertPos = 0;
3605 DependentDecltypeType *Canon
3606 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3607 if (Canon) {
3608 // We already have a "canonical" version of an equivalent, dependent
3609 // decltype type. Use that as our canonical type.
Richard Smith0d729102012-08-13 20:08:14 +00003610 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003611 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003612 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003613 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003614 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003615 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3616 dt = Canon;
3617 }
3618 } else {
Douglas Gregorf8af9822012-02-12 18:42:33 +00003619 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3620 getCanonicalType(UnderlyingType));
Douglas Gregordd0257c2009-07-08 00:03:05 +00003621 }
Anders Carlsson395b4752009-06-24 19:06:50 +00003622 Types.push_back(dt);
3623 return QualType(dt, 0);
3624}
3625
Sean Huntca63c202011-05-24 22:41:36 +00003626/// getUnaryTransformationType - We don't unique these, since the memory
3627/// savings are minimal and these are rare.
3628QualType ASTContext::getUnaryTransformType(QualType BaseType,
3629 QualType UnderlyingType,
3630 UnaryTransformType::UTTKind Kind)
3631 const {
3632 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00003633 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3634 Kind,
3635 UnderlyingType->isDependentType() ?
Peter Collingbourne12fc4b02012-03-05 16:02:06 +00003636 QualType() : getCanonicalType(UnderlyingType));
Sean Huntca63c202011-05-24 22:41:36 +00003637 Types.push_back(Ty);
3638 return QualType(Ty, 0);
3639}
3640
Richard Smith60e141e2013-05-04 07:00:32 +00003641/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3642/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3643/// canonical deduced-but-dependent 'auto' type.
3644QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Richard Smithdc7a4f52013-04-30 13:56:41 +00003645 bool IsDependent) const {
Richard Smith60e141e2013-05-04 07:00:32 +00003646 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
3647 return getAutoDeductType();
3648
3649 // Look in the folding set for an existing type.
Richard Smith483b9f32011-02-21 20:05:19 +00003650 void *InsertPos = 0;
Richard Smith60e141e2013-05-04 07:00:32 +00003651 llvm::FoldingSetNodeID ID;
3652 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
3653 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3654 return QualType(AT, 0);
Richard Smith483b9f32011-02-21 20:05:19 +00003655
Richard Smitha2c36462013-04-26 16:15:35 +00003656 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithdc7a4f52013-04-30 13:56:41 +00003657 IsDecltypeAuto,
3658 IsDependent);
Richard Smith483b9f32011-02-21 20:05:19 +00003659 Types.push_back(AT);
3660 if (InsertPos)
3661 AutoTypes.InsertNode(AT, InsertPos);
3662 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00003663}
3664
Eli Friedmanb001de72011-10-06 23:00:33 +00003665/// getAtomicType - Return the uniqued reference to the atomic type for
3666/// the given value type.
3667QualType ASTContext::getAtomicType(QualType T) const {
3668 // Unique pointers, to guarantee there is only one pointer of a particular
3669 // structure.
3670 llvm::FoldingSetNodeID ID;
3671 AtomicType::Profile(ID, T);
3672
3673 void *InsertPos = 0;
3674 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3675 return QualType(AT, 0);
3676
3677 // If the atomic value type isn't canonical, this won't be a canonical type
3678 // either, so fill in the canonical type field.
3679 QualType Canonical;
3680 if (!T.isCanonical()) {
3681 Canonical = getAtomicType(getCanonicalType(T));
3682
3683 // Get the new insert position for the node we care about.
3684 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3685 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3686 }
3687 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3688 Types.push_back(New);
3689 AtomicTypes.InsertNode(New, InsertPos);
3690 return QualType(New, 0);
3691}
3692
Richard Smithad762fc2011-04-14 22:09:26 +00003693/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3694QualType ASTContext::getAutoDeductType() const {
3695 if (AutoDeductTy.isNull())
Richard Smith60e141e2013-05-04 07:00:32 +00003696 AutoDeductTy = QualType(
3697 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
3698 /*dependent*/false),
3699 0);
Richard Smithad762fc2011-04-14 22:09:26 +00003700 return AutoDeductTy;
3701}
3702
3703/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3704QualType ASTContext::getAutoRRefDeductType() const {
3705 if (AutoRRefDeductTy.isNull())
3706 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3707 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3708 return AutoRRefDeductTy;
3709}
3710
Reid Spencer5f016e22007-07-11 17:01:13 +00003711/// getTagDeclType - Return the unique reference to the type for the
3712/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003713QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003714 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003715 // FIXME: What is the design on getTagDeclType when it requires casting
3716 // away const? mutable?
3717 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003718}
3719
Mike Stump1eb44332009-09-09 15:08:12 +00003720/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3721/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3722/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003723CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003724 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003725}
3726
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003727/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3728CanQualType ASTContext::getIntMaxType() const {
3729 return getFromTargetType(Target->getIntMaxType());
3730}
3731
3732/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3733CanQualType ASTContext::getUIntMaxType() const {
3734 return getFromTargetType(Target->getUIntMaxType());
3735}
3736
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003737/// getSignedWCharType - Return the type of "signed wchar_t".
3738/// Used when in C++, as a GCC extension.
3739QualType ASTContext::getSignedWCharType() const {
3740 // FIXME: derive from "Target" ?
3741 return WCharTy;
3742}
3743
3744/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3745/// Used when in C++, as a GCC extension.
3746QualType ASTContext::getUnsignedWCharType() const {
3747 // FIXME: derive from "Target" ?
3748 return UnsignedIntTy;
3749}
3750
Enea Zaffanella9677eb82013-01-26 17:08:37 +00003751QualType ASTContext::getIntPtrType() const {
3752 return getFromTargetType(Target->getIntPtrType());
3753}
3754
3755QualType ASTContext::getUIntPtrType() const {
3756 return getCorrespondingUnsignedType(getIntPtrType());
3757}
3758
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003759/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003760/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3761QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003762 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003763}
3764
Eli Friedman6902e412012-11-27 02:58:24 +00003765/// \brief Return the unique type for "pid_t" defined in
3766/// <sys/types.h>. We need this to compute the correct type for vfork().
3767QualType ASTContext::getProcessIDType() const {
3768 return getFromTargetType(Target->getProcessIDType());
3769}
3770
Chris Lattnere6327742008-04-02 05:18:44 +00003771//===----------------------------------------------------------------------===//
3772// Type Operators
3773//===----------------------------------------------------------------------===//
3774
Jay Foad4ba2a172011-01-12 09:06:06 +00003775CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003776 // Push qualifiers into arrays, and then discard any remaining
3777 // qualifiers.
3778 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003779 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003780 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003781 QualType Result;
3782 if (isa<ArrayType>(Ty)) {
3783 Result = getArrayDecayedType(QualType(Ty,0));
3784 } else if (isa<FunctionType>(Ty)) {
3785 Result = getPointerType(QualType(Ty, 0));
3786 } else {
3787 Result = QualType(Ty, 0);
3788 }
3789
3790 return CanQualType::CreateUnsafe(Result);
3791}
3792
John McCall62c28c82011-01-18 07:41:22 +00003793QualType ASTContext::getUnqualifiedArrayType(QualType type,
3794 Qualifiers &quals) {
3795 SplitQualType splitType = type.getSplitUnqualifiedType();
3796
3797 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3798 // the unqualified desugared type and then drops it on the floor.
3799 // We then have to strip that sugar back off with
3800 // getUnqualifiedDesugaredType(), which is silly.
3801 const ArrayType *AT =
John McCall200fa532012-02-08 00:46:36 +00003802 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall62c28c82011-01-18 07:41:22 +00003803
3804 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003805 if (!AT) {
John McCall200fa532012-02-08 00:46:36 +00003806 quals = splitType.Quals;
3807 return QualType(splitType.Ty, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003808 }
3809
John McCall62c28c82011-01-18 07:41:22 +00003810 // Otherwise, recurse on the array's element type.
3811 QualType elementType = AT->getElementType();
3812 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3813
3814 // If that didn't change the element type, AT has no qualifiers, so we
3815 // can just use the results in splitType.
3816 if (elementType == unqualElementType) {
3817 assert(quals.empty()); // from the recursive call
John McCall200fa532012-02-08 00:46:36 +00003818 quals = splitType.Quals;
3819 return QualType(splitType.Ty, 0);
John McCall62c28c82011-01-18 07:41:22 +00003820 }
3821
3822 // Otherwise, add in the qualifiers from the outermost type, then
3823 // build the type back up.
John McCall200fa532012-02-08 00:46:36 +00003824 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003825
Douglas Gregor9dadd942010-05-17 18:45:21 +00003826 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003827 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003828 CAT->getSizeModifier(), 0);
3829 }
3830
Douglas Gregor9dadd942010-05-17 18:45:21 +00003831 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003832 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003833 }
3834
Douglas Gregor9dadd942010-05-17 18:45:21 +00003835 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003836 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003837 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003838 VAT->getSizeModifier(),
3839 VAT->getIndexTypeCVRQualifiers(),
3840 VAT->getBracketsRange());
3841 }
3842
3843 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003844 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003845 DSAT->getSizeModifier(), 0,
3846 SourceRange());
3847}
3848
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003849/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3850/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3851/// they point to and return true. If T1 and T2 aren't pointer types
3852/// or pointer-to-member types, or if they are not similar at this
3853/// level, returns false and leaves T1 and T2 unchanged. Top-level
3854/// qualifiers on T1 and T2 are ignored. This function will typically
3855/// be called in a loop that successively "unwraps" pointer and
3856/// pointer-to-member types to compare them at each level.
3857bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3858 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3859 *T2PtrType = T2->getAs<PointerType>();
3860 if (T1PtrType && T2PtrType) {
3861 T1 = T1PtrType->getPointeeType();
3862 T2 = T2PtrType->getPointeeType();
3863 return true;
3864 }
3865
3866 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3867 *T2MPType = T2->getAs<MemberPointerType>();
3868 if (T1MPType && T2MPType &&
3869 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3870 QualType(T2MPType->getClass(), 0))) {
3871 T1 = T1MPType->getPointeeType();
3872 T2 = T2MPType->getPointeeType();
3873 return true;
3874 }
3875
David Blaikie4e4d0842012-03-11 07:00:24 +00003876 if (getLangOpts().ObjC1) {
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003877 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3878 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3879 if (T1OPType && T2OPType) {
3880 T1 = T1OPType->getPointeeType();
3881 T2 = T2OPType->getPointeeType();
3882 return true;
3883 }
3884 }
3885
3886 // FIXME: Block pointers, too?
3887
3888 return false;
3889}
3890
Jay Foad4ba2a172011-01-12 09:06:06 +00003891DeclarationNameInfo
3892ASTContext::getNameForTemplate(TemplateName Name,
3893 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003894 switch (Name.getKind()) {
3895 case TemplateName::QualifiedTemplate:
3896 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003897 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003898 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3899 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003900
John McCall14606042011-06-30 08:33:18 +00003901 case TemplateName::OverloadedTemplate: {
3902 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3903 // DNInfo work in progress: CHECKME: what about DNLoc?
3904 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3905 }
3906
3907 case TemplateName::DependentTemplate: {
3908 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003909 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003910 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003911 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3912 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003913 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003914 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3915 // DNInfo work in progress: FIXME: source locations?
3916 DeclarationNameLoc DNLoc;
3917 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3918 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3919 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003920 }
3921 }
3922
John McCall14606042011-06-30 08:33:18 +00003923 case TemplateName::SubstTemplateTemplateParm: {
3924 SubstTemplateTemplateParmStorage *subst
3925 = Name.getAsSubstTemplateTemplateParm();
3926 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3927 NameLoc);
3928 }
3929
3930 case TemplateName::SubstTemplateTemplateParmPack: {
3931 SubstTemplateTemplateParmPackStorage *subst
3932 = Name.getAsSubstTemplateTemplateParmPack();
3933 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3934 NameLoc);
3935 }
3936 }
3937
3938 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003939}
3940
Jay Foad4ba2a172011-01-12 09:06:06 +00003941TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003942 switch (Name.getKind()) {
3943 case TemplateName::QualifiedTemplate:
3944 case TemplateName::Template: {
3945 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003946 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003947 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003948 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3949
3950 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003951 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003952 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003953
John McCall14606042011-06-30 08:33:18 +00003954 case TemplateName::OverloadedTemplate:
3955 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003956
John McCall14606042011-06-30 08:33:18 +00003957 case TemplateName::DependentTemplate: {
3958 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3959 assert(DTN && "Non-dependent template names must refer to template decls.");
3960 return DTN->CanonicalTemplateName;
3961 }
3962
3963 case TemplateName::SubstTemplateTemplateParm: {
3964 SubstTemplateTemplateParmStorage *subst
3965 = Name.getAsSubstTemplateTemplateParm();
3966 return getCanonicalTemplateName(subst->getReplacement());
3967 }
3968
3969 case TemplateName::SubstTemplateTemplateParmPack: {
3970 SubstTemplateTemplateParmPackStorage *subst
3971 = Name.getAsSubstTemplateTemplateParmPack();
3972 TemplateTemplateParmDecl *canonParameter
3973 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3974 TemplateArgument canonArgPack
3975 = getCanonicalTemplateArgument(subst->getArgumentPack());
3976 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3977 }
3978 }
3979
3980 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003981}
3982
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003983bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3984 X = getCanonicalTemplateName(X);
3985 Y = getCanonicalTemplateName(Y);
3986 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3987}
3988
Mike Stump1eb44332009-09-09 15:08:12 +00003989TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003990ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003991 switch (Arg.getKind()) {
3992 case TemplateArgument::Null:
3993 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003994
Douglas Gregor1275ae02009-07-28 23:00:59 +00003995 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003996 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003997
Douglas Gregord2008e22012-04-06 22:40:38 +00003998 case TemplateArgument::Declaration: {
Eli Friedmand7a6b162012-09-26 02:36:12 +00003999 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4000 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregord2008e22012-04-06 22:40:38 +00004001 }
Mike Stump1eb44332009-09-09 15:08:12 +00004002
Eli Friedmand7a6b162012-09-26 02:36:12 +00004003 case TemplateArgument::NullPtr:
4004 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4005 /*isNullPtr*/true);
4006
Douglas Gregor788cd062009-11-11 01:00:40 +00004007 case TemplateArgument::Template:
4008 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00004009
4010 case TemplateArgument::TemplateExpansion:
4011 return TemplateArgument(getCanonicalTemplateName(
4012 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00004013 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00004014
Douglas Gregor1275ae02009-07-28 23:00:59 +00004015 case TemplateArgument::Integral:
Benjamin Kramer85524372012-06-07 15:09:51 +00004016 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00004017
Douglas Gregor1275ae02009-07-28 23:00:59 +00004018 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00004019 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00004020
Douglas Gregor1275ae02009-07-28 23:00:59 +00004021 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00004022 if (Arg.pack_size() == 0)
4023 return Arg;
4024
Douglas Gregor910f8002010-11-07 23:05:16 +00004025 TemplateArgument *CanonArgs
4026 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00004027 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004028 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00004029 AEnd = Arg.pack_end();
4030 A != AEnd; (void)++A, ++Idx)
4031 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00004032
Douglas Gregor910f8002010-11-07 23:05:16 +00004033 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00004034 }
4035 }
4036
4037 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00004038 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00004039}
4040
Douglas Gregord57959a2009-03-27 23:10:48 +00004041NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00004042ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004043 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00004044 return 0;
4045
4046 switch (NNS->getKind()) {
4047 case NestedNameSpecifier::Identifier:
4048 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00004049 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00004050 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4051 NNS->getAsIdentifier());
4052
4053 case NestedNameSpecifier::Namespace:
4054 // A namespace is canonical; build a nested-name-specifier with
4055 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00004056 return NestedNameSpecifier::Create(*this, 0,
4057 NNS->getAsNamespace()->getOriginalNamespace());
4058
4059 case NestedNameSpecifier::NamespaceAlias:
4060 // A namespace is canonical; build a nested-name-specifier with
4061 // this namespace and no prefix.
4062 return NestedNameSpecifier::Create(*this, 0,
4063 NNS->getAsNamespaceAlias()->getNamespace()
4064 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00004065
4066 case NestedNameSpecifier::TypeSpec:
4067 case NestedNameSpecifier::TypeSpecWithTemplate: {
4068 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00004069
4070 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4071 // break it apart into its prefix and identifier, then reconsititute those
4072 // as the canonical nested-name-specifier. This is required to canonicalize
4073 // a dependent nested-name-specifier involving typedefs of dependent-name
4074 // types, e.g.,
4075 // typedef typename T::type T1;
4076 // typedef typename T1::type T2;
Eli Friedman16412ef2012-03-03 04:09:56 +00004077 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4078 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor264bf662010-11-04 00:09:33 +00004079 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor264bf662010-11-04 00:09:33 +00004080
Eli Friedman16412ef2012-03-03 04:09:56 +00004081 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4082 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4083 // first place?
John McCall3b657512011-01-19 10:06:00 +00004084 return NestedNameSpecifier::Create(*this, 0, false,
4085 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00004086 }
4087
4088 case NestedNameSpecifier::Global:
4089 // The global specifier is canonical and unique.
4090 return NNS;
4091 }
4092
David Blaikie7530c032012-01-17 06:56:22 +00004093 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregord57959a2009-03-27 23:10:48 +00004094}
4095
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004096
Jay Foad4ba2a172011-01-12 09:06:06 +00004097const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004098 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004099 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004100 // Handle the common positive case fast.
4101 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4102 return AT;
4103 }
Mike Stump1eb44332009-09-09 15:08:12 +00004104
John McCall0953e762009-09-24 19:53:00 +00004105 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00004106 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004107 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004108
John McCall0953e762009-09-24 19:53:00 +00004109 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004110 // implements C99 6.7.3p8: "If the specification of an array type includes
4111 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00004112
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004113 // If we get here, we either have type qualifiers on the type, or we have
4114 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00004115 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00004116
John McCall3b657512011-01-19 10:06:00 +00004117 SplitQualType split = T.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004118 Qualifiers qs = split.Quals;
Mike Stump1eb44332009-09-09 15:08:12 +00004119
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004120 // If we have a simple case, just return now.
John McCall200fa532012-02-08 00:46:36 +00004121 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall3b657512011-01-19 10:06:00 +00004122 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004123 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00004124
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004125 // Otherwise, we have an array and we have qualifiers on it. Push the
4126 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00004127 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00004128
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004129 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4130 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4131 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004132 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004133 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4134 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4135 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004136 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00004137
Mike Stump1eb44332009-09-09 15:08:12 +00004138 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00004139 = dyn_cast<DependentSizedArrayType>(ATy))
4140 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00004141 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00004142 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00004143 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004144 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004145 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00004146
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004147 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004148 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00004149 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004150 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004151 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004152 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00004153}
4154
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004155QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004156 // C99 6.7.5.3p7:
4157 // A declaration of a parameter as "array of type" shall be
4158 // adjusted to "qualified pointer to type", where the type
4159 // qualifiers (if any) are those specified within the [ and ] of
4160 // the array type derivation.
4161 if (T->isArrayType())
4162 return getArrayDecayedType(T);
4163
4164 // C99 6.7.5.3p8:
4165 // A declaration of a parameter as "function returning type"
4166 // shall be adjusted to "pointer to function returning type", as
4167 // in 6.3.2.1.
4168 if (T->isFunctionType())
4169 return getPointerType(T);
4170
4171 return T;
4172}
4173
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004174QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004175 T = getVariableArrayDecayedType(T);
4176 T = getAdjustedParameterType(T);
4177 return T.getUnqualifiedType();
4178}
4179
Chris Lattnere6327742008-04-02 05:18:44 +00004180/// getArrayDecayedType - Return the properly qualified result of decaying the
4181/// specified array type to a pointer. This operation is non-trivial when
4182/// handling typedefs etc. The canonical type of "T" must be an array type,
4183/// this returns a pointer to a properly qualified element of the array.
4184///
4185/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00004186QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004187 // Get the element type with 'getAsArrayType' so that we don't lose any
4188 // typedefs in the element type of the array. This also handles propagation
4189 // of type qualifiers from the array type into the element type if present
4190 // (C99 6.7.3p8).
4191 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4192 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00004193
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004194 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00004195
4196 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00004197 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00004198}
4199
John McCall3b657512011-01-19 10:06:00 +00004200QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4201 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00004202}
4203
John McCall3b657512011-01-19 10:06:00 +00004204QualType ASTContext::getBaseElementType(QualType type) const {
4205 Qualifiers qs;
4206 while (true) {
4207 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004208 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall3b657512011-01-19 10:06:00 +00004209 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00004210
John McCall3b657512011-01-19 10:06:00 +00004211 type = array->getElementType();
John McCall200fa532012-02-08 00:46:36 +00004212 qs.addConsistentQualifiers(split.Quals);
John McCall3b657512011-01-19 10:06:00 +00004213 }
Mike Stump1eb44332009-09-09 15:08:12 +00004214
John McCall3b657512011-01-19 10:06:00 +00004215 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00004216}
4217
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004218/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00004219uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004220ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4221 uint64_t ElementCount = 1;
4222 do {
4223 ElementCount *= CA->getSize().getZExtValue();
Richard Smithd5e83942012-12-06 03:04:50 +00004224 CA = dyn_cast_or_null<ConstantArrayType>(
4225 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004226 } while (CA);
4227 return ElementCount;
4228}
4229
Reid Spencer5f016e22007-07-11 17:01:13 +00004230/// getFloatingRank - Return a relative rank for floating point types.
4231/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00004232static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00004233 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00004234 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00004235
John McCall183700f2009-09-21 23:43:11 +00004236 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4237 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004238 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00004239 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00004240 case BuiltinType::Float: return FloatRank;
4241 case BuiltinType::Double: return DoubleRank;
4242 case BuiltinType::LongDouble: return LongDoubleRank;
4243 }
4244}
4245
Mike Stump1eb44332009-09-09 15:08:12 +00004246/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4247/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00004248/// 'typeDomain' is a real floating point or complex type.
4249/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00004250QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4251 QualType Domain) const {
4252 FloatingRank EltRank = getFloatingRank(Size);
4253 if (Domain->isComplexType()) {
4254 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00004255 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Narofff1448a02007-08-27 01:27:54 +00004256 case FloatRank: return FloatComplexTy;
4257 case DoubleRank: return DoubleComplexTy;
4258 case LongDoubleRank: return LongDoubleComplexTy;
4259 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004260 }
Chris Lattner1361b112008-04-06 23:58:54 +00004261
4262 assert(Domain->isRealFloatingType() && "Unknown domain!");
4263 switch (EltRank) {
Joey Gouly19dbb202013-01-23 11:56:20 +00004264 case HalfRank: return HalfTy;
Chris Lattner1361b112008-04-06 23:58:54 +00004265 case FloatRank: return FloatTy;
4266 case DoubleRank: return DoubleTy;
4267 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00004268 }
David Blaikie561d3ab2012-01-17 02:30:50 +00004269 llvm_unreachable("getFloatingRank(): illegal value for rank");
Reid Spencer5f016e22007-07-11 17:01:13 +00004270}
4271
Chris Lattner7cfeb082008-04-06 23:55:33 +00004272/// getFloatingTypeOrder - Compare the rank of the two specified floating
4273/// point types, ignoring the domain of the type (i.e. 'double' ==
4274/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004275/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004276int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00004277 FloatingRank LHSR = getFloatingRank(LHS);
4278 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004279
Chris Lattnera75cea32008-04-06 23:38:49 +00004280 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004281 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00004282 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004283 return 1;
4284 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004285}
4286
Chris Lattnerf52ab252008-04-06 22:59:24 +00004287/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4288/// routine will assert if passed a built-in type that isn't an integer or enum,
4289/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00004290unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00004291 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00004292
Chris Lattnerf52ab252008-04-06 22:59:24 +00004293 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004294 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00004295 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004296 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004297 case BuiltinType::Char_S:
4298 case BuiltinType::Char_U:
4299 case BuiltinType::SChar:
4300 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004301 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004302 case BuiltinType::Short:
4303 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004304 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004305 case BuiltinType::Int:
4306 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004307 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004308 case BuiltinType::Long:
4309 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004310 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004311 case BuiltinType::LongLong:
4312 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004313 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00004314 case BuiltinType::Int128:
4315 case BuiltinType::UInt128:
4316 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00004317 }
4318}
4319
Eli Friedman04e83572009-08-20 04:21:42 +00004320/// \brief Whether this is a promotable bitfield reference according
4321/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4322///
4323/// \returns the type this bit-field will promote to, or NULL if no
4324/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00004325QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00004326 if (E->isTypeDependent() || E->isValueDependent())
4327 return QualType();
4328
John McCall993f43f2013-05-06 21:39:12 +00004329 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman04e83572009-08-20 04:21:42 +00004330 if (!Field)
4331 return QualType();
4332
4333 QualType FT = Field->getType();
4334
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004335 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00004336 uint64_t IntSize = getTypeSize(IntTy);
4337 // GCC extension compatibility: if the bit-field size is less than or equal
4338 // to the size of int, it gets promoted no matter what its type is.
4339 // For instance, unsigned long bf : 4 gets promoted to signed int.
4340 if (BitWidth < IntSize)
4341 return IntTy;
4342
4343 if (BitWidth == IntSize)
4344 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4345
4346 // Types bigger than int are not subject to promotions, and therefore act
4347 // like the base type.
4348 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4349 // is ridiculous.
4350 return QualType();
4351}
4352
Eli Friedmana95d7572009-08-19 07:44:53 +00004353/// getPromotedIntegerType - Returns the type that Promotable will
4354/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4355/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00004356QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00004357 assert(!Promotable.isNull());
4358 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00004359 if (const EnumType *ET = Promotable->getAs<EnumType>())
4360 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00004361
4362 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4363 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4364 // (3.9.1) can be converted to a prvalue of the first of the following
4365 // types that can represent all the values of its underlying type:
4366 // int, unsigned int, long int, unsigned long int, long long int, or
4367 // unsigned long long int [...]
4368 // FIXME: Is there some better way to compute this?
4369 if (BT->getKind() == BuiltinType::WChar_S ||
4370 BT->getKind() == BuiltinType::WChar_U ||
4371 BT->getKind() == BuiltinType::Char16 ||
4372 BT->getKind() == BuiltinType::Char32) {
4373 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4374 uint64_t FromSize = getTypeSize(BT);
4375 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4376 LongLongTy, UnsignedLongLongTy };
4377 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4378 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4379 if (FromSize < ToSize ||
4380 (FromSize == ToSize &&
4381 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4382 return PromoteTypes[Idx];
4383 }
4384 llvm_unreachable("char type should fit into long long");
4385 }
4386 }
4387
4388 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00004389 if (Promotable->isSignedIntegerType())
4390 return IntTy;
Eli Friedman5b64e772012-11-15 01:21:59 +00004391 uint64_t PromotableSize = getIntWidth(Promotable);
4392 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedmana95d7572009-08-19 07:44:53 +00004393 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4394 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4395}
4396
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004397/// \brief Recurses in pointer/array types until it finds an objc retainable
4398/// type and returns its ownership.
4399Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4400 while (!T.isNull()) {
4401 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4402 return T.getObjCLifetime();
4403 if (T->isArrayType())
4404 T = getBaseElementType(T);
4405 else if (const PointerType *PT = T->getAs<PointerType>())
4406 T = PT->getPointeeType();
4407 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00004408 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004409 else
4410 break;
4411 }
4412
4413 return Qualifiers::OCL_None;
4414}
4415
Mike Stump1eb44332009-09-09 15:08:12 +00004416/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00004417/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004418/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004419int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00004420 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4421 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00004422 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004423
Chris Lattnerf52ab252008-04-06 22:59:24 +00004424 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4425 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00004426
Chris Lattner7cfeb082008-04-06 23:55:33 +00004427 unsigned LHSRank = getIntegerRank(LHSC);
4428 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00004429
Chris Lattner7cfeb082008-04-06 23:55:33 +00004430 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4431 if (LHSRank == RHSRank) return 0;
4432 return LHSRank > RHSRank ? 1 : -1;
4433 }
Mike Stump1eb44332009-09-09 15:08:12 +00004434
Chris Lattner7cfeb082008-04-06 23:55:33 +00004435 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4436 if (LHSUnsigned) {
4437 // If the unsigned [LHS] type is larger, return it.
4438 if (LHSRank >= RHSRank)
4439 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004440
Chris Lattner7cfeb082008-04-06 23:55:33 +00004441 // If the signed type can represent all values of the unsigned type, it
4442 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004443 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004444 return -1;
4445 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00004446
Chris Lattner7cfeb082008-04-06 23:55:33 +00004447 // If the unsigned [RHS] type is larger, return it.
4448 if (RHSRank >= LHSRank)
4449 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00004450
Chris Lattner7cfeb082008-04-06 23:55:33 +00004451 // If the signed type can represent all values of the unsigned type, it
4452 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004453 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004454 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004455}
Anders Carlsson71993dd2007-08-17 05:31:46 +00004456
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004457static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004458CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4459 DeclContext *DC, IdentifierInfo *Id) {
4460 SourceLocation Loc;
David Blaikie4e4d0842012-03-11 07:00:24 +00004461 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004462 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004463 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004464 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004465}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004466
Mike Stump1eb44332009-09-09 15:08:12 +00004467// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00004468QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00004469 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004470 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004471 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004472 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00004473 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004474
Anders Carlssonf06273f2007-11-19 00:25:30 +00004475 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00004476
Anders Carlsson71993dd2007-08-17 05:31:46 +00004477 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00004478 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00004479 // int flags;
4480 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00004481 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00004482 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00004483 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00004484 FieldTypes[3] = LongTy;
4485
Anders Carlsson71993dd2007-08-17 05:31:46 +00004486 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00004487 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00004488 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004489 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00004490 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00004491 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00004492 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004493 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004494 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004495 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004496 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00004497 }
4498
Douglas Gregor838db382010-02-11 01:19:42 +00004499 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00004500 }
Mike Stump1eb44332009-09-09 15:08:12 +00004501
Anders Carlsson71993dd2007-08-17 05:31:46 +00004502 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00004503}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004504
Fariborz Jahanianf7992132013-01-04 18:45:40 +00004505QualType ASTContext::getObjCSuperType() const {
4506 if (ObjCSuperType.isNull()) {
4507 RecordDecl *ObjCSuperTypeDecl =
4508 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4509 TUDecl->addDecl(ObjCSuperTypeDecl);
4510 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4511 }
4512 return ObjCSuperType;
4513}
4514
Douglas Gregor319ac892009-04-23 22:29:11 +00004515void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004516 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00004517 assert(Rec && "Invalid CFConstantStringType");
4518 CFConstantStringTypeDecl = Rec->getDecl();
4519}
4520
Jay Foad4ba2a172011-01-12 09:06:06 +00004521QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00004522 if (BlockDescriptorType)
4523 return getTagDeclType(BlockDescriptorType);
4524
4525 RecordDecl *T;
4526 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004527 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004528 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00004529 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004530
4531 QualType FieldTypes[] = {
4532 UnsignedLongTy,
4533 UnsignedLongTy,
4534 };
4535
4536 const char *FieldNames[] = {
4537 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00004538 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00004539 };
4540
4541 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004542 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00004543 SourceLocation(),
4544 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004545 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00004546 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004547 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004548 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004549 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00004550 T->addDecl(Field);
4551 }
4552
Douglas Gregor838db382010-02-11 01:19:42 +00004553 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004554
4555 BlockDescriptorType = T;
4556
4557 return getTagDeclType(BlockDescriptorType);
4558}
4559
Jay Foad4ba2a172011-01-12 09:06:06 +00004560QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00004561 if (BlockDescriptorExtendedType)
4562 return getTagDeclType(BlockDescriptorExtendedType);
4563
4564 RecordDecl *T;
4565 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004566 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004567 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00004568 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004569
4570 QualType FieldTypes[] = {
4571 UnsignedLongTy,
4572 UnsignedLongTy,
4573 getPointerType(VoidPtrTy),
4574 getPointerType(VoidPtrTy)
4575 };
4576
4577 const char *FieldNames[] = {
4578 "reserved",
4579 "Size",
4580 "CopyFuncPtr",
4581 "DestroyFuncPtr"
4582 };
4583
4584 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004585 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00004586 SourceLocation(),
4587 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004588 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00004589 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004590 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004591 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004592 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00004593 T->addDecl(Field);
4594 }
4595
Douglas Gregor838db382010-02-11 01:19:42 +00004596 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004597
4598 BlockDescriptorExtendedType = T;
4599
4600 return getTagDeclType(BlockDescriptorExtendedType);
4601}
4602
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004603/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4604/// requires copy/dispose. Note that this must match the logic
4605/// in buildByrefHelpers.
4606bool ASTContext::BlockRequiresCopying(QualType Ty,
4607 const VarDecl *D) {
4608 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4609 const Expr *copyExpr = getBlockVarCopyInits(D);
4610 if (!copyExpr && record->hasTrivialDestructor()) return false;
4611
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004612 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00004613 }
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004614
4615 if (!Ty->isObjCRetainableType()) return false;
4616
4617 Qualifiers qs = Ty.getQualifiers();
4618
4619 // If we have lifetime, that dominates.
4620 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4621 assert(getLangOpts().ObjCAutoRefCount);
4622
4623 switch (lifetime) {
4624 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4625
4626 // These are just bits as far as the runtime is concerned.
4627 case Qualifiers::OCL_ExplicitNone:
4628 case Qualifiers::OCL_Autoreleasing:
4629 return false;
4630
4631 // Tell the runtime that this is ARC __weak, called by the
4632 // byref routines.
4633 case Qualifiers::OCL_Weak:
4634 // ARC __strong __block variables need to be retained.
4635 case Qualifiers::OCL_Strong:
4636 return true;
4637 }
4638 llvm_unreachable("fell out of lifetime switch!");
4639 }
4640 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4641 Ty->isObjCObjectPointerType());
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004642}
4643
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004644bool ASTContext::getByrefLifetime(QualType Ty,
4645 Qualifiers::ObjCLifetime &LifeTime,
4646 bool &HasByrefExtendedLayout) const {
4647
4648 if (!getLangOpts().ObjC1 ||
4649 getLangOpts().getGC() != LangOptions::NonGC)
4650 return false;
4651
4652 HasByrefExtendedLayout = false;
Fariborz Jahanian34db84f2012-12-11 19:58:01 +00004653 if (Ty->isRecordType()) {
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004654 HasByrefExtendedLayout = true;
4655 LifeTime = Qualifiers::OCL_None;
4656 }
4657 else if (getLangOpts().ObjCAutoRefCount)
4658 LifeTime = Ty.getObjCLifetime();
4659 // MRR.
4660 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4661 LifeTime = Qualifiers::OCL_ExplicitNone;
4662 else
4663 LifeTime = Qualifiers::OCL_None;
4664 return true;
4665}
4666
Douglas Gregore97179c2011-09-08 01:46:34 +00004667TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4668 if (!ObjCInstanceTypeDecl)
4669 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4670 getTranslationUnitDecl(),
4671 SourceLocation(),
4672 SourceLocation(),
4673 &Idents.get("instancetype"),
4674 getTrivialTypeSourceInfo(getObjCIdType()));
4675 return ObjCInstanceTypeDecl;
4676}
4677
Anders Carlssone8c49532007-10-29 06:33:42 +00004678// This returns true if a type has been typedefed to BOOL:
4679// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00004680static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00004681 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00004682 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4683 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00004684
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004685 return false;
4686}
4687
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004688/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004689/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00004690CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00004691 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4692 return CharUnits::Zero();
4693
Ken Dyck199c3d62010-01-11 17:06:35 +00004694 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004695
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004696 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004697 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004698 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004699 // Treat arrays as pointers, since that's how they're passed in.
4700 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004701 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004702 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004703}
4704
4705static inline
4706std::string charUnitsToString(const CharUnits &CU) {
4707 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004708}
4709
John McCall6b5a61b2011-02-07 10:33:21 +00004710/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004711/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004712std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4713 std::string S;
4714
David Chisnall5e530af2009-11-17 19:33:30 +00004715 const BlockDecl *Decl = Expr->getBlockDecl();
4716 QualType BlockTy =
4717 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4718 // Encode result type.
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004719 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004720 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4721 BlockTy->getAs<FunctionType>()->getResultType(),
4722 S, true /*Extended*/);
4723 else
4724 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4725 S);
David Chisnall5e530af2009-11-17 19:33:30 +00004726 // Compute size of all parameters.
4727 // Start with computing size of a pointer in number of bytes.
4728 // FIXME: There might(should) be a better way of doing this computation!
4729 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004730 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4731 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004732 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004733 E = Decl->param_end(); PI != E; ++PI) {
4734 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004735 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahanian075a5432012-06-30 00:48:59 +00004736 if (sz.isZero())
4737 continue;
Ken Dyck199c3d62010-01-11 17:06:35 +00004738 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004739 ParmOffset += sz;
4740 }
4741 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004742 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004743 // Block pointer and offset.
4744 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004745
4746 // Argument types.
4747 ParmOffset = PtrSize;
4748 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4749 Decl->param_end(); PI != E; ++PI) {
4750 ParmVarDecl *PVDecl = *PI;
4751 QualType PType = PVDecl->getOriginalType();
4752 if (const ArrayType *AT =
4753 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4754 // Use array's original type only if it has known number of
4755 // elements.
4756 if (!isa<ConstantArrayType>(AT))
4757 PType = PVDecl->getType();
4758 } else if (PType->isFunctionType())
4759 PType = PVDecl->getType();
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004760 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004761 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4762 S, true /*Extended*/);
4763 else
4764 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004765 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004766 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004767 }
John McCall6b5a61b2011-02-07 10:33:21 +00004768
4769 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004770}
4771
Douglas Gregorf968d832011-05-27 01:19:52 +00004772bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004773 std::string& S) {
4774 // Encode result type.
4775 getObjCEncodingForType(Decl->getResultType(), S);
4776 CharUnits ParmOffset;
4777 // Compute size of all parameters.
4778 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4779 E = Decl->param_end(); PI != E; ++PI) {
4780 QualType PType = (*PI)->getType();
4781 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004782 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004783 continue;
4784
David Chisnall5389f482010-12-30 14:05:53 +00004785 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004786 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004787 ParmOffset += sz;
4788 }
4789 S += charUnitsToString(ParmOffset);
4790 ParmOffset = CharUnits::Zero();
4791
4792 // Argument types.
4793 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4794 E = Decl->param_end(); PI != E; ++PI) {
4795 ParmVarDecl *PVDecl = *PI;
4796 QualType PType = PVDecl->getOriginalType();
4797 if (const ArrayType *AT =
4798 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4799 // Use array's original type only if it has known number of
4800 // elements.
4801 if (!isa<ConstantArrayType>(AT))
4802 PType = PVDecl->getType();
4803 } else if (PType->isFunctionType())
4804 PType = PVDecl->getType();
4805 getObjCEncodingForType(PType, S);
4806 S += charUnitsToString(ParmOffset);
4807 ParmOffset += getObjCEncodingTypeSize(PType);
4808 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004809
4810 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004811}
4812
Bob Wilsondc8dab62011-11-30 01:57:58 +00004813/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4814/// method parameter or return type. If Extended, include class names and
4815/// block object types.
4816void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4817 QualType T, std::string& S,
4818 bool Extended) const {
4819 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4820 getObjCEncodingForTypeQualifier(QT, S);
4821 // Encode parameter type.
4822 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4823 true /*OutermostType*/,
4824 false /*EncodingProperty*/,
4825 false /*StructField*/,
4826 Extended /*EncodeBlockParameters*/,
4827 Extended /*EncodeClassNames*/);
4828}
4829
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004830/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004831/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004832bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004833 std::string& S,
4834 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004835 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004836 // Encode return type.
4837 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4838 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004839 // Compute size of all parameters.
4840 // Start with computing size of a pointer in number of bytes.
4841 // FIXME: There might(should) be a better way of doing this computation!
4842 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004843 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004844 // The first two arguments (self and _cmd) are pointers; account for
4845 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004846 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004847 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004848 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004849 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004850 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004851 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004852 continue;
4853
Ken Dyck199c3d62010-01-11 17:06:35 +00004854 assert (sz.isPositive() &&
4855 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004856 ParmOffset += sz;
4857 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004858 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004859 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004860 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004861
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004862 // Argument types.
4863 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004864 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004865 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004866 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004867 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004868 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004869 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4870 // Use array's original type only if it has known number of
4871 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004872 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004873 PType = PVDecl->getType();
4874 } else if (PType->isFunctionType())
4875 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004876 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4877 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004878 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004879 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004880 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004881
4882 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004883}
4884
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004885/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004886/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004887/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4888/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004889/// Property attributes are stored as a comma-delimited C string. The simple
4890/// attributes readonly and bycopy are encoded as single characters. The
4891/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4892/// encoded as single characters, followed by an identifier. Property types
4893/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004894/// these attributes are defined by the following enumeration:
4895/// @code
4896/// enum PropertyAttributes {
4897/// kPropertyReadOnly = 'R', // property is read-only.
4898/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4899/// kPropertyByref = '&', // property is a reference to the value last assigned
4900/// kPropertyDynamic = 'D', // property is dynamic
4901/// kPropertyGetter = 'G', // followed by getter selector name
4902/// kPropertySetter = 'S', // followed by setter selector name
4903/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson0d4cb852012-03-22 17:48:02 +00004904/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004905/// kPropertyWeak = 'W' // 'weak' property
4906/// kPropertyStrong = 'P' // property GC'able
4907/// kPropertyNonAtomic = 'N' // property non-atomic
4908/// };
4909/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004910void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004911 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004912 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004913 // Collect information from the property implementation decl(s).
4914 bool Dynamic = false;
4915 ObjCPropertyImplDecl *SynthesizePID = 0;
4916
4917 // FIXME: Duplicated code due to poor abstraction.
4918 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004919 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004920 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4921 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004922 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004923 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004924 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004925 if (PID->getPropertyDecl() == PD) {
4926 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4927 Dynamic = true;
4928 } else {
4929 SynthesizePID = PID;
4930 }
4931 }
4932 }
4933 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004934 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004935 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004936 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004937 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004938 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004939 if (PID->getPropertyDecl() == PD) {
4940 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4941 Dynamic = true;
4942 } else {
4943 SynthesizePID = PID;
4944 }
4945 }
Mike Stump1eb44332009-09-09 15:08:12 +00004946 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004947 }
4948 }
4949
4950 // FIXME: This is not very efficient.
4951 S = "T";
4952
4953 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004954 // GCC has some special rules regarding encoding of properties which
4955 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004956 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004957 true /* outermost type */,
4958 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004959
4960 if (PD->isReadOnly()) {
4961 S += ",R";
Nico Weberd7ceab32013-05-08 23:47:40 +00004962 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
4963 S += ",C";
4964 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
4965 S += ",&";
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004966 } else {
4967 switch (PD->getSetterKind()) {
4968 case ObjCPropertyDecl::Assign: break;
4969 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004970 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004971 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004972 }
4973 }
4974
4975 // It really isn't clear at all what this means, since properties
4976 // are "dynamic by default".
4977 if (Dynamic)
4978 S += ",D";
4979
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004980 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4981 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004982
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004983 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4984 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004985 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004986 }
4987
4988 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4989 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004990 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004991 }
4992
4993 if (SynthesizePID) {
4994 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4995 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004996 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004997 }
4998
4999 // FIXME: OBJCGC: weak & strong
5000}
5001
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005002/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00005003/// Another legacy compatibility encoding: 32-bit longs are encoded as
5004/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005005/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5006///
5007void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00005008 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00005009 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00005010 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005011 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00005012 else
Jay Foad4ba2a172011-01-12 09:06:06 +00005013 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005014 PointeeTy = IntTy;
5015 }
5016 }
5017}
5018
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005019void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00005020 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005021 // We follow the behavior of gcc, expanding structures which are
5022 // directly pointed to, and expanding embedded structures. Note that
5023 // these rules are sufficient to prevent recursive encoding of the
5024 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00005025 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00005026 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005027}
5028
John McCall3624e9e2012-12-20 02:45:14 +00005029static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5030 BuiltinType::Kind kind) {
5031 switch (kind) {
David Chisnall64fd7e82010-06-04 01:10:52 +00005032 case BuiltinType::Void: return 'v';
5033 case BuiltinType::Bool: return 'B';
5034 case BuiltinType::Char_U:
5035 case BuiltinType::UChar: return 'C';
John McCall3624e9e2012-12-20 02:45:14 +00005036 case BuiltinType::Char16:
David Chisnall64fd7e82010-06-04 01:10:52 +00005037 case BuiltinType::UShort: return 'S';
John McCall3624e9e2012-12-20 02:45:14 +00005038 case BuiltinType::Char32:
David Chisnall64fd7e82010-06-04 01:10:52 +00005039 case BuiltinType::UInt: return 'I';
5040 case BuiltinType::ULong:
John McCall3624e9e2012-12-20 02:45:14 +00005041 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00005042 case BuiltinType::UInt128: return 'T';
5043 case BuiltinType::ULongLong: return 'Q';
5044 case BuiltinType::Char_S:
5045 case BuiltinType::SChar: return 'c';
5046 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00005047 case BuiltinType::WChar_S:
5048 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00005049 case BuiltinType::Int: return 'i';
5050 case BuiltinType::Long:
John McCall3624e9e2012-12-20 02:45:14 +00005051 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00005052 case BuiltinType::LongLong: return 'q';
5053 case BuiltinType::Int128: return 't';
5054 case BuiltinType::Float: return 'f';
5055 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00005056 case BuiltinType::LongDouble: return 'D';
John McCall3624e9e2012-12-20 02:45:14 +00005057 case BuiltinType::NullPtr: return '*'; // like char*
5058
5059 case BuiltinType::Half:
5060 // FIXME: potentially need @encodes for these!
5061 return ' ';
5062
5063 case BuiltinType::ObjCId:
5064 case BuiltinType::ObjCClass:
5065 case BuiltinType::ObjCSel:
5066 llvm_unreachable("@encoding ObjC primitive type");
5067
5068 // OpenCL and placeholder types don't need @encodings.
5069 case BuiltinType::OCLImage1d:
5070 case BuiltinType::OCLImage1dArray:
5071 case BuiltinType::OCLImage1dBuffer:
5072 case BuiltinType::OCLImage2d:
5073 case BuiltinType::OCLImage2dArray:
5074 case BuiltinType::OCLImage3d:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005075 case BuiltinType::OCLEvent:
Guy Benyei21f18c42013-02-07 10:55:47 +00005076 case BuiltinType::OCLSampler:
John McCall3624e9e2012-12-20 02:45:14 +00005077 case BuiltinType::Dependent:
5078#define BUILTIN_TYPE(KIND, ID)
5079#define PLACEHOLDER_TYPE(KIND, ID) \
5080 case BuiltinType::KIND:
5081#include "clang/AST/BuiltinTypes.def"
5082 llvm_unreachable("invalid builtin type for @encode");
David Chisnall64fd7e82010-06-04 01:10:52 +00005083 }
David Blaikie719e53f2013-01-09 17:48:41 +00005084 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnall64fd7e82010-06-04 01:10:52 +00005085}
5086
Douglas Gregor5471bc82011-09-08 17:18:35 +00005087static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5088 EnumDecl *Enum = ET->getDecl();
5089
5090 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5091 if (!Enum->isFixed())
5092 return 'i';
5093
5094 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall3624e9e2012-12-20 02:45:14 +00005095 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5096 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor5471bc82011-09-08 17:18:35 +00005097}
5098
Jay Foad4ba2a172011-01-12 09:06:06 +00005099static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00005100 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005101 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00005102 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00005103 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5104 // The GNU runtime requires more information; bitfields are encoded as b,
5105 // then the offset (in bits) of the first element, then the type of the
5106 // bitfield, then the size in bits. For example, in this structure:
5107 //
5108 // struct
5109 // {
5110 // int integer;
5111 // int flags:2;
5112 // };
5113 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5114 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5115 // information is not especially sensible, but we're stuck with it for
5116 // compatibility with GCC, although providing it breaks anything that
5117 // actually uses runtime introspection and wants to work on both runtimes...
John McCall260611a2012-06-20 06:18:46 +00005118 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnall64fd7e82010-06-04 01:10:52 +00005119 const RecordDecl *RD = FD->getParent();
5120 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00005121 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00005122 if (const EnumType *ET = T->getAs<EnumType>())
5123 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall3624e9e2012-12-20 02:45:14 +00005124 else {
5125 const BuiltinType *BT = T->castAs<BuiltinType>();
5126 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5127 }
David Chisnall64fd7e82010-06-04 01:10:52 +00005128 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005129 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00005130}
5131
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00005132// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005133void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5134 bool ExpandPointedToStructures,
5135 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00005136 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00005137 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005138 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00005139 bool StructField,
5140 bool EncodeBlockParameters,
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005141 bool EncodeClassNames,
5142 bool EncodePointerToObjCTypedef) const {
John McCall3624e9e2012-12-20 02:45:14 +00005143 CanQualType CT = getCanonicalType(T);
5144 switch (CT->getTypeClass()) {
5145 case Type::Builtin:
5146 case Type::Enum:
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005147 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00005148 return EncodeBitField(this, S, T, FD);
John McCall3624e9e2012-12-20 02:45:14 +00005149 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5150 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5151 else
5152 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005153 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005154
John McCall3624e9e2012-12-20 02:45:14 +00005155 case Type::Complex: {
5156 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005157 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00005158 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005159 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005160 return;
5161 }
John McCall3624e9e2012-12-20 02:45:14 +00005162
5163 case Type::Atomic: {
5164 const AtomicType *AT = T->castAs<AtomicType>();
5165 S += 'A';
5166 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5167 false, false);
5168 return;
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00005169 }
John McCall3624e9e2012-12-20 02:45:14 +00005170
5171 // encoding for pointer or reference types.
5172 case Type::Pointer:
5173 case Type::LValueReference:
5174 case Type::RValueReference: {
5175 QualType PointeeTy;
5176 if (isa<PointerType>(CT)) {
5177 const PointerType *PT = T->castAs<PointerType>();
5178 if (PT->isObjCSelType()) {
5179 S += ':';
5180 return;
5181 }
5182 PointeeTy = PT->getPointeeType();
5183 } else {
5184 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5185 }
5186
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005187 bool isReadOnly = false;
5188 // For historical/compatibility reasons, the read-only qualifier of the
5189 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5190 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00005191 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00005192 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005193 if (OutermostType && T.isConstQualified()) {
5194 isReadOnly = true;
5195 S += 'r';
5196 }
Mike Stump9fdbab32009-07-31 02:02:20 +00005197 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005198 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00005199 while (P->getAs<PointerType>())
5200 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005201 if (P.isConstQualified()) {
5202 isReadOnly = true;
5203 S += 'r';
5204 }
5205 }
5206 if (isReadOnly) {
5207 // Another legacy compatibility encoding. Some ObjC qualifier and type
5208 // combinations need to be rearranged.
5209 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00005210 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00005211 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005212 }
Mike Stump1eb44332009-09-09 15:08:12 +00005213
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005214 if (PointeeTy->isCharType()) {
5215 // char pointer types should be encoded as '*' unless it is a
5216 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00005217 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005218 S += '*';
5219 return;
5220 }
Ted Kremenek6217b802009-07-29 21:53:49 +00005221 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00005222 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5223 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5224 S += '#';
5225 return;
5226 }
5227 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5228 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5229 S += '@';
5230 return;
5231 }
5232 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005233 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005234 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005235 getLegacyIntegralTypeEncoding(PointeeTy);
5236
Mike Stump1eb44332009-09-09 15:08:12 +00005237 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005238 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005239 return;
5240 }
John McCall3624e9e2012-12-20 02:45:14 +00005241
5242 case Type::ConstantArray:
5243 case Type::IncompleteArray:
5244 case Type::VariableArray: {
5245 const ArrayType *AT = cast<ArrayType>(CT);
5246
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005247 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00005248 // Incomplete arrays are encoded as a pointer to the array element.
5249 S += '^';
5250
Mike Stump1eb44332009-09-09 15:08:12 +00005251 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005252 false, ExpandStructures, FD);
5253 } else {
5254 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00005255
Fariborz Jahanian48eff6c2013-06-04 16:04:37 +00005256 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5257 S += llvm::utostr(CAT->getSize().getZExtValue());
5258 else {
Anders Carlsson559a8332009-02-22 01:38:57 +00005259 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005260 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5261 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00005262 S += '0';
5263 }
Mike Stump1eb44332009-09-09 15:08:12 +00005264
5265 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005266 false, ExpandStructures, FD);
5267 S += ']';
5268 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005269 return;
5270 }
Mike Stump1eb44332009-09-09 15:08:12 +00005271
John McCall3624e9e2012-12-20 02:45:14 +00005272 case Type::FunctionNoProto:
5273 case Type::FunctionProto:
Anders Carlssonc0a87b72007-10-30 00:06:20 +00005274 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005275 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005276
John McCall3624e9e2012-12-20 02:45:14 +00005277 case Type::Record: {
5278 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005279 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005280 // Anonymous structures print as '?'
5281 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5282 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005283 if (ClassTemplateSpecializationDecl *Spec
5284 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5285 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer5eada842013-02-22 15:46:01 +00005286 llvm::raw_string_ostream OS(S);
5287 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor910f8002010-11-07 23:05:16 +00005288 TemplateArgs.data(),
5289 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00005290 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005291 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005292 } else {
5293 S += '?';
5294 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00005295 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005296 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005297 if (!RDecl->isUnion()) {
5298 getObjCEncodingForStructureImpl(RDecl, S, FD);
5299 } else {
5300 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5301 FieldEnd = RDecl->field_end();
5302 Field != FieldEnd; ++Field) {
5303 if (FD) {
5304 S += '"';
5305 S += Field->getNameAsString();
5306 S += '"';
5307 }
Mike Stump1eb44332009-09-09 15:08:12 +00005308
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005309 // Special case bit-fields.
5310 if (Field->isBitField()) {
5311 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie581deb32012-06-06 20:45:41 +00005312 *Field);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005313 } else {
5314 QualType qt = Field->getType();
5315 getLegacyIntegralTypeEncoding(qt);
5316 getObjCEncodingForTypeImpl(qt, S, false, true,
5317 FD, /*OutermostType*/false,
5318 /*EncodingProperty*/false,
5319 /*StructField*/true);
5320 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005321 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005322 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00005323 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005324 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005325 return;
5326 }
Mike Stump1eb44332009-09-09 15:08:12 +00005327
John McCall3624e9e2012-12-20 02:45:14 +00005328 case Type::BlockPointer: {
5329 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff21a98b12009-02-02 18:24:29 +00005330 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00005331 if (EncodeBlockParameters) {
John McCall3624e9e2012-12-20 02:45:14 +00005332 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilsondc8dab62011-11-30 01:57:58 +00005333
5334 S += '<';
5335 // Block return type
5336 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5337 ExpandPointedToStructures, ExpandStructures,
5338 FD,
5339 false /* OutermostType */,
5340 EncodingProperty,
5341 false /* StructField */,
5342 EncodeBlockParameters,
5343 EncodeClassNames);
5344 // Block self
5345 S += "@?";
5346 // Block parameters
5347 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5348 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5349 E = FPT->arg_type_end(); I && (I != E); ++I) {
5350 getObjCEncodingForTypeImpl(*I, S,
5351 ExpandPointedToStructures,
5352 ExpandStructures,
5353 FD,
5354 false /* OutermostType */,
5355 EncodingProperty,
5356 false /* StructField */,
5357 EncodeBlockParameters,
5358 EncodeClassNames);
5359 }
5360 }
5361 S += '>';
5362 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005363 return;
5364 }
Mike Stump1eb44332009-09-09 15:08:12 +00005365
John McCall3624e9e2012-12-20 02:45:14 +00005366 case Type::ObjCObject:
5367 case Type::ObjCInterface: {
5368 // Ignore protocol qualifiers when mangling at this level.
5369 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCallc12c5bb2010-05-15 11:32:37 +00005370
John McCall3624e9e2012-12-20 02:45:14 +00005371 // The assumption seems to be that this assert will succeed
5372 // because nested levels will have filtered out 'id' and 'Class'.
5373 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005374 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00005375 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005376 S += '{';
5377 const IdentifierInfo *II = OI->getIdentifier();
5378 S += II->getName();
5379 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00005380 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005381 DeepCollectObjCIvars(OI, true, Ivars);
5382 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00005383 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005384 if (Field->isBitField())
5385 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005386 else
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005387 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5388 false, false, false, false, false,
5389 EncodePointerToObjCTypedef);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005390 }
5391 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005392 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005393 }
Mike Stump1eb44332009-09-09 15:08:12 +00005394
John McCall3624e9e2012-12-20 02:45:14 +00005395 case Type::ObjCObjectPointer: {
5396 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00005397 if (OPT->isObjCIdType()) {
5398 S += '@';
5399 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005400 }
Mike Stump1eb44332009-09-09 15:08:12 +00005401
Steve Naroff27d20a22009-10-28 22:03:49 +00005402 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5403 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5404 // Since this is a binary compatibility issue, need to consult with runtime
5405 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00005406 S += '#';
5407 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005408 }
Mike Stump1eb44332009-09-09 15:08:12 +00005409
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005410 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005411 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00005412 ExpandPointedToStructures,
5413 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00005414 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00005415 // Note that we do extended encoding of protocol qualifer list
5416 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00005417 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005418 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5419 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00005420 S += '<';
5421 S += (*I)->getNameAsString();
5422 S += '>';
5423 }
5424 S += '"';
5425 }
5426 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005427 }
Mike Stump1eb44332009-09-09 15:08:12 +00005428
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005429 QualType PointeeTy = OPT->getPointeeType();
5430 if (!EncodingProperty &&
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005431 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5432 !EncodePointerToObjCTypedef) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005433 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00005434 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005435 // {...};
5436 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00005437 getObjCEncodingForTypeImpl(PointeeTy, S,
5438 false, ExpandPointedToStructures,
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005439 NULL,
5440 false, false, false, false, false,
5441 /*EncodePointerToObjCTypedef*/true);
Steve Naroff14108da2009-07-10 23:34:53 +00005442 return;
5443 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005444
5445 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00005446 if (OPT->getInterfaceDecl() &&
5447 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005448 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00005449 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005450 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5451 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005452 S += '<';
5453 S += (*I)->getNameAsString();
5454 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00005455 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005456 S += '"';
5457 }
5458 return;
5459 }
Mike Stump1eb44332009-09-09 15:08:12 +00005460
John McCall532ec7b2010-05-17 23:56:34 +00005461 // gcc just blithely ignores member pointers.
John McCall3624e9e2012-12-20 02:45:14 +00005462 // FIXME: we shoul do better than that. 'M' is available.
5463 case Type::MemberPointer:
John McCall532ec7b2010-05-17 23:56:34 +00005464 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005465
John McCall3624e9e2012-12-20 02:45:14 +00005466 case Type::Vector:
5467 case Type::ExtVector:
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005468 // This matches gcc's encoding, even though technically it is
5469 // insufficient.
5470 // FIXME. We should do a better job than gcc.
5471 return;
John McCall3624e9e2012-12-20 02:45:14 +00005472
Richard Smithdc7a4f52013-04-30 13:56:41 +00005473 case Type::Auto:
5474 // We could see an undeduced auto type here during error recovery.
5475 // Just ignore it.
5476 return;
5477
John McCall3624e9e2012-12-20 02:45:14 +00005478#define ABSTRACT_TYPE(KIND, BASE)
5479#define TYPE(KIND, BASE)
5480#define DEPENDENT_TYPE(KIND, BASE) \
5481 case Type::KIND:
5482#define NON_CANONICAL_TYPE(KIND, BASE) \
5483 case Type::KIND:
5484#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5485 case Type::KIND:
5486#include "clang/AST/TypeNodes.def"
5487 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005488 }
John McCall3624e9e2012-12-20 02:45:14 +00005489 llvm_unreachable("bad type kind!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005490}
5491
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005492void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5493 std::string &S,
5494 const FieldDecl *FD,
5495 bool includeVBases) const {
5496 assert(RDecl && "Expected non-null RecordDecl");
5497 assert(!RDecl->isUnion() && "Should not be called for unions");
5498 if (!RDecl->getDefinition())
5499 return;
5500
5501 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5502 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5503 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5504
5505 if (CXXRec) {
5506 for (CXXRecordDecl::base_class_iterator
5507 BI = CXXRec->bases_begin(),
5508 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5509 if (!BI->isVirtual()) {
5510 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005511 if (base->isEmpty())
5512 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005513 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005514 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5515 std::make_pair(offs, base));
5516 }
5517 }
5518 }
5519
5520 unsigned i = 0;
5521 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5522 FieldEnd = RDecl->field_end();
5523 Field != FieldEnd; ++Field, ++i) {
5524 uint64_t offs = layout.getFieldOffset(i);
5525 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie581deb32012-06-06 20:45:41 +00005526 std::make_pair(offs, *Field));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005527 }
5528
5529 if (CXXRec && includeVBases) {
5530 for (CXXRecordDecl::base_class_iterator
5531 BI = CXXRec->vbases_begin(),
5532 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5533 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005534 if (base->isEmpty())
5535 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005536 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00005537 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5538 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5539 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005540 }
5541 }
5542
5543 CharUnits size;
5544 if (CXXRec) {
5545 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5546 } else {
5547 size = layout.getSize();
5548 }
5549
5550 uint64_t CurOffs = 0;
5551 std::multimap<uint64_t, NamedDecl *>::iterator
5552 CurLayObj = FieldOrBaseOffsets.begin();
5553
Douglas Gregor58db7a52012-04-27 22:30:01 +00005554 if (CXXRec && CXXRec->isDynamicClass() &&
5555 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005556 if (FD) {
5557 S += "\"_vptr$";
5558 std::string recname = CXXRec->getNameAsString();
5559 if (recname.empty()) recname = "?";
5560 S += recname;
5561 S += '"';
5562 }
5563 S += "^^?";
5564 CurOffs += getTypeSize(VoidPtrTy);
5565 }
5566
5567 if (!RDecl->hasFlexibleArrayMember()) {
5568 // Mark the end of the structure.
5569 uint64_t offs = toBits(size);
5570 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5571 std::make_pair(offs, (NamedDecl*)0));
5572 }
5573
5574 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5575 assert(CurOffs <= CurLayObj->first);
5576
5577 if (CurOffs < CurLayObj->first) {
5578 uint64_t padding = CurLayObj->first - CurOffs;
5579 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5580 // packing/alignment of members is different that normal, in which case
5581 // the encoding will be out-of-sync with the real layout.
5582 // If the runtime switches to just consider the size of types without
5583 // taking into account alignment, we could make padding explicit in the
5584 // encoding (e.g. using arrays of chars). The encoding strings would be
5585 // longer then though.
5586 CurOffs += padding;
5587 }
5588
5589 NamedDecl *dcl = CurLayObj->second;
5590 if (dcl == 0)
5591 break; // reached end of structure.
5592
5593 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5594 // We expand the bases without their virtual bases since those are going
5595 // in the initial structure. Note that this differs from gcc which
5596 // expands virtual bases each time one is encountered in the hierarchy,
5597 // making the encoding type bigger than it really is.
5598 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005599 assert(!base->isEmpty());
5600 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005601 } else {
5602 FieldDecl *field = cast<FieldDecl>(dcl);
5603 if (FD) {
5604 S += '"';
5605 S += field->getNameAsString();
5606 S += '"';
5607 }
5608
5609 if (field->isBitField()) {
5610 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005611 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005612 } else {
5613 QualType qt = field->getType();
5614 getLegacyIntegralTypeEncoding(qt);
5615 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5616 /*OutermostType*/false,
5617 /*EncodingProperty*/false,
5618 /*StructField*/true);
5619 CurOffs += getTypeSize(field->getType());
5620 }
5621 }
5622 }
5623}
5624
Mike Stump1eb44332009-09-09 15:08:12 +00005625void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00005626 std::string& S) const {
5627 if (QT & Decl::OBJC_TQ_In)
5628 S += 'n';
5629 if (QT & Decl::OBJC_TQ_Inout)
5630 S += 'N';
5631 if (QT & Decl::OBJC_TQ_Out)
5632 S += 'o';
5633 if (QT & Decl::OBJC_TQ_Bycopy)
5634 S += 'O';
5635 if (QT & Decl::OBJC_TQ_Byref)
5636 S += 'R';
5637 if (QT & Decl::OBJC_TQ_Oneway)
5638 S += 'V';
5639}
5640
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00005641TypedefDecl *ASTContext::getObjCIdDecl() const {
5642 if (!ObjCIdDecl) {
5643 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5644 T = getObjCObjectPointerType(T);
5645 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5646 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5647 getTranslationUnitDecl(),
5648 SourceLocation(), SourceLocation(),
5649 &Idents.get("id"), IdInfo);
5650 }
5651
5652 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00005653}
5654
Douglas Gregor7a27ea52011-08-12 06:17:30 +00005655TypedefDecl *ASTContext::getObjCSelDecl() const {
5656 if (!ObjCSelDecl) {
5657 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5658 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5659 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5660 getTranslationUnitDecl(),
5661 SourceLocation(), SourceLocation(),
5662 &Idents.get("SEL"), SelInfo);
5663 }
5664 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00005665}
5666
Douglas Gregor79d67262011-08-12 05:59:41 +00005667TypedefDecl *ASTContext::getObjCClassDecl() const {
5668 if (!ObjCClassDecl) {
5669 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5670 T = getObjCObjectPointerType(T);
5671 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5672 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5673 getTranslationUnitDecl(),
5674 SourceLocation(), SourceLocation(),
5675 &Idents.get("Class"), ClassInfo);
5676 }
5677
5678 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00005679}
5680
Douglas Gregora6ea10e2012-01-17 18:09:05 +00005681ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5682 if (!ObjCProtocolClassDecl) {
5683 ObjCProtocolClassDecl
5684 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5685 SourceLocation(),
5686 &Idents.get("Protocol"),
5687 /*PrevDecl=*/0,
5688 SourceLocation(), true);
5689 }
5690
5691 return ObjCProtocolClassDecl;
5692}
5693
Meador Ingec5613b22012-06-16 03:34:49 +00005694//===----------------------------------------------------------------------===//
5695// __builtin_va_list Construction Functions
5696//===----------------------------------------------------------------------===//
5697
5698static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5699 // typedef char* __builtin_va_list;
5700 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5701 TypeSourceInfo *TInfo
5702 = Context->getTrivialTypeSourceInfo(CharPtrType);
5703
5704 TypedefDecl *VaListTypeDecl
5705 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5706 Context->getTranslationUnitDecl(),
5707 SourceLocation(), SourceLocation(),
5708 &Context->Idents.get("__builtin_va_list"),
5709 TInfo);
5710 return VaListTypeDecl;
5711}
5712
5713static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5714 // typedef void* __builtin_va_list;
5715 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5716 TypeSourceInfo *TInfo
5717 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5718
5719 TypedefDecl *VaListTypeDecl
5720 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5721 Context->getTranslationUnitDecl(),
5722 SourceLocation(), SourceLocation(),
5723 &Context->Idents.get("__builtin_va_list"),
5724 TInfo);
5725 return VaListTypeDecl;
5726}
5727
Tim Northoverc264e162013-01-31 12:13:10 +00005728static TypedefDecl *
5729CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5730 RecordDecl *VaListTagDecl;
5731 if (Context->getLangOpts().CPlusPlus) {
5732 // namespace std { struct __va_list {
5733 NamespaceDecl *NS;
5734 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5735 Context->getTranslationUnitDecl(),
5736 /*Inline*/false, SourceLocation(),
5737 SourceLocation(), &Context->Idents.get("std"),
5738 /*PrevDecl*/0);
5739
5740 VaListTagDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5741 Context->getTranslationUnitDecl(),
5742 SourceLocation(), SourceLocation(),
5743 &Context->Idents.get("__va_list"));
5744 VaListTagDecl->setDeclContext(NS);
5745 } else {
5746 // struct __va_list
5747 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5748 Context->getTranslationUnitDecl(),
5749 &Context->Idents.get("__va_list"));
5750 }
5751
5752 VaListTagDecl->startDefinition();
5753
5754 const size_t NumFields = 5;
5755 QualType FieldTypes[NumFields];
5756 const char *FieldNames[NumFields];
5757
5758 // void *__stack;
5759 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5760 FieldNames[0] = "__stack";
5761
5762 // void *__gr_top;
5763 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5764 FieldNames[1] = "__gr_top";
5765
5766 // void *__vr_top;
5767 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5768 FieldNames[2] = "__vr_top";
5769
5770 // int __gr_offs;
5771 FieldTypes[3] = Context->IntTy;
5772 FieldNames[3] = "__gr_offs";
5773
5774 // int __vr_offs;
5775 FieldTypes[4] = Context->IntTy;
5776 FieldNames[4] = "__vr_offs";
5777
5778 // Create fields
5779 for (unsigned i = 0; i < NumFields; ++i) {
5780 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5781 VaListTagDecl,
5782 SourceLocation(),
5783 SourceLocation(),
5784 &Context->Idents.get(FieldNames[i]),
5785 FieldTypes[i], /*TInfo=*/0,
5786 /*BitWidth=*/0,
5787 /*Mutable=*/false,
5788 ICIS_NoInit);
5789 Field->setAccess(AS_public);
5790 VaListTagDecl->addDecl(Field);
5791 }
5792 VaListTagDecl->completeDefinition();
5793 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5794 Context->VaListTagTy = VaListTagType;
5795
5796 // } __builtin_va_list;
5797 TypedefDecl *VaListTypedefDecl
5798 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5799 Context->getTranslationUnitDecl(),
5800 SourceLocation(), SourceLocation(),
5801 &Context->Idents.get("__builtin_va_list"),
5802 Context->getTrivialTypeSourceInfo(VaListTagType));
5803
5804 return VaListTypedefDecl;
5805}
5806
Meador Ingec5613b22012-06-16 03:34:49 +00005807static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5808 // typedef struct __va_list_tag {
5809 RecordDecl *VaListTagDecl;
5810
5811 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5812 Context->getTranslationUnitDecl(),
5813 &Context->Idents.get("__va_list_tag"));
5814 VaListTagDecl->startDefinition();
5815
5816 const size_t NumFields = 5;
5817 QualType FieldTypes[NumFields];
5818 const char *FieldNames[NumFields];
5819
5820 // unsigned char gpr;
5821 FieldTypes[0] = Context->UnsignedCharTy;
5822 FieldNames[0] = "gpr";
5823
5824 // unsigned char fpr;
5825 FieldTypes[1] = Context->UnsignedCharTy;
5826 FieldNames[1] = "fpr";
5827
5828 // unsigned short reserved;
5829 FieldTypes[2] = Context->UnsignedShortTy;
5830 FieldNames[2] = "reserved";
5831
5832 // void* overflow_arg_area;
5833 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5834 FieldNames[3] = "overflow_arg_area";
5835
5836 // void* reg_save_area;
5837 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5838 FieldNames[4] = "reg_save_area";
5839
5840 // Create fields
5841 for (unsigned i = 0; i < NumFields; ++i) {
5842 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5843 SourceLocation(),
5844 SourceLocation(),
5845 &Context->Idents.get(FieldNames[i]),
5846 FieldTypes[i], /*TInfo=*/0,
5847 /*BitWidth=*/0,
5848 /*Mutable=*/false,
5849 ICIS_NoInit);
5850 Field->setAccess(AS_public);
5851 VaListTagDecl->addDecl(Field);
5852 }
5853 VaListTagDecl->completeDefinition();
5854 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005855 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005856
5857 // } __va_list_tag;
5858 TypedefDecl *VaListTagTypedefDecl
5859 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5860 Context->getTranslationUnitDecl(),
5861 SourceLocation(), SourceLocation(),
5862 &Context->Idents.get("__va_list_tag"),
5863 Context->getTrivialTypeSourceInfo(VaListTagType));
5864 QualType VaListTagTypedefType =
5865 Context->getTypedefType(VaListTagTypedefDecl);
5866
5867 // typedef __va_list_tag __builtin_va_list[1];
5868 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5869 QualType VaListTagArrayType
5870 = Context->getConstantArrayType(VaListTagTypedefType,
5871 Size, ArrayType::Normal, 0);
5872 TypeSourceInfo *TInfo
5873 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5874 TypedefDecl *VaListTypedefDecl
5875 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5876 Context->getTranslationUnitDecl(),
5877 SourceLocation(), SourceLocation(),
5878 &Context->Idents.get("__builtin_va_list"),
5879 TInfo);
5880
5881 return VaListTypedefDecl;
5882}
5883
5884static TypedefDecl *
5885CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5886 // typedef struct __va_list_tag {
5887 RecordDecl *VaListTagDecl;
5888 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5889 Context->getTranslationUnitDecl(),
5890 &Context->Idents.get("__va_list_tag"));
5891 VaListTagDecl->startDefinition();
5892
5893 const size_t NumFields = 4;
5894 QualType FieldTypes[NumFields];
5895 const char *FieldNames[NumFields];
5896
5897 // unsigned gp_offset;
5898 FieldTypes[0] = Context->UnsignedIntTy;
5899 FieldNames[0] = "gp_offset";
5900
5901 // unsigned fp_offset;
5902 FieldTypes[1] = Context->UnsignedIntTy;
5903 FieldNames[1] = "fp_offset";
5904
5905 // void* overflow_arg_area;
5906 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5907 FieldNames[2] = "overflow_arg_area";
5908
5909 // void* reg_save_area;
5910 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5911 FieldNames[3] = "reg_save_area";
5912
5913 // Create fields
5914 for (unsigned i = 0; i < NumFields; ++i) {
5915 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5916 VaListTagDecl,
5917 SourceLocation(),
5918 SourceLocation(),
5919 &Context->Idents.get(FieldNames[i]),
5920 FieldTypes[i], /*TInfo=*/0,
5921 /*BitWidth=*/0,
5922 /*Mutable=*/false,
5923 ICIS_NoInit);
5924 Field->setAccess(AS_public);
5925 VaListTagDecl->addDecl(Field);
5926 }
5927 VaListTagDecl->completeDefinition();
5928 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005929 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005930
5931 // } __va_list_tag;
5932 TypedefDecl *VaListTagTypedefDecl
5933 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5934 Context->getTranslationUnitDecl(),
5935 SourceLocation(), SourceLocation(),
5936 &Context->Idents.get("__va_list_tag"),
5937 Context->getTrivialTypeSourceInfo(VaListTagType));
5938 QualType VaListTagTypedefType =
5939 Context->getTypedefType(VaListTagTypedefDecl);
5940
5941 // typedef __va_list_tag __builtin_va_list[1];
5942 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5943 QualType VaListTagArrayType
5944 = Context->getConstantArrayType(VaListTagTypedefType,
5945 Size, ArrayType::Normal,0);
5946 TypeSourceInfo *TInfo
5947 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5948 TypedefDecl *VaListTypedefDecl
5949 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5950 Context->getTranslationUnitDecl(),
5951 SourceLocation(), SourceLocation(),
5952 &Context->Idents.get("__builtin_va_list"),
5953 TInfo);
5954
5955 return VaListTypedefDecl;
5956}
5957
5958static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5959 // typedef int __builtin_va_list[4];
5960 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5961 QualType IntArrayType
5962 = Context->getConstantArrayType(Context->IntTy,
5963 Size, ArrayType::Normal, 0);
5964 TypedefDecl *VaListTypedefDecl
5965 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5966 Context->getTranslationUnitDecl(),
5967 SourceLocation(), SourceLocation(),
5968 &Context->Idents.get("__builtin_va_list"),
5969 Context->getTrivialTypeSourceInfo(IntArrayType));
5970
5971 return VaListTypedefDecl;
5972}
5973
Logan Chieneae5a8202012-10-10 06:56:20 +00005974static TypedefDecl *
5975CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5976 RecordDecl *VaListDecl;
5977 if (Context->getLangOpts().CPlusPlus) {
5978 // namespace std { struct __va_list {
5979 NamespaceDecl *NS;
5980 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5981 Context->getTranslationUnitDecl(),
5982 /*Inline*/false, SourceLocation(),
5983 SourceLocation(), &Context->Idents.get("std"),
5984 /*PrevDecl*/0);
5985
5986 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5987 Context->getTranslationUnitDecl(),
5988 SourceLocation(), SourceLocation(),
5989 &Context->Idents.get("__va_list"));
5990
5991 VaListDecl->setDeclContext(NS);
5992
5993 } else {
5994 // struct __va_list {
5995 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
5996 Context->getTranslationUnitDecl(),
5997 &Context->Idents.get("__va_list"));
5998 }
5999
6000 VaListDecl->startDefinition();
6001
6002 // void * __ap;
6003 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6004 VaListDecl,
6005 SourceLocation(),
6006 SourceLocation(),
6007 &Context->Idents.get("__ap"),
6008 Context->getPointerType(Context->VoidTy),
6009 /*TInfo=*/0,
6010 /*BitWidth=*/0,
6011 /*Mutable=*/false,
6012 ICIS_NoInit);
6013 Field->setAccess(AS_public);
6014 VaListDecl->addDecl(Field);
6015
6016 // };
6017 VaListDecl->completeDefinition();
6018
6019 // typedef struct __va_list __builtin_va_list;
6020 TypeSourceInfo *TInfo
6021 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
6022
6023 TypedefDecl *VaListTypeDecl
6024 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6025 Context->getTranslationUnitDecl(),
6026 SourceLocation(), SourceLocation(),
6027 &Context->Idents.get("__builtin_va_list"),
6028 TInfo);
6029
6030 return VaListTypeDecl;
6031}
6032
Ulrich Weigandb8409212013-05-06 16:26:41 +00006033static TypedefDecl *
6034CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6035 // typedef struct __va_list_tag {
6036 RecordDecl *VaListTagDecl;
6037 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
6038 Context->getTranslationUnitDecl(),
6039 &Context->Idents.get("__va_list_tag"));
6040 VaListTagDecl->startDefinition();
6041
6042 const size_t NumFields = 4;
6043 QualType FieldTypes[NumFields];
6044 const char *FieldNames[NumFields];
6045
6046 // long __gpr;
6047 FieldTypes[0] = Context->LongTy;
6048 FieldNames[0] = "__gpr";
6049
6050 // long __fpr;
6051 FieldTypes[1] = Context->LongTy;
6052 FieldNames[1] = "__fpr";
6053
6054 // void *__overflow_arg_area;
6055 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6056 FieldNames[2] = "__overflow_arg_area";
6057
6058 // void *__reg_save_area;
6059 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6060 FieldNames[3] = "__reg_save_area";
6061
6062 // Create fields
6063 for (unsigned i = 0; i < NumFields; ++i) {
6064 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6065 VaListTagDecl,
6066 SourceLocation(),
6067 SourceLocation(),
6068 &Context->Idents.get(FieldNames[i]),
6069 FieldTypes[i], /*TInfo=*/0,
6070 /*BitWidth=*/0,
6071 /*Mutable=*/false,
6072 ICIS_NoInit);
6073 Field->setAccess(AS_public);
6074 VaListTagDecl->addDecl(Field);
6075 }
6076 VaListTagDecl->completeDefinition();
6077 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6078 Context->VaListTagTy = VaListTagType;
6079
6080 // } __va_list_tag;
6081 TypedefDecl *VaListTagTypedefDecl
6082 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6083 Context->getTranslationUnitDecl(),
6084 SourceLocation(), SourceLocation(),
6085 &Context->Idents.get("__va_list_tag"),
6086 Context->getTrivialTypeSourceInfo(VaListTagType));
6087 QualType VaListTagTypedefType =
6088 Context->getTypedefType(VaListTagTypedefDecl);
6089
6090 // typedef __va_list_tag __builtin_va_list[1];
6091 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6092 QualType VaListTagArrayType
6093 = Context->getConstantArrayType(VaListTagTypedefType,
6094 Size, ArrayType::Normal,0);
6095 TypeSourceInfo *TInfo
6096 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
6097 TypedefDecl *VaListTypedefDecl
6098 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6099 Context->getTranslationUnitDecl(),
6100 SourceLocation(), SourceLocation(),
6101 &Context->Idents.get("__builtin_va_list"),
6102 TInfo);
6103
6104 return VaListTypedefDecl;
6105}
6106
Meador Ingec5613b22012-06-16 03:34:49 +00006107static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6108 TargetInfo::BuiltinVaListKind Kind) {
6109 switch (Kind) {
6110 case TargetInfo::CharPtrBuiltinVaList:
6111 return CreateCharPtrBuiltinVaListDecl(Context);
6112 case TargetInfo::VoidPtrBuiltinVaList:
6113 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northoverc264e162013-01-31 12:13:10 +00006114 case TargetInfo::AArch64ABIBuiltinVaList:
6115 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00006116 case TargetInfo::PowerABIBuiltinVaList:
6117 return CreatePowerABIBuiltinVaListDecl(Context);
6118 case TargetInfo::X86_64ABIBuiltinVaList:
6119 return CreateX86_64ABIBuiltinVaListDecl(Context);
6120 case TargetInfo::PNaClABIBuiltinVaList:
6121 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chieneae5a8202012-10-10 06:56:20 +00006122 case TargetInfo::AAPCSABIBuiltinVaList:
6123 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigandb8409212013-05-06 16:26:41 +00006124 case TargetInfo::SystemZBuiltinVaList:
6125 return CreateSystemZBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00006126 }
6127
6128 llvm_unreachable("Unhandled __builtin_va_list type kind");
6129}
6130
6131TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6132 if (!BuiltinVaListDecl)
6133 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6134
6135 return BuiltinVaListDecl;
6136}
6137
Meador Ingefb40e3f2012-07-01 15:57:25 +00006138QualType ASTContext::getVaListTagType() const {
6139 // Force the creation of VaListTagTy by building the __builtin_va_list
6140 // declaration.
6141 if (VaListTagTy.isNull())
6142 (void) getBuiltinVaListDecl();
6143
6144 return VaListTagTy;
6145}
6146
Ted Kremeneka526c5c2008-01-07 19:49:32 +00006147void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00006148 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00006149 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00006150
Ted Kremeneka526c5c2008-01-07 19:49:32 +00006151 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00006152}
6153
John McCall0bd6feb2009-12-02 08:04:21 +00006154/// \brief Retrieve the template name that corresponds to a non-empty
6155/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00006156TemplateName
6157ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6158 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00006159 unsigned size = End - Begin;
6160 assert(size > 1 && "set is not overloaded!");
6161
6162 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6163 size * sizeof(FunctionTemplateDecl*));
6164 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6165
6166 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00006167 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00006168 NamedDecl *D = *I;
6169 assert(isa<FunctionTemplateDecl>(D) ||
6170 (isa<UsingShadowDecl>(D) &&
6171 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6172 *Storage++ = D;
6173 }
6174
6175 return TemplateName(OT);
6176}
6177
Douglas Gregor7532dc62009-03-30 22:58:21 +00006178/// \brief Retrieve the template name that represents a qualified
6179/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00006180TemplateName
6181ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6182 bool TemplateKeyword,
6183 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00006184 assert(NNS && "Missing nested-name-specifier in qualified template name");
6185
Douglas Gregor789b1f62010-02-04 18:10:26 +00006186 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00006187 llvm::FoldingSetNodeID ID;
6188 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6189
6190 void *InsertPos = 0;
6191 QualifiedTemplateName *QTN =
6192 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6193 if (!QTN) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006194 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6195 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregor7532dc62009-03-30 22:58:21 +00006196 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6197 }
6198
6199 return TemplateName(QTN);
6200}
6201
6202/// \brief Retrieve the template name that represents a dependent
6203/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00006204TemplateName
6205ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6206 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00006207 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00006208 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00006209
6210 llvm::FoldingSetNodeID ID;
6211 DependentTemplateName::Profile(ID, NNS, Name);
6212
6213 void *InsertPos = 0;
6214 DependentTemplateName *QTN =
6215 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6216
6217 if (QTN)
6218 return TemplateName(QTN);
6219
6220 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6221 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006222 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6223 DependentTemplateName(NNS, Name);
Douglas Gregor7532dc62009-03-30 22:58:21 +00006224 } else {
6225 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smith2f47cab2012-08-16 01:19:31 +00006226 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6227 DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00006228 DependentTemplateName *CheckQTN =
6229 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6230 assert(!CheckQTN && "Dependent type name canonicalization broken");
6231 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00006232 }
6233
6234 DependentTemplateNames.InsertNode(QTN, InsertPos);
6235 return TemplateName(QTN);
6236}
6237
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006238/// \brief Retrieve the template name that represents a dependent
6239/// template name such as \c MetaFun::template operator+.
6240TemplateName
6241ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00006242 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006243 assert((!NNS || NNS->isDependent()) &&
6244 "Nested name specifier must be dependent");
6245
6246 llvm::FoldingSetNodeID ID;
6247 DependentTemplateName::Profile(ID, NNS, Operator);
6248
6249 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00006250 DependentTemplateName *QTN
6251 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006252
6253 if (QTN)
6254 return TemplateName(QTN);
6255
6256 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6257 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006258 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6259 DependentTemplateName(NNS, Operator);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006260 } else {
6261 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smith2f47cab2012-08-16 01:19:31 +00006262 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6263 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00006264
6265 DependentTemplateName *CheckQTN
6266 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6267 assert(!CheckQTN && "Dependent template name canonicalization broken");
6268 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006269 }
6270
6271 DependentTemplateNames.InsertNode(QTN, InsertPos);
6272 return TemplateName(QTN);
6273}
6274
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006275TemplateName
John McCall14606042011-06-30 08:33:18 +00006276ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6277 TemplateName replacement) const {
6278 llvm::FoldingSetNodeID ID;
6279 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6280
6281 void *insertPos = 0;
6282 SubstTemplateTemplateParmStorage *subst
6283 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6284
6285 if (!subst) {
6286 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6287 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6288 }
6289
6290 return TemplateName(subst);
6291}
6292
6293TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006294ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6295 const TemplateArgument &ArgPack) const {
6296 ASTContext &Self = const_cast<ASTContext &>(*this);
6297 llvm::FoldingSetNodeID ID;
6298 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6299
6300 void *InsertPos = 0;
6301 SubstTemplateTemplateParmPackStorage *Subst
6302 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6303
6304 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00006305 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006306 ArgPack.pack_size(),
6307 ArgPack.pack_begin());
6308 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6309 }
6310
6311 return TemplateName(Subst);
6312}
6313
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006314/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00006315/// TargetInfo, produce the corresponding type. The unsigned @p Type
6316/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00006317CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006318 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00006319 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006320 case TargetInfo::SignedShort: return ShortTy;
6321 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6322 case TargetInfo::SignedInt: return IntTy;
6323 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6324 case TargetInfo::SignedLong: return LongTy;
6325 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6326 case TargetInfo::SignedLongLong: return LongLongTy;
6327 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6328 }
6329
David Blaikieb219cfc2011-09-23 05:06:16 +00006330 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006331}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00006332
6333//===----------------------------------------------------------------------===//
6334// Type Predicates.
6335//===----------------------------------------------------------------------===//
6336
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006337/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6338/// garbage collection attribute.
6339///
John McCallae278a32011-01-12 00:34:59 +00006340Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006341 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00006342 return Qualifiers::GCNone;
6343
David Blaikie4e4d0842012-03-11 07:00:24 +00006344 assert(getLangOpts().ObjC1);
John McCallae278a32011-01-12 00:34:59 +00006345 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6346
6347 // Default behaviour under objective-C's gc is for ObjC pointers
6348 // (or pointers to them) be treated as though they were declared
6349 // as __strong.
6350 if (GCAttrs == Qualifiers::GCNone) {
6351 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6352 return Qualifiers::Strong;
6353 else if (Ty->isPointerType())
6354 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6355 } else {
6356 // It's not valid to set GC attributes on anything that isn't a
6357 // pointer.
6358#ifndef NDEBUG
6359 QualType CT = Ty->getCanonicalTypeInternal();
6360 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6361 CT = AT->getElementType();
6362 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6363#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006364 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00006365 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006366}
6367
Chris Lattner6ac46a42008-04-07 06:51:04 +00006368//===----------------------------------------------------------------------===//
6369// Type Compatibility Testing
6370//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00006371
Mike Stump1eb44332009-09-09 15:08:12 +00006372/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006373/// compatible.
6374static bool areCompatVectorTypes(const VectorType *LHS,
6375 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00006376 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00006377 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00006378 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00006379}
6380
Douglas Gregor255210e2010-08-06 10:14:59 +00006381bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6382 QualType SecondVec) {
6383 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6384 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6385
6386 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6387 return true;
6388
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006389 // Treat Neon vector types and most AltiVec vector types as if they are the
6390 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00006391 const VectorType *First = FirstVec->getAs<VectorType>();
6392 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006393 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00006394 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006395 First->getVectorKind() != VectorType::AltiVecPixel &&
6396 First->getVectorKind() != VectorType::AltiVecBool &&
6397 Second->getVectorKind() != VectorType::AltiVecPixel &&
6398 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00006399 return true;
6400
6401 return false;
6402}
6403
Steve Naroff4084c302009-07-23 01:01:38 +00006404//===----------------------------------------------------------------------===//
6405// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6406//===----------------------------------------------------------------------===//
6407
6408/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6409/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00006410bool
6411ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6412 ObjCProtocolDecl *rProto) const {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00006413 if (declaresSameEntity(lProto, rProto))
Steve Naroff4084c302009-07-23 01:01:38 +00006414 return true;
6415 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6416 E = rProto->protocol_end(); PI != E; ++PI)
6417 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6418 return true;
6419 return false;
6420}
6421
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00006422/// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
Steve Naroff4084c302009-07-23 01:01:38 +00006423/// return true if lhs's protocols conform to rhs's protocol; false
6424/// otherwise.
6425bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
6426 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
6427 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
6428 return false;
6429}
6430
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00006431/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6432/// Class<pr1, ...>.
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006433bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6434 QualType rhs) {
6435 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6436 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6437 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6438
6439 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6440 E = lhsQID->qual_end(); I != E; ++I) {
6441 bool match = false;
6442 ObjCProtocolDecl *lhsProto = *I;
6443 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6444 E = rhsOPT->qual_end(); J != E; ++J) {
6445 ObjCProtocolDecl *rhsProto = *J;
6446 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6447 match = true;
6448 break;
6449 }
6450 }
6451 if (!match)
6452 return false;
6453 }
6454 return true;
6455}
6456
Steve Naroff4084c302009-07-23 01:01:38 +00006457/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6458/// ObjCQualifiedIDType.
6459bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6460 bool compare) {
6461 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00006462 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006463 lhs->isObjCIdType() || lhs->isObjCClassType())
6464 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006465 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006466 rhs->isObjCIdType() || rhs->isObjCClassType())
6467 return true;
6468
6469 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00006470 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006471
Steve Naroff4084c302009-07-23 01:01:38 +00006472 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006473
Steve Naroff4084c302009-07-23 01:01:38 +00006474 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006475 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00006476 // make sure we check the class hierarchy.
6477 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6478 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6479 E = lhsQID->qual_end(); I != E; ++I) {
6480 // when comparing an id<P> on lhs with a static type on rhs,
6481 // see if static class implements all of id's protocols, directly or
6482 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006483 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00006484 return false;
6485 }
6486 }
6487 // If there are no qualifiers and no interface, we have an 'id'.
6488 return true;
6489 }
Mike Stump1eb44332009-09-09 15:08:12 +00006490 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006491 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6492 E = lhsQID->qual_end(); I != E; ++I) {
6493 ObjCProtocolDecl *lhsProto = *I;
6494 bool match = false;
6495
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.
6499 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6500 E = rhsOPT->qual_end(); J != E; ++J) {
6501 ObjCProtocolDecl *rhsProto = *J;
6502 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6503 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6504 match = true;
6505 break;
6506 }
6507 }
Mike Stump1eb44332009-09-09 15:08:12 +00006508 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00006509 // make sure we check the class hierarchy.
6510 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6511 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6512 E = lhsQID->qual_end(); I != E; ++I) {
6513 // when comparing an id<P> on lhs with a static type on rhs,
6514 // see if static class implements all of id's protocols, directly or
6515 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006516 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00006517 match = true;
6518 break;
6519 }
6520 }
6521 }
6522 if (!match)
6523 return false;
6524 }
Mike Stump1eb44332009-09-09 15:08:12 +00006525
Steve Naroff4084c302009-07-23 01:01:38 +00006526 return true;
6527 }
Mike Stump1eb44332009-09-09 15:08:12 +00006528
Steve Naroff4084c302009-07-23 01:01:38 +00006529 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6530 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6531
Mike Stump1eb44332009-09-09 15:08:12 +00006532 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00006533 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006534 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006535 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6536 E = lhsOPT->qual_end(); I != E; ++I) {
6537 ObjCProtocolDecl *lhsProto = *I;
6538 bool match = false;
6539
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006540 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00006541 // see if static class implements all of id's protocols, directly or
6542 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006543 // First, lhs protocols in the qualifier list must be found, direct
6544 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00006545 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6546 E = rhsQID->qual_end(); J != E; ++J) {
6547 ObjCProtocolDecl *rhsProto = *J;
6548 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6549 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6550 match = true;
6551 break;
6552 }
6553 }
6554 if (!match)
6555 return false;
6556 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006557
6558 // Static class's protocols, or its super class or category protocols
6559 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6560 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6561 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6562 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6563 // This is rather dubious but matches gcc's behavior. If lhs has
6564 // no type qualifier and its class has no static protocol(s)
6565 // assume that it is mismatch.
6566 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6567 return false;
6568 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6569 LHSInheritedProtocols.begin(),
6570 E = LHSInheritedProtocols.end(); I != E; ++I) {
6571 bool match = false;
6572 ObjCProtocolDecl *lhsProto = (*I);
6573 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6574 E = rhsQID->qual_end(); J != E; ++J) {
6575 ObjCProtocolDecl *rhsProto = *J;
6576 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6577 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6578 match = true;
6579 break;
6580 }
6581 }
6582 if (!match)
6583 return false;
6584 }
6585 }
Steve Naroff4084c302009-07-23 01:01:38 +00006586 return true;
6587 }
6588 return false;
6589}
6590
Eli Friedman3d815e72008-08-22 00:56:42 +00006591/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006592/// compatible for assignment from RHS to LHS. This handles validation of any
6593/// protocol qualifiers on the LHS or RHS.
6594///
Steve Naroff14108da2009-07-10 23:34:53 +00006595bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6596 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00006597 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6598 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6599
Steve Naroffde2e22d2009-07-15 18:40:39 +00006600 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00006601 if (LHS->isObjCUnqualifiedIdOrClass() ||
6602 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00006603 return true;
6604
John McCallc12c5bb2010-05-15 11:32:37 +00006605 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00006606 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6607 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00006608 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006609
6610 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6611 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6612 QualType(RHSOPT,0));
6613
John McCallc12c5bb2010-05-15 11:32:37 +00006614 // If we have 2 user-defined types, fall into that path.
6615 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00006616 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006617
Steve Naroff4084c302009-07-23 01:01:38 +00006618 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006619}
6620
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006621/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00006622/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006623/// arguments in block literals. When passed as arguments, passing 'A*' where
6624/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6625/// not OK. For the return type, the opposite is not OK.
6626bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6627 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006628 const ObjCObjectPointerType *RHSOPT,
6629 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006630 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006631 return true;
6632
6633 if (LHSOPT->isObjCBuiltinType()) {
6634 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6635 }
6636
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006637 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006638 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6639 QualType(RHSOPT,0),
6640 false);
6641
6642 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6643 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6644 if (LHS && RHS) { // We have 2 user-defined types.
6645 if (LHS != RHS) {
6646 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006647 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006648 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006649 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006650 }
6651 else
6652 return true;
6653 }
6654 return false;
6655}
6656
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006657/// getIntersectionOfProtocols - This routine finds the intersection of set
6658/// of protocols inherited from two distinct objective-c pointer objects.
6659/// It is used to build composite qualifier list of the composite type of
6660/// the conditional expression involving two objective-c pointer objects.
6661static
6662void getIntersectionOfProtocols(ASTContext &Context,
6663 const ObjCObjectPointerType *LHSOPT,
6664 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006665 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006666
John McCallc12c5bb2010-05-15 11:32:37 +00006667 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6668 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6669 assert(LHS->getInterface() && "LHS must have an interface base");
6670 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006671
6672 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6673 unsigned LHSNumProtocols = LHS->getNumProtocols();
6674 if (LHSNumProtocols > 0)
6675 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6676 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006677 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006678 Context.CollectInheritedProtocols(LHS->getInterface(),
6679 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006680 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6681 LHSInheritedProtocols.end());
6682 }
6683
6684 unsigned RHSNumProtocols = RHS->getNumProtocols();
6685 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00006686 ObjCProtocolDecl **RHSProtocols =
6687 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006688 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6689 if (InheritedProtocolSet.count(RHSProtocols[i]))
6690 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00006691 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006692 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006693 Context.CollectInheritedProtocols(RHS->getInterface(),
6694 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006695 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6696 RHSInheritedProtocols.begin(),
6697 E = RHSInheritedProtocols.end(); I != E; ++I)
6698 if (InheritedProtocolSet.count((*I)))
6699 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006700 }
6701}
6702
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006703/// areCommonBaseCompatible - Returns common base class of the two classes if
6704/// one found. Note that this is O'2 algorithm. But it will be called as the
6705/// last type comparison in a ?-exp of ObjC pointer types before a
6706/// warning is issued. So, its invokation is extremely rare.
6707QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00006708 const ObjCObjectPointerType *Lptr,
6709 const ObjCObjectPointerType *Rptr) {
6710 const ObjCObjectType *LHS = Lptr->getObjectType();
6711 const ObjCObjectType *RHS = Rptr->getObjectType();
6712 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6713 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor60ef3082011-12-15 00:29:59 +00006714 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006715 return QualType();
6716
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006717 do {
John McCallc12c5bb2010-05-15 11:32:37 +00006718 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006719 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006720 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006721 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6722
6723 QualType Result = QualType(LHS, 0);
6724 if (!Protocols.empty())
6725 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6726 Result = getObjCObjectPointerType(Result);
6727 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006728 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006729 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006730
6731 return QualType();
6732}
6733
John McCallc12c5bb2010-05-15 11:32:37 +00006734bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6735 const ObjCObjectType *RHS) {
6736 assert(LHS->getInterface() && "LHS is not an interface type");
6737 assert(RHS->getInterface() && "RHS is not an interface type");
6738
Chris Lattner6ac46a42008-04-07 06:51:04 +00006739 // Verify that the base decls are compatible: the RHS must be a subclass of
6740 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00006741 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00006742 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006743
Chris Lattner6ac46a42008-04-07 06:51:04 +00006744 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6745 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00006746 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00006747 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006748
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006749 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6750 // more detailed analysis is required.
6751 if (RHS->getNumProtocols() == 0) {
6752 // OK, if LHS is a superclass of RHS *and*
6753 // this superclass is assignment compatible with LHS.
6754 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006755 bool IsSuperClass =
6756 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6757 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006758 // OK if conversion of LHS to SuperClass results in narrowing of types
6759 // ; i.e., SuperClass may implement at least one of the protocols
6760 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6761 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6762 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006763 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006764 // If super class has no protocols, it is not a match.
6765 if (SuperClassInheritedProtocols.empty())
6766 return false;
6767
6768 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6769 LHSPE = LHS->qual_end();
6770 LHSPI != LHSPE; LHSPI++) {
6771 bool SuperImplementsProtocol = false;
6772 ObjCProtocolDecl *LHSProto = (*LHSPI);
6773
6774 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6775 SuperClassInheritedProtocols.begin(),
6776 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6777 ObjCProtocolDecl *SuperClassProto = (*I);
6778 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6779 SuperImplementsProtocol = true;
6780 break;
6781 }
6782 }
6783 if (!SuperImplementsProtocol)
6784 return false;
6785 }
6786 return true;
6787 }
6788 return false;
6789 }
Mike Stump1eb44332009-09-09 15:08:12 +00006790
John McCallc12c5bb2010-05-15 11:32:37 +00006791 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6792 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006793 LHSPI != LHSPE; LHSPI++) {
6794 bool RHSImplementsProtocol = false;
6795
6796 // If the RHS doesn't implement the protocol on the left, the types
6797 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00006798 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6799 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00006800 RHSPI != RHSPE; RHSPI++) {
6801 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006802 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00006803 break;
6804 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006805 }
6806 // FIXME: For better diagnostics, consider passing back the protocol name.
6807 if (!RHSImplementsProtocol)
6808 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006809 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006810 // The RHS implements all protocols listed on the LHS.
6811 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006812}
6813
Steve Naroff389bf462009-02-12 17:52:19 +00006814bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6815 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00006816 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6817 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006818
Steve Naroff14108da2009-07-10 23:34:53 +00006819 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00006820 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006821
6822 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6823 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00006824}
6825
Douglas Gregor569c3162010-08-07 11:51:51 +00006826bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6827 return canAssignObjCInterfaces(
6828 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6829 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6830}
6831
Mike Stump1eb44332009-09-09 15:08:12 +00006832/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00006833/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00006834/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00006835/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00006836bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6837 bool CompareUnqualified) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006838 if (getLangOpts().CPlusPlus)
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006839 return hasSameType(LHS, RHS);
6840
Douglas Gregor447234d2010-07-29 15:18:02 +00006841 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00006842}
6843
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006844bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00006845 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006846}
6847
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006848bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6849 return !mergeTypes(LHS, RHS, true).isNull();
6850}
6851
Peter Collingbourne48466752010-10-24 18:30:18 +00006852/// mergeTransparentUnionType - if T is a transparent union type and a member
6853/// of T is compatible with SubType, return the merged type, else return
6854/// QualType()
6855QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6856 bool OfBlockPointer,
6857 bool Unqualified) {
6858 if (const RecordType *UT = T->getAsUnionType()) {
6859 RecordDecl *UD = UT->getDecl();
6860 if (UD->hasAttr<TransparentUnionAttr>()) {
6861 for (RecordDecl::field_iterator it = UD->field_begin(),
6862 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00006863 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006864 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6865 if (!MT.isNull())
6866 return MT;
6867 }
6868 }
6869 }
6870
6871 return QualType();
6872}
6873
6874/// mergeFunctionArgumentTypes - merge two types which appear as function
6875/// argument types
6876QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6877 bool OfBlockPointer,
6878 bool Unqualified) {
6879 // GNU extension: two types are compatible if they appear as a function
6880 // argument, one of the types is a transparent union type and the other
6881 // type is compatible with a union member
6882 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6883 Unqualified);
6884 if (!lmerge.isNull())
6885 return lmerge;
6886
6887 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6888 Unqualified);
6889 if (!rmerge.isNull())
6890 return rmerge;
6891
6892 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6893}
6894
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006895QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00006896 bool OfBlockPointer,
6897 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00006898 const FunctionType *lbase = lhs->getAs<FunctionType>();
6899 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00006900 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6901 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00006902 bool allLTypes = true;
6903 bool allRTypes = true;
6904
6905 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006906 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006907 if (OfBlockPointer) {
6908 QualType RHS = rbase->getResultType();
6909 QualType LHS = lbase->getResultType();
6910 bool UnqualifiedResult = Unqualified;
6911 if (!UnqualifiedResult)
6912 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006913 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006914 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006915 else
John McCall8cc246c2010-12-15 01:06:38 +00006916 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6917 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006918 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006919
6920 if (Unqualified)
6921 retType = retType.getUnqualifiedType();
6922
6923 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6924 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6925 if (Unqualified) {
6926 LRetType = LRetType.getUnqualifiedType();
6927 RRetType = RRetType.getUnqualifiedType();
6928 }
6929
6930 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006931 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00006932 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006933 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00006934
Daniel Dunbar6a15c852010-04-28 16:20:58 +00006935 // FIXME: double check this
6936 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6937 // rbase->getRegParmAttr() != 0 &&
6938 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00006939 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6940 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00006941
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006942 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00006943 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006944 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006945
John McCall8cc246c2010-12-15 01:06:38 +00006946 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00006947 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6948 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00006949 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6950 return QualType();
6951
John McCallf85e1932011-06-15 23:02:42 +00006952 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6953 return QualType();
6954
John McCall8cc246c2010-12-15 01:06:38 +00006955 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6956 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00006957
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00006958 if (lbaseInfo.getNoReturn() != NoReturn)
6959 allLTypes = false;
6960 if (rbaseInfo.getNoReturn() != NoReturn)
6961 allRTypes = false;
6962
John McCallf85e1932011-06-15 23:02:42 +00006963 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00006964
Eli Friedman3d815e72008-08-22 00:56:42 +00006965 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00006966 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6967 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006968 unsigned lproto_nargs = lproto->getNumArgs();
6969 unsigned rproto_nargs = rproto->getNumArgs();
6970
6971 // Compatible functions must have the same number of arguments
6972 if (lproto_nargs != rproto_nargs)
6973 return QualType();
6974
6975 // Variadic and non-variadic functions aren't compatible
6976 if (lproto->isVariadic() != rproto->isVariadic())
6977 return QualType();
6978
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00006979 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6980 return QualType();
6981
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006982 if (LangOpts.ObjCAutoRefCount &&
6983 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6984 return QualType();
6985
Eli Friedman3d815e72008-08-22 00:56:42 +00006986 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00006987 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00006988 for (unsigned i = 0; i < lproto_nargs; i++) {
6989 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6990 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006991 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6992 OfBlockPointer,
6993 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006994 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006995
6996 if (Unqualified)
6997 argtype = argtype.getUnqualifiedType();
6998
Eli Friedman3d815e72008-08-22 00:56:42 +00006999 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00007000 if (Unqualified) {
7001 largtype = largtype.getUnqualifiedType();
7002 rargtype = rargtype.getUnqualifiedType();
7003 }
7004
Chris Lattner61710852008-10-05 17:34:18 +00007005 if (getCanonicalType(argtype) != getCanonicalType(largtype))
7006 allLTypes = false;
7007 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
7008 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00007009 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00007010
Eli Friedman3d815e72008-08-22 00:56:42 +00007011 if (allLTypes) return lhs;
7012 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00007013
7014 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7015 EPI.ExtInfo = einfo;
Jordan Rosebea522f2013-03-08 21:51:21 +00007016 return getFunctionType(retType, types, EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00007017 }
7018
7019 if (lproto) allRTypes = false;
7020 if (rproto) allLTypes = false;
7021
Douglas Gregor72564e72009-02-26 23:50:07 +00007022 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00007023 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00007024 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00007025 if (proto->isVariadic()) return QualType();
7026 // Check that the types are compatible with the types that
7027 // would result from default argument promotions (C99 6.7.5.3p15).
7028 // The only types actually affected are promotable integer
7029 // types and floats, which would be passed as a different
7030 // type depending on whether the prototype is visible.
7031 unsigned proto_nargs = proto->getNumArgs();
7032 for (unsigned i = 0; i < proto_nargs; ++i) {
7033 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007034
Eli Friedmanc586d5d2012-08-30 00:44:15 +00007035 // Look at the converted type of enum types, since that is the type used
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007036 // to pass enum values.
Eli Friedmanc586d5d2012-08-30 00:44:15 +00007037 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
7038 argTy = Enum->getDecl()->getIntegerType();
7039 if (argTy.isNull())
7040 return QualType();
7041 }
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007042
Eli Friedman3d815e72008-08-22 00:56:42 +00007043 if (argTy->isPromotableIntegerType() ||
7044 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
7045 return QualType();
7046 }
7047
7048 if (allLTypes) return lhs;
7049 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00007050
7051 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7052 EPI.ExtInfo = einfo;
Reid Kleckner0567a792013-06-10 20:51:09 +00007053 return getFunctionType(retType, proto->getArgTypes(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00007054 }
7055
7056 if (allLTypes) return lhs;
7057 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00007058 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00007059}
7060
John McCallb9da7132013-03-21 00:10:07 +00007061/// Given that we have an enum type and a non-enum type, try to merge them.
7062static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7063 QualType other, bool isBlockReturnType) {
7064 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7065 // a signed integer type, or an unsigned integer type.
7066 // Compatibility is based on the underlying type, not the promotion
7067 // type.
7068 QualType underlyingType = ET->getDecl()->getIntegerType();
7069 if (underlyingType.isNull()) return QualType();
7070 if (Context.hasSameType(underlyingType, other))
7071 return other;
7072
7073 // In block return types, we're more permissive and accept any
7074 // integral type of the same size.
7075 if (isBlockReturnType && other->isIntegerType() &&
7076 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7077 return other;
7078
7079 return QualType();
7080}
7081
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007082QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00007083 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00007084 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00007085 // C++ [expr]: If an expression initially has the type "reference to T", the
7086 // type is adjusted to "T" prior to any further analysis, the expression
7087 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00007088 // expression is an lvalue unless the reference is an rvalue reference and
7089 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00007090 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7091 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00007092
7093 if (Unqualified) {
7094 LHS = LHS.getUnqualifiedType();
7095 RHS = RHS.getUnqualifiedType();
7096 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00007097
Eli Friedman3d815e72008-08-22 00:56:42 +00007098 QualType LHSCan = getCanonicalType(LHS),
7099 RHSCan = getCanonicalType(RHS);
7100
7101 // If two types are identical, they are compatible.
7102 if (LHSCan == RHSCan)
7103 return LHS;
7104
John McCall0953e762009-09-24 19:53:00 +00007105 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00007106 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7107 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00007108 if (LQuals != RQuals) {
7109 // If any of these qualifiers are different, we have a type
7110 // mismatch.
7111 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00007112 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7113 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00007114 return QualType();
7115
7116 // Exactly one GC qualifier difference is allowed: __strong is
7117 // okay if the other type has no GC qualifier but is an Objective
7118 // C object pointer (i.e. implicitly strong by default). We fix
7119 // this by pretending that the unqualified type was actually
7120 // qualified __strong.
7121 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7122 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7123 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7124
7125 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7126 return QualType();
7127
7128 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7129 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7130 }
7131 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7132 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7133 }
Eli Friedman3d815e72008-08-22 00:56:42 +00007134 return QualType();
John McCall0953e762009-09-24 19:53:00 +00007135 }
7136
7137 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00007138
Eli Friedman852d63b2009-06-01 01:22:52 +00007139 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7140 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00007141
Chris Lattner1adb8832008-01-14 05:45:46 +00007142 // We want to consider the two function types to be the same for these
7143 // comparisons, just force one to the other.
7144 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7145 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00007146
7147 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00007148 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7149 LHSClass = Type::ConstantArray;
7150 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7151 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00007152
John McCallc12c5bb2010-05-15 11:32:37 +00007153 // ObjCInterfaces are just specialized ObjCObjects.
7154 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7155 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7156
Nate Begeman213541a2008-04-18 23:10:10 +00007157 // Canonicalize ExtVector -> Vector.
7158 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7159 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00007160
Chris Lattnera36a61f2008-04-07 05:43:21 +00007161 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00007162 if (LHSClass != RHSClass) {
John McCallb9da7132013-03-21 00:10:07 +00007163 // Note that we only have special rules for turning block enum
7164 // returns into block int returns, not vice-versa.
John McCall183700f2009-09-21 23:43:11 +00007165 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCallb9da7132013-03-21 00:10:07 +00007166 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmanbab96962008-02-12 08:46:17 +00007167 }
John McCall183700f2009-09-21 23:43:11 +00007168 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCallb9da7132013-03-21 00:10:07 +00007169 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmanbab96962008-02-12 08:46:17 +00007170 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00007171 // allow block pointer type to match an 'id' type.
Fariborz Jahanian41963632012-01-26 17:08:50 +00007172 if (OfBlockPointer && !BlockReturnType) {
7173 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7174 return LHS;
7175 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7176 return RHS;
7177 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00007178
Eli Friedman3d815e72008-08-22 00:56:42 +00007179 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00007180 }
Eli Friedman3d815e72008-08-22 00:56:42 +00007181
Steve Naroff4a746782008-01-09 22:43:08 +00007182 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00007183 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00007184#define TYPE(Class, Base)
7185#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00007186#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00007187#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7188#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7189#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00007190 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00007191
Richard Smithdc7a4f52013-04-30 13:56:41 +00007192 case Type::Auto:
Sebastian Redl7c80bd62009-03-16 23:22:08 +00007193 case Type::LValueReference:
7194 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00007195 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00007196 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00007197
John McCallc12c5bb2010-05-15 11:32:37 +00007198 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00007199 case Type::IncompleteArray:
7200 case Type::VariableArray:
7201 case Type::FunctionProto:
7202 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00007203 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00007204
Chris Lattner1adb8832008-01-14 05:45:46 +00007205 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00007206 {
7207 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00007208 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7209 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007210 if (Unqualified) {
7211 LHSPointee = LHSPointee.getUnqualifiedType();
7212 RHSPointee = RHSPointee.getUnqualifiedType();
7213 }
7214 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7215 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00007216 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00007217 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00007218 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00007219 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00007220 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00007221 return getPointerType(ResultType);
7222 }
Steve Naroffc0febd52008-12-10 17:49:55 +00007223 case Type::BlockPointer:
7224 {
7225 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00007226 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7227 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007228 if (Unqualified) {
7229 LHSPointee = LHSPointee.getUnqualifiedType();
7230 RHSPointee = RHSPointee.getUnqualifiedType();
7231 }
7232 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7233 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00007234 if (ResultType.isNull()) return QualType();
7235 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7236 return LHS;
7237 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7238 return RHS;
7239 return getBlockPointerType(ResultType);
7240 }
Eli Friedmanb001de72011-10-06 23:00:33 +00007241 case Type::Atomic:
7242 {
7243 // Merge two pointer types, while trying to preserve typedef info
7244 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7245 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7246 if (Unqualified) {
7247 LHSValue = LHSValue.getUnqualifiedType();
7248 RHSValue = RHSValue.getUnqualifiedType();
7249 }
7250 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7251 Unqualified);
7252 if (ResultType.isNull()) return QualType();
7253 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7254 return LHS;
7255 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7256 return RHS;
7257 return getAtomicType(ResultType);
7258 }
Chris Lattner1adb8832008-01-14 05:45:46 +00007259 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00007260 {
7261 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7262 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7263 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7264 return QualType();
7265
7266 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7267 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007268 if (Unqualified) {
7269 LHSElem = LHSElem.getUnqualifiedType();
7270 RHSElem = RHSElem.getUnqualifiedType();
7271 }
7272
7273 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00007274 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00007275 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7276 return LHS;
7277 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7278 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00007279 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7280 ArrayType::ArraySizeModifier(), 0);
7281 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7282 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00007283 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7284 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00007285 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7286 return LHS;
7287 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7288 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00007289 if (LVAT) {
7290 // FIXME: This isn't correct! But tricky to implement because
7291 // the array's size has to be the size of LHS, but the type
7292 // has to be different.
7293 return LHS;
7294 }
7295 if (RVAT) {
7296 // FIXME: This isn't correct! But tricky to implement because
7297 // the array's size has to be the size of RHS, but the type
7298 // has to be different.
7299 return RHS;
7300 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00007301 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7302 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00007303 return getIncompleteArrayType(ResultType,
7304 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00007305 }
Chris Lattner1adb8832008-01-14 05:45:46 +00007306 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00007307 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00007308 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00007309 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00007310 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00007311 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00007312 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00007313 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00007314 case Type::Complex:
7315 // Distinct complex types are incompatible.
7316 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00007317 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00007318 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00007319 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7320 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00007321 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00007322 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00007323 case Type::ObjCObject: {
7324 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00007325 // FIXME: This should be type compatibility, e.g. whether
7326 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00007327 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7328 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7329 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00007330 return LHS;
7331
Eli Friedman3d815e72008-08-22 00:56:42 +00007332 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00007333 }
Steve Naroff14108da2009-07-10 23:34:53 +00007334 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007335 if (OfBlockPointer) {
7336 if (canAssignObjCInterfacesInBlockPointer(
7337 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00007338 RHS->getAs<ObjCObjectPointerType>(),
7339 BlockReturnType))
David Blaikie7530c032012-01-17 06:56:22 +00007340 return LHS;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007341 return QualType();
7342 }
John McCall183700f2009-09-21 23:43:11 +00007343 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7344 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00007345 return LHS;
7346
Steve Naroffbc76dd02008-12-10 22:14:21 +00007347 return QualType();
David Blaikie7530c032012-01-17 06:56:22 +00007348 }
Steve Naroffec0550f2007-10-15 20:41:53 +00007349 }
Douglas Gregor72564e72009-02-26 23:50:07 +00007350
David Blaikie7530c032012-01-17 06:56:22 +00007351 llvm_unreachable("Invalid Type::Class!");
Steve Naroffec0550f2007-10-15 20:41:53 +00007352}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00007353
Fariborz Jahanian78213e42011-09-28 21:52:05 +00007354bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7355 const FunctionProtoType *FromFunctionType,
7356 const FunctionProtoType *ToFunctionType) {
7357 if (FromFunctionType->hasAnyConsumedArgs() !=
7358 ToFunctionType->hasAnyConsumedArgs())
7359 return false;
7360 FunctionProtoType::ExtProtoInfo FromEPI =
7361 FromFunctionType->getExtProtoInfo();
7362 FunctionProtoType::ExtProtoInfo ToEPI =
7363 ToFunctionType->getExtProtoInfo();
7364 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
7365 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
7366 ArgIdx != NumArgs; ++ArgIdx) {
7367 if (FromEPI.ConsumedArguments[ArgIdx] !=
7368 ToEPI.ConsumedArguments[ArgIdx])
7369 return false;
7370 }
7371 return true;
7372}
7373
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007374/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7375/// 'RHS' attributes and returns the merged version; including for function
7376/// return types.
7377QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7378 QualType LHSCan = getCanonicalType(LHS),
7379 RHSCan = getCanonicalType(RHS);
7380 // If two types are identical, they are compatible.
7381 if (LHSCan == RHSCan)
7382 return LHS;
7383 if (RHSCan->isFunctionType()) {
7384 if (!LHSCan->isFunctionType())
7385 return QualType();
7386 QualType OldReturnType =
7387 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7388 QualType NewReturnType =
7389 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7390 QualType ResReturnType =
7391 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7392 if (ResReturnType.isNull())
7393 return QualType();
7394 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7395 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7396 // In either case, use OldReturnType to build the new function type.
7397 const FunctionType *F = LHS->getAs<FunctionType>();
7398 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00007399 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7400 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner0567a792013-06-10 20:51:09 +00007401 QualType ResultType =
7402 getFunctionType(OldReturnType, FPT->getArgTypes(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007403 return ResultType;
7404 }
7405 }
7406 return QualType();
7407 }
7408
7409 // If the qualifiers are different, the types can still be merged.
7410 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7411 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7412 if (LQuals != RQuals) {
7413 // If any of these qualifiers are different, we have a type mismatch.
7414 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7415 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7416 return QualType();
7417
7418 // Exactly one GC qualifier difference is allowed: __strong is
7419 // okay if the other type has no GC qualifier but is an Objective
7420 // C object pointer (i.e. implicitly strong by default). We fix
7421 // this by pretending that the unqualified type was actually
7422 // qualified __strong.
7423 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7424 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7425 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7426
7427 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7428 return QualType();
7429
7430 if (GC_L == Qualifiers::Strong)
7431 return LHS;
7432 if (GC_R == Qualifiers::Strong)
7433 return RHS;
7434 return QualType();
7435 }
7436
7437 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7438 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7439 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7440 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7441 if (ResQT == LHSBaseQT)
7442 return LHS;
7443 if (ResQT == RHSBaseQT)
7444 return RHS;
7445 }
7446 return QualType();
7447}
7448
Chris Lattner5426bf62008-04-07 07:01:58 +00007449//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00007450// Integer Predicates
7451//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00007452
Jay Foad4ba2a172011-01-12 09:06:06 +00007453unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00007454 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00007455 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007456 if (T->isBooleanType())
7457 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00007458 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00007459 return (unsigned)getTypeSize(T);
7460}
7461
Abramo Bagnara762f1592012-09-09 10:21:24 +00007462QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregorf6094622010-07-23 15:58:24 +00007463 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00007464
7465 // Turn <4 x signed int> -> <4 x unsigned int>
7466 if (const VectorType *VTy = T->getAs<VectorType>())
7467 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00007468 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00007469
7470 // For enums, we return the unsigned version of the base type.
7471 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00007472 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00007473
7474 const BuiltinType *BTy = T->getAs<BuiltinType>();
7475 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007476 switch (BTy->getKind()) {
7477 case BuiltinType::Char_S:
7478 case BuiltinType::SChar:
7479 return UnsignedCharTy;
7480 case BuiltinType::Short:
7481 return UnsignedShortTy;
7482 case BuiltinType::Int:
7483 return UnsignedIntTy;
7484 case BuiltinType::Long:
7485 return UnsignedLongTy;
7486 case BuiltinType::LongLong:
7487 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00007488 case BuiltinType::Int128:
7489 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00007490 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00007491 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007492 }
7493}
7494
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00007495ASTMutationListener::~ASTMutationListener() { }
7496
Richard Smith9dadfab2013-05-11 05:45:24 +00007497void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7498 QualType ReturnType) {}
Chris Lattner86df27b2009-06-14 00:45:47 +00007499
7500//===----------------------------------------------------------------------===//
7501// Builtin Type Computation
7502//===----------------------------------------------------------------------===//
7503
7504/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00007505/// pointer over the consumed characters. This returns the resultant type. If
7506/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7507/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7508/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00007509///
7510/// RequiresICE is filled in on return to indicate whether the value is required
7511/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00007512static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00007513 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00007514 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00007515 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00007516 // Modifiers.
7517 int HowLong = 0;
7518 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00007519 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007520
Chris Lattner33daae62010-10-01 22:42:38 +00007521 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00007522 bool Done = false;
7523 while (!Done) {
7524 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00007525 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007526 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00007527 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007528 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007529 case 'S':
7530 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7531 assert(!Signed && "Can't use 'S' modifier multiple times!");
7532 Signed = true;
7533 break;
7534 case 'U':
7535 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7536 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7537 Unsigned = true;
7538 break;
7539 case 'L':
7540 assert(HowLong <= 2 && "Can't have LLLL modifier");
7541 ++HowLong;
7542 break;
7543 }
7544 }
7545
7546 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00007547
Chris Lattner86df27b2009-06-14 00:45:47 +00007548 // Read the base type.
7549 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00007550 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00007551 case 'v':
7552 assert(HowLong == 0 && !Signed && !Unsigned &&
7553 "Bad modifiers used with 'v'!");
7554 Type = Context.VoidTy;
7555 break;
7556 case 'f':
7557 assert(HowLong == 0 && !Signed && !Unsigned &&
7558 "Bad modifiers used with 'f'!");
7559 Type = Context.FloatTy;
7560 break;
7561 case 'd':
7562 assert(HowLong < 2 && !Signed && !Unsigned &&
7563 "Bad modifiers used with 'd'!");
7564 if (HowLong)
7565 Type = Context.LongDoubleTy;
7566 else
7567 Type = Context.DoubleTy;
7568 break;
7569 case 's':
7570 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7571 if (Unsigned)
7572 Type = Context.UnsignedShortTy;
7573 else
7574 Type = Context.ShortTy;
7575 break;
7576 case 'i':
7577 if (HowLong == 3)
7578 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7579 else if (HowLong == 2)
7580 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7581 else if (HowLong == 1)
7582 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7583 else
7584 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7585 break;
7586 case 'c':
7587 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7588 if (Signed)
7589 Type = Context.SignedCharTy;
7590 else if (Unsigned)
7591 Type = Context.UnsignedCharTy;
7592 else
7593 Type = Context.CharTy;
7594 break;
7595 case 'b': // boolean
7596 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7597 Type = Context.BoolTy;
7598 break;
7599 case 'z': // size_t.
7600 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7601 Type = Context.getSizeType();
7602 break;
7603 case 'F':
7604 Type = Context.getCFConstantStringType();
7605 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00007606 case 'G':
7607 Type = Context.getObjCIdType();
7608 break;
7609 case 'H':
7610 Type = Context.getObjCSelType();
7611 break;
Fariborz Jahanianf7992132013-01-04 18:45:40 +00007612 case 'M':
7613 Type = Context.getObjCSuperType();
7614 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007615 case 'a':
7616 Type = Context.getBuiltinVaListType();
7617 assert(!Type.isNull() && "builtin va list type not initialized!");
7618 break;
7619 case 'A':
7620 // This is a "reference" to a va_list; however, what exactly
7621 // this means depends on how va_list is defined. There are two
7622 // different kinds of va_list: ones passed by value, and ones
7623 // passed by reference. An example of a by-value va_list is
7624 // x86, where va_list is a char*. An example of by-ref va_list
7625 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7626 // we want this argument to be a char*&; for x86-64, we want
7627 // it to be a __va_list_tag*.
7628 Type = Context.getBuiltinVaListType();
7629 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00007630 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00007631 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00007632 else
Chris Lattner86df27b2009-06-14 00:45:47 +00007633 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00007634 break;
7635 case 'V': {
7636 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00007637 unsigned NumElements = strtoul(Str, &End, 10);
7638 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00007639 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00007640
Chris Lattner14e0e742010-10-01 22:53:11 +00007641 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7642 RequiresICE, false);
7643 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00007644
7645 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00007646 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00007647 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00007648 break;
7649 }
Douglas Gregorb4bc99b2012-06-07 18:08:25 +00007650 case 'E': {
7651 char *End;
7652
7653 unsigned NumElements = strtoul(Str, &End, 10);
7654 assert(End != Str && "Missing vector size");
7655
7656 Str = End;
7657
7658 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7659 false);
7660 Type = Context.getExtVectorType(ElementType, NumElements);
7661 break;
7662 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00007663 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00007664 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7665 false);
7666 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00007667 Type = Context.getComplexType(ElementType);
7668 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00007669 }
7670 case 'Y' : {
7671 Type = Context.getPointerDiffType();
7672 break;
7673 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007674 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00007675 Type = Context.getFILEType();
7676 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007677 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00007678 return QualType();
7679 }
Mike Stumpfd612db2009-07-28 23:47:15 +00007680 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007681 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00007682 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00007683 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00007684 else
7685 Type = Context.getjmp_bufType();
7686
Mike Stumpfd612db2009-07-28 23:47:15 +00007687 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007688 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00007689 return QualType();
7690 }
7691 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00007692 case 'K':
7693 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7694 Type = Context.getucontext_tType();
7695
7696 if (Type.isNull()) {
7697 Error = ASTContext::GE_Missing_ucontext;
7698 return QualType();
7699 }
7700 break;
Eli Friedman6902e412012-11-27 02:58:24 +00007701 case 'p':
7702 Type = Context.getProcessIDType();
7703 break;
Mike Stump782fa302009-07-28 02:25:19 +00007704 }
Mike Stump1eb44332009-09-09 15:08:12 +00007705
Chris Lattner33daae62010-10-01 22:42:38 +00007706 // If there are modifiers and if we're allowed to parse them, go for it.
7707 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00007708 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00007709 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00007710 default: Done = true; --Str; break;
7711 case '*':
7712 case '&': {
7713 // Both pointers and references can have their pointee types
7714 // qualified with an address space.
7715 char *End;
7716 unsigned AddrSpace = strtoul(Str, &End, 10);
7717 if (End != Str && AddrSpace != 0) {
7718 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7719 Str = End;
7720 }
7721 if (c == '*')
7722 Type = Context.getPointerType(Type);
7723 else
7724 Type = Context.getLValueReferenceType(Type);
7725 break;
7726 }
7727 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7728 case 'C':
7729 Type = Type.withConst();
7730 break;
7731 case 'D':
7732 Type = Context.getVolatileType(Type);
7733 break;
Ted Kremenek18932a02012-01-20 21:40:12 +00007734 case 'R':
7735 Type = Type.withRestrict();
7736 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007737 }
7738 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00007739
Chris Lattner14e0e742010-10-01 22:53:11 +00007740 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00007741 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00007742
Chris Lattner86df27b2009-06-14 00:45:47 +00007743 return Type;
7744}
7745
7746/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00007747QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00007748 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00007749 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00007750 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00007751
Chris Lattner5f9e2722011-07-23 10:55:15 +00007752 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00007753
Chris Lattner14e0e742010-10-01 22:53:11 +00007754 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00007755 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00007756 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7757 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007758 if (Error != GE_None)
7759 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00007760
7761 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7762
Chris Lattner86df27b2009-06-14 00:45:47 +00007763 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00007764 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007765 if (Error != GE_None)
7766 return QualType();
7767
Chris Lattner14e0e742010-10-01 22:53:11 +00007768 // If this argument is required to be an IntegerConstantExpression and the
7769 // caller cares, fill in the bitmask we return.
7770 if (RequiresICE && IntegerConstantArgs)
7771 *IntegerConstantArgs |= 1 << ArgTypes.size();
7772
Chris Lattner86df27b2009-06-14 00:45:47 +00007773 // Do array -> pointer decay. The builtin should use the decayed type.
7774 if (Ty->isArrayType())
7775 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00007776
Chris Lattner86df27b2009-06-14 00:45:47 +00007777 ArgTypes.push_back(Ty);
7778 }
7779
7780 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7781 "'.' should only occur at end of builtin type list!");
7782
John McCall00ccbef2010-12-21 00:44:39 +00007783 FunctionType::ExtInfo EI;
7784 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7785
7786 bool Variadic = (TypeStr[0] == '.');
7787
7788 // We really shouldn't be making a no-proto type here, especially in C++.
7789 if (ArgTypes.empty() && Variadic)
7790 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00007791
John McCalle23cf432010-12-14 08:05:40 +00007792 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00007793 EPI.ExtInfo = EI;
7794 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00007795
Jordan Rosebea522f2013-03-08 21:51:21 +00007796 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00007797}
Eli Friedmana95d7572009-08-19 07:44:53 +00007798
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007799GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007800 if (!FD->isExternallyVisible())
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007801 return GVA_Internal;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007802
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007803 GVALinkage External = GVA_StrongExternal;
7804 switch (FD->getTemplateSpecializationKind()) {
7805 case TSK_Undeclared:
7806 case TSK_ExplicitSpecialization:
7807 External = GVA_StrongExternal;
7808 break;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007809
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007810 case TSK_ExplicitInstantiationDefinition:
7811 return GVA_ExplicitTemplateInstantiation;
7812
7813 case TSK_ExplicitInstantiationDeclaration:
7814 case TSK_ImplicitInstantiation:
7815 External = GVA_TemplateInstantiation;
7816 break;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007817 }
7818
7819 if (!FD->isInlined())
7820 return External;
7821
David Blaikie4e4d0842012-03-11 07:00:24 +00007822 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007823 // GNU or C99 inline semantics. Determine whether this symbol should be
7824 // externally visible.
7825 if (FD->isInlineDefinitionExternallyVisible())
7826 return External;
7827
7828 // C99 inline semantics, where the symbol is not externally visible.
7829 return GVA_C99Inline;
7830 }
7831
7832 // C++0x [temp.explicit]p9:
7833 // [ Note: The intent is that an inline function that is the subject of
7834 // an explicit instantiation declaration will still be implicitly
7835 // instantiated when used so that the body can be considered for
7836 // inlining, but that no out-of-line copy of the inline function would be
7837 // generated in the translation unit. -- end note ]
7838 if (FD->getTemplateSpecializationKind()
7839 == TSK_ExplicitInstantiationDeclaration)
7840 return GVA_C99Inline;
7841
7842 return GVA_CXXInline;
7843}
7844
7845GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007846 if (!VD->isExternallyVisible())
7847 return GVA_Internal;
7848
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007849 // If this is a static data member, compute the kind of template
7850 // specialization. Otherwise, this variable is not part of a
7851 // template.
7852 TemplateSpecializationKind TSK = TSK_Undeclared;
7853 if (VD->isStaticDataMember())
7854 TSK = VD->getTemplateSpecializationKind();
7855
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007856 switch (TSK) {
7857 case TSK_Undeclared:
7858 case TSK_ExplicitSpecialization:
7859 return GVA_StrongExternal;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007860
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007861 case TSK_ExplicitInstantiationDeclaration:
7862 llvm_unreachable("Variable should not be instantiated");
7863 // Fall through to treat this like any other instantiation.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007864
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007865 case TSK_ExplicitInstantiationDefinition:
7866 return GVA_ExplicitTemplateInstantiation;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007867
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007868 case TSK_ImplicitInstantiation:
7869 return GVA_TemplateInstantiation;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007870 }
Rafael Espindola77b50252013-05-13 14:05:53 +00007871
7872 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007873}
7874
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00007875bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007876 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7877 if (!VD->isFileVarDecl())
7878 return false;
Richard Smithf396ad92013-04-01 20:22:16 +00007879 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7880 // We never need to emit an uninstantiated function template.
7881 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7882 return false;
7883 } else
7884 return false;
7885
7886 // If this is a member of a class template, we do not need to emit it.
7887 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007888 return false;
7889
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007890 // Weak references don't produce any output by themselves.
7891 if (D->hasAttr<WeakRefAttr>())
7892 return false;
7893
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007894 // Aliases and used decls are required.
7895 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7896 return true;
7897
7898 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7899 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00007900 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00007901 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007902
7903 // Constructors and destructors are required.
7904 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7905 return true;
7906
John McCalld5617ee2013-01-25 22:31:03 +00007907 // The key function for a class is required. This rule only comes
7908 // into play when inline functions can be key functions, though.
7909 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7910 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7911 const CXXRecordDecl *RD = MD->getParent();
7912 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7913 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7914 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7915 return true;
7916 }
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007917 }
7918 }
7919
7920 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7921
7922 // static, static inline, always_inline, and extern inline functions can
7923 // always be deferred. Normal inline functions can be deferred in C99/C++.
7924 // Implicit template instantiations can also be deferred in C++.
7925 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev3a5aca82012-02-02 06:06:34 +00007926 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007927 return false;
7928 return true;
7929 }
Douglas Gregor94da1582011-09-10 00:22:34 +00007930
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007931 const VarDecl *VD = cast<VarDecl>(D);
7932 assert(VD->isFileVarDecl() && "Expected file scoped var");
7933
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007934 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7935 return false;
7936
Richard Smith5f9a7e32012-11-12 21:38:00 +00007937 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007938 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smith5f9a7e32012-11-12 21:38:00 +00007939 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7940 return true;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007941
Richard Smith5f9a7e32012-11-12 21:38:00 +00007942 // Variables that have destruction with side-effects are required.
7943 if (VD->getType().isDestructedType())
7944 return true;
7945
7946 // Variables that have initialization with side-effects are required.
7947 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7948 return true;
7949
7950 return false;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007951}
Charles Davis071cc7d2010-08-16 03:33:14 +00007952
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007953CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davisee743f92010-11-09 18:04:24 +00007954 // Pass through to the C++ ABI object
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007955 return ABI->getDefaultMethodCallConv(isVariadic);
7956}
7957
7958CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
John McCallb8b2c9d2013-01-25 22:30:49 +00007959 if (CC == CC_C && !LangOpts.MRTD &&
7960 getTargetInfo().getCXXABI().isMemberFunctionCCDefault())
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007961 return CC_Default;
7962 return CC;
Charles Davisee743f92010-11-09 18:04:24 +00007963}
7964
Jay Foad4ba2a172011-01-12 09:06:06 +00007965bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00007966 // Pass through to the C++ ABI object
7967 return ABI->isNearlyEmpty(RD);
7968}
7969
Peter Collingbourne14110472011-01-13 18:57:25 +00007970MangleContext *ASTContext::createMangleContext() {
John McCallb8b2c9d2013-01-25 22:30:49 +00007971 switch (Target->getCXXABI().getKind()) {
Tim Northoverc264e162013-01-31 12:13:10 +00007972 case TargetCXXABI::GenericAArch64:
John McCallb8b2c9d2013-01-25 22:30:49 +00007973 case TargetCXXABI::GenericItanium:
7974 case TargetCXXABI::GenericARM:
7975 case TargetCXXABI::iOS:
Peter Collingbourne14110472011-01-13 18:57:25 +00007976 return createItaniumMangleContext(*this, getDiagnostics());
John McCallb8b2c9d2013-01-25 22:30:49 +00007977 case TargetCXXABI::Microsoft:
Peter Collingbourne14110472011-01-13 18:57:25 +00007978 return createMicrosoftMangleContext(*this, getDiagnostics());
7979 }
David Blaikieb219cfc2011-09-23 05:06:16 +00007980 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00007981}
7982
Charles Davis071cc7d2010-08-16 03:33:14 +00007983CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00007984
7985size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00007986 return ASTRecordLayouts.getMemorySize()
7987 + llvm::capacity_in_bytes(ObjCLayouts)
7988 + llvm::capacity_in_bytes(KeyFunctions)
7989 + llvm::capacity_in_bytes(ObjCImpls)
7990 + llvm::capacity_in_bytes(BlockVarCopyInits)
7991 + llvm::capacity_in_bytes(DeclAttrs)
7992 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7993 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7994 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7995 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7996 + llvm::capacity_in_bytes(OverriddenMethods)
7997 + llvm::capacity_in_bytes(Types)
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007998 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet0d95f0d2011-08-14 14:28:49 +00007999 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00008000}
Ted Kremenekd211cb72011-10-06 05:00:56 +00008001
David Blaikie66cff722012-11-14 01:52:05 +00008002void ASTContext::addUnnamedTag(const TagDecl *Tag) {
8003 // FIXME: This mangling should be applied to function local classes too
8004 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl() ||
Rafael Espindola5bbb0582013-05-28 14:09:46 +00008005 !isa<CXXRecordDecl>(Tag->getParent()))
David Blaikie66cff722012-11-14 01:52:05 +00008006 return;
8007
8008 std::pair<llvm::DenseMap<const DeclContext *, unsigned>::iterator, bool> P =
8009 UnnamedMangleContexts.insert(std::make_pair(Tag->getParent(), 0));
8010 UnnamedMangleNumbers.insert(std::make_pair(Tag, P.first->second++));
8011}
8012
8013int ASTContext::getUnnamedTagManglingNumber(const TagDecl *Tag) const {
8014 llvm::DenseMap<const TagDecl *, unsigned>::const_iterator I =
8015 UnnamedMangleNumbers.find(Tag);
8016 return I != UnnamedMangleNumbers.end() ? I->second : -1;
8017}
8018
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00008019unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
8020 CXXRecordDecl *Lambda = CallOperator->getParent();
8021 return LambdaMangleContexts[Lambda->getDeclContext()]
8022 .getManglingNumber(CallOperator);
8023}
8024
8025
Ted Kremenekd211cb72011-10-06 05:00:56 +00008026void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8027 ParamIndices[D] = index;
8028}
8029
8030unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8031 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8032 assert(I != ParamIndices.end() &&
8033 "ParmIndices lacks entry set by ParmVarDecl");
8034 return I->second;
8035}
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00008036
Richard Smith211c8dd2013-06-05 00:46:14 +00008037APValue *
8038ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8039 bool MayCreate) {
8040 assert(E && E->getStorageDuration() == SD_Static &&
8041 "don't need to cache the computed value for this temporary");
8042 if (MayCreate)
8043 return &MaterializedTemporaryValues[E];
8044
8045 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8046 MaterializedTemporaryValues.find(E);
8047 return I == MaterializedTemporaryValues.end() ? 0 : &I->second;
8048}
8049
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00008050bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8051 const llvm::Triple &T = getTargetInfo().getTriple();
8052 if (!T.isOSDarwin())
8053 return false;
8054
8055 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8056 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8057 uint64_t Size = sizeChars.getQuantity();
8058 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8059 unsigned Align = alignChars.getQuantity();
8060 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8061 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8062}
Reid Klecknercff15122013-06-17 12:56:08 +00008063
8064namespace {
8065
8066 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8067 /// parents as defined by the \c RecursiveASTVisitor.
8068 ///
8069 /// Note that the relationship described here is purely in terms of AST
8070 /// traversal - there are other relationships (for example declaration context)
8071 /// in the AST that are better modeled by special matchers.
8072 ///
8073 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8074 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8075
8076 public:
8077 /// \brief Builds and returns the translation unit's parent map.
8078 ///
8079 /// The caller takes ownership of the returned \c ParentMap.
8080 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8081 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8082 Visitor.TraverseDecl(&TU);
8083 return Visitor.Parents;
8084 }
8085
8086 private:
8087 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8088
8089 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8090 }
8091
8092 bool shouldVisitTemplateInstantiations() const {
8093 return true;
8094 }
8095 bool shouldVisitImplicitCode() const {
8096 return true;
8097 }
8098 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8099 // are not triggered during data recursion.
8100 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8101 return false;
8102 }
8103
8104 template <typename T>
8105 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
8106 if (Node == NULL)
8107 return true;
8108 if (ParentStack.size() > 0)
8109 // FIXME: Currently we add the same parent multiple times, for example
8110 // when we visit all subexpressions of template instantiations; this is
8111 // suboptimal, bug benign: the only way to visit those is with
8112 // hasAncestor / hasParent, and those do not create new matches.
8113 // The plan is to enable DynTypedNode to be storable in a map or hash
8114 // map. The main problem there is to implement hash functions /
8115 // comparison operators for all types that DynTypedNode supports that
8116 // do not have pointer identity.
8117 (*Parents)[Node].push_back(ParentStack.back());
8118 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8119 bool Result = (this ->* traverse) (Node);
8120 ParentStack.pop_back();
8121 return Result;
8122 }
8123
8124 bool TraverseDecl(Decl *DeclNode) {
8125 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8126 }
8127
8128 bool TraverseStmt(Stmt *StmtNode) {
8129 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8130 }
8131
8132 ASTContext::ParentMap *Parents;
8133 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8134
8135 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8136 };
8137
8138} // end namespace
8139
8140ASTContext::ParentVector
8141ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8142 assert(Node.getMemoizationData() &&
8143 "Invariant broken: only nodes that support memoization may be "
8144 "used in the parent map.");
8145 if (!AllParents) {
8146 // We always need to run over the whole translation unit, as
8147 // hasAncestor can escape any subtree.
8148 AllParents.reset(
8149 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8150 }
8151 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8152 if (I == AllParents->end()) {
8153 return ParentVector();
8154 }
8155 return I->second;
8156}