blob: fff2f82e23bf0e9dc98b4159ad74beb0eb55762a [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000015#include "CXXABI.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000016#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000018#include "clang/AST/CharUnits.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000019#include "clang/AST/Comment.h"
Dmitri Gribenkoaa580812012-08-09 00:03:17 +000020#include "clang/AST/CommentCommandTraits.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000021#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000022#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000023#include "clang/AST/DeclTemplate.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000024#include "clang/AST/Expr.h"
John McCallea1471e2010-05-20 01:18:31 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000026#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000027#include "clang/AST/Mangle.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000028#include "clang/AST/RecordLayout.h"
29#include "clang/AST/TypeLoc.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000030#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000031#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000032#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000033#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000034#include "llvm/ADT/StringExtras.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000035#include "llvm/Support/Capacity.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000036#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000037#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +000038#include <map>
Anders Carlsson29445a02009-07-18 21:19:52 +000039
Reid Spencer5f016e22007-07-11 17:01:13 +000040using namespace clang;
41
Douglas Gregor18274032010-07-03 00:47:00 +000042unsigned ASTContext::NumImplicitDefaultConstructors;
43unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000044unsigned ASTContext::NumImplicitCopyConstructors;
45unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000046unsigned ASTContext::NumImplicitMoveConstructors;
47unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000048unsigned ASTContext::NumImplicitCopyAssignmentOperators;
49unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000050unsigned ASTContext::NumImplicitMoveAssignmentOperators;
51unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000052unsigned ASTContext::NumImplicitDestructors;
53unsigned ASTContext::NumImplicitDestructorsDeclared;
54
Reid Spencer5f016e22007-07-11 17:01:13 +000055enum FloatingRank {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +000056 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Reid Spencer5f016e22007-07-11 17:01:13 +000057};
58
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000059RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +000060 if (!CommentsLoaded && ExternalSource) {
61 ExternalSource->ReadComments();
62 CommentsLoaded = true;
63 }
64
65 assert(D);
66
Dmitri Gribenkoc3fee352012-06-28 16:19:39 +000067 // User can not attach documentation to implicit declarations.
68 if (D->isImplicit())
69 return NULL;
70
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +000071 // User can not attach documentation to implicit instantiations.
72 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
73 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
74 return NULL;
75 }
76
Dmitri Gribenkodce750b2012-08-20 22:36:31 +000077 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
78 if (VD->isStaticDataMember() &&
79 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
80 return NULL;
81 }
82
83 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
84 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
85 return NULL;
86 }
87
88 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
89 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
90 return NULL;
91 }
92
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +000093 // TODO: handle comments for function parameters properly.
94 if (isa<ParmVarDecl>(D))
95 return NULL;
96
Dmitri Gribenko96b09862012-07-31 22:37:06 +000097 // TODO: we could look up template parameter documentation in the template
98 // documentation.
99 if (isa<TemplateTypeParmDecl>(D) ||
100 isa<NonTypeTemplateParmDecl>(D) ||
101 isa<TemplateTemplateParmDecl>(D))
102 return NULL;
103
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000104 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000105
106 // If there are no comments anywhere, we won't find anything.
107 if (RawComments.empty())
108 return NULL;
109
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000110 // Find declaration location.
111 // For Objective-C declarations we generally don't expect to have multiple
112 // declarators, thus use declaration starting location as the "declaration
113 // location".
114 // For all other declarations multiple declarators are used quite frequently,
115 // so we use the location of the identifier as the "declaration location".
116 SourceLocation DeclLoc;
117 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko96b09862012-07-31 22:37:06 +0000118 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +0000119 isa<RedeclarableTemplateDecl>(D) ||
120 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000121 DeclLoc = D->getLocStart();
122 else
123 DeclLoc = D->getLocation();
124
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000125 // If the declaration doesn't map directly to a location in a file, we
126 // can't find the comment.
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000127 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
128 return NULL;
129
130 // Find the comment that occurs just after this declaration.
Dmitri Gribenkoa444f182012-07-17 22:01:09 +0000131 ArrayRef<RawComment *>::iterator Comment;
132 {
133 // When searching for comments during parsing, the comment we are looking
134 // for is usually among the last two comments we parsed -- check them
135 // first.
136 RawComment CommentAtDeclLoc(SourceMgr, SourceRange(DeclLoc));
137 BeforeThanCompare<RawComment> Compare(SourceMgr);
138 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
139 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
140 if (!Found && RawComments.size() >= 2) {
141 MaybeBeforeDecl--;
142 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
143 }
144
145 if (Found) {
146 Comment = MaybeBeforeDecl + 1;
147 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
148 &CommentAtDeclLoc, Compare));
149 } else {
150 // Slow path.
151 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
152 &CommentAtDeclLoc, Compare);
153 }
154 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000155
156 // Decompose the location for the declaration and find the beginning of the
157 // file buffer.
158 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
159
160 // First check whether we have a trailing comment.
161 if (Comment != RawComments.end() &&
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000162 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Dmitri Gribenko9c006762012-07-06 23:27:33 +0000163 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000164 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000165 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000166 // Check that Doxygen trailing comment comes after the declaration, starts
167 // on the same line and in the same file as the declaration.
168 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
169 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
170 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
171 CommentBeginDecomp.second)) {
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000172 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000173 }
174 }
175
176 // The comment just after the declaration was not a trailing comment.
177 // Let's look at the previous comment.
178 if (Comment == RawComments.begin())
179 return NULL;
180 --Comment;
181
182 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000183 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000184 return NULL;
185
186 // Decompose the end of the comment.
187 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000188 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000189
190 // If the comment and the declaration aren't in the same file, then they
191 // aren't related.
192 if (DeclLocDecomp.first != CommentEndDecomp.first)
193 return NULL;
194
195 // Get the corresponding buffer.
196 bool Invalid = false;
197 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
198 &Invalid).data();
199 if (Invalid)
200 return NULL;
201
202 // Extract text between the comment and declaration.
203 StringRef Text(Buffer + CommentEndDecomp.second,
204 DeclLocDecomp.second - CommentEndDecomp.second);
205
Dmitri Gribenko8bdb58a2012-06-27 23:43:37 +0000206 // There should be no other declarations or preprocessor directives between
207 // comment and declaration.
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000208 if (Text.find_first_of(",;{}#@") != StringRef::npos)
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000209 return NULL;
210
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000211 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000212}
213
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000214namespace {
215/// If we have a 'templated' declaration for a template, adjust 'D' to
216/// refer to the actual template.
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000217/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000218const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregorcd81df22012-08-13 16:37:30 +0000219 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000220 // Is this function declaration part of a function template?
Douglas Gregorcd81df22012-08-13 16:37:30 +0000221 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000222 return FTD;
223
224 // Nothing to do if function is not an implicit instantiation.
225 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
226 return D;
227
228 // Function is an implicit instantiation of a function template?
229 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
230 return FTD;
231
232 // Function is instantiated from a member definition of a class template?
233 if (const FunctionDecl *MemberDecl =
234 FD->getInstantiatedFromMemberFunction())
235 return MemberDecl;
236
237 return D;
Douglas Gregorcd81df22012-08-13 16:37:30 +0000238 }
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000239 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
240 // Static data member is instantiated from a member definition of a class
241 // template?
242 if (VD->isStaticDataMember())
243 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
244 return MemberDecl;
245
246 return D;
247 }
248 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
249 // Is this class declaration part of a class template?
250 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
251 return CTD;
252
253 // Class is an implicit instantiation of a class template or partial
254 // specialization?
255 if (const ClassTemplateSpecializationDecl *CTSD =
256 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
257 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
258 return D;
259 llvm::PointerUnion<ClassTemplateDecl *,
260 ClassTemplatePartialSpecializationDecl *>
261 PU = CTSD->getSpecializedTemplateOrPartial();
262 return PU.is<ClassTemplateDecl*>() ?
263 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
264 static_cast<const Decl*>(
265 PU.get<ClassTemplatePartialSpecializationDecl *>());
266 }
267
268 // Class is instantiated from a member definition of a class template?
269 if (const MemberSpecializationInfo *Info =
270 CRD->getMemberSpecializationInfo())
271 return Info->getInstantiatedFrom();
272
273 return D;
274 }
275 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
276 // Enum is instantiated from a member definition of a class template?
277 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
278 return MemberDecl;
279
280 return D;
281 }
282 // FIXME: Adjust alias templates?
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000283 return D;
284}
285} // unnamed namespace
286
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000287const RawComment *ASTContext::getRawCommentForAnyRedecl(
288 const Decl *D,
289 const Decl **OriginalDecl) const {
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000290 D = adjustDeclToTemplate(D);
Douglas Gregorcd81df22012-08-13 16:37:30 +0000291
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000292 // Check whether we have cached a comment for this declaration already.
293 {
294 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
295 RedeclComments.find(D);
296 if (Pos != RedeclComments.end()) {
297 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000298 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
299 if (OriginalDecl)
300 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000301 return Raw.getRaw();
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000302 }
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000303 }
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000304 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000305
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000306 // Search for comments attached to declarations in the redeclaration chain.
307 const RawComment *RC = NULL;
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000308 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000309 for (Decl::redecl_iterator I = D->redecls_begin(),
310 E = D->redecls_end();
311 I != E; ++I) {
312 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
313 RedeclComments.find(*I);
314 if (Pos != RedeclComments.end()) {
315 const RawCommentAndCacheFlags &Raw = Pos->second;
316 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
317 RC = Raw.getRaw();
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000318 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000319 break;
320 }
321 } else {
322 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000323 OriginalDeclForRC = *I;
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000324 RawCommentAndCacheFlags Raw;
325 if (RC) {
326 Raw.setRaw(RC);
327 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
328 } else
329 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000330 Raw.setOriginalDecl(*I);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000331 RedeclComments[*I] = Raw;
332 if (RC)
333 break;
334 }
335 }
336
Dmitri Gribenko8376f592012-06-28 16:25:36 +0000337 // If we found a comment, it should be a documentation comment.
338 assert(!RC || RC->isDocumentation());
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000339
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000340 if (OriginalDecl)
341 *OriginalDecl = OriginalDeclForRC;
342
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000343 // Update cache for every declaration in the redeclaration chain.
344 RawCommentAndCacheFlags Raw;
345 Raw.setRaw(RC);
346 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000347 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000348
349 for (Decl::redecl_iterator I = D->redecls_begin(),
350 E = D->redecls_end();
351 I != E; ++I) {
352 RawCommentAndCacheFlags &R = RedeclComments[*I];
353 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
354 R = Raw;
355 }
356
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000357 return RC;
358}
359
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000360static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
361 SmallVectorImpl<const NamedDecl *> &Redeclared) {
362 const DeclContext *DC = ObjCMethod->getDeclContext();
363 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
364 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
365 if (!ID)
366 return;
367 // Add redeclared method here.
Douglas Gregord3297242013-01-16 23:00:23 +0000368 for (ObjCInterfaceDecl::known_extensions_iterator
369 Ext = ID->known_extensions_begin(),
370 ExtEnd = ID->known_extensions_end();
371 Ext != ExtEnd; ++Ext) {
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000372 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregord3297242013-01-16 23:00:23 +0000373 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000374 ObjCMethod->isInstanceMethod()))
375 Redeclared.push_back(RedeclaredMethod);
376 }
377 }
378}
379
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000380comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
381 const Decl *D) const {
382 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
383 ThisDeclInfo->CommentDecl = D;
384 ThisDeclInfo->IsFilled = false;
385 ThisDeclInfo->fill();
386 ThisDeclInfo->CommentDecl = FC->getDecl();
387 comments::FullComment *CFC =
388 new (*this) comments::FullComment(FC->getBlocks(),
389 ThisDeclInfo);
390 return CFC;
391
392}
393
Dmitri Gribenko19523542012-09-29 11:40:46 +0000394comments::FullComment *ASTContext::getCommentForDecl(
395 const Decl *D,
396 const Preprocessor *PP) const {
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000397 D = adjustDeclToTemplate(D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000398
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000399 const Decl *Canonical = D->getCanonicalDecl();
400 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
401 ParsedComments.find(Canonical);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000402
403 if (Pos != ParsedComments.end()) {
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000404 if (Canonical != D) {
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000405 comments::FullComment *FC = Pos->second;
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000406 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000407 return CFC;
408 }
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000409 return Pos->second;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000410 }
411
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000412 const Decl *OriginalDecl;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000413
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000414 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000415 if (!RC) {
416 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko1e905da2012-11-03 14:24:57 +0000417 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanianc328d9c2013-01-12 00:28:34 +0000418 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
419 if (OMD && OMD->isPropertyAccessor()) {
420 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl()) {
421 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP)) {
422 comments::FullComment *CFC = cloneFullComment(FC, D);
423 return CFC;
424 }
425 }
426 }
427 if (OMD)
Dmitri Gribenko1e905da2012-11-03 14:24:57 +0000428 addRedeclaredMethods(OMD, Overridden);
429 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
430 for (unsigned i = 0, e = Overridden.size(); i < e; i++) {
431 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP)) {
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000432 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000433 return CFC;
434 }
435 }
436 }
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000437 return NULL;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000438 }
439
Dmitri Gribenko4b41c652012-08-22 18:12:19 +0000440 // If the RawComment was attached to other redeclaration of this Decl, we
441 // should parse the comment in context of that other Decl. This is important
442 // because comments can contain references to parameter names which can be
443 // different across redeclarations.
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000444 if (D != OriginalDecl)
Dmitri Gribenko19523542012-09-29 11:40:46 +0000445 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000446
Dmitri Gribenko19523542012-09-29 11:40:46 +0000447 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000448 ParsedComments[Canonical] = FC;
449 return FC;
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000450}
451
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000452void
453ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
454 TemplateTemplateParmDecl *Parm) {
455 ID.AddInteger(Parm->getDepth());
456 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +0000457 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000458
459 TemplateParameterList *Params = Parm->getTemplateParameters();
460 ID.AddInteger(Params->size());
461 for (TemplateParameterList::const_iterator P = Params->begin(),
462 PEnd = Params->end();
463 P != PEnd; ++P) {
464 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
465 ID.AddInteger(0);
466 ID.AddBoolean(TTP->isParameterPack());
467 continue;
468 }
469
470 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
471 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000472 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000473 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000474 if (NTTP->isExpandedParameterPack()) {
475 ID.AddBoolean(true);
476 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000477 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
478 QualType T = NTTP->getExpansionType(I);
479 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
480 }
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000481 } else
482 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000483 continue;
484 }
485
486 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
487 ID.AddInteger(2);
488 Profile(ID, TTP);
489 }
490}
491
492TemplateTemplateParmDecl *
493ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +0000494 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000495 // Check if we already have a canonical template template parameter.
496 llvm::FoldingSetNodeID ID;
497 CanonicalTemplateTemplateParm::Profile(ID, TTP);
498 void *InsertPos = 0;
499 CanonicalTemplateTemplateParm *Canonical
500 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
501 if (Canonical)
502 return Canonical->getParam();
503
504 // Build a canonical template parameter list.
505 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000506 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000507 CanonParams.reserve(Params->size());
508 for (TemplateParameterList::const_iterator P = Params->begin(),
509 PEnd = Params->end();
510 P != PEnd; ++P) {
511 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
512 CanonParams.push_back(
513 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000514 SourceLocation(),
515 SourceLocation(),
516 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000517 TTP->getIndex(), 0, false,
518 TTP->isParameterPack()));
519 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000520 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
521 QualType T = getCanonicalType(NTTP->getType());
522 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
523 NonTypeTemplateParmDecl *Param;
524 if (NTTP->isExpandedParameterPack()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000525 SmallVector<QualType, 2> ExpandedTypes;
526 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000527 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
528 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
529 ExpandedTInfos.push_back(
530 getTrivialTypeSourceInfo(ExpandedTypes.back()));
531 }
532
533 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000534 SourceLocation(),
535 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000536 NTTP->getDepth(),
537 NTTP->getPosition(), 0,
538 T,
539 TInfo,
540 ExpandedTypes.data(),
541 ExpandedTypes.size(),
542 ExpandedTInfos.data());
543 } else {
544 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000545 SourceLocation(),
546 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000547 NTTP->getDepth(),
548 NTTP->getPosition(), 0,
549 T,
550 NTTP->isParameterPack(),
551 TInfo);
552 }
553 CanonParams.push_back(Param);
554
555 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000556 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
557 cast<TemplateTemplateParmDecl>(*P)));
558 }
559
560 TemplateTemplateParmDecl *CanonTTP
561 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
562 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000563 TTP->getPosition(),
564 TTP->isParameterPack(),
565 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000566 TemplateParameterList::Create(*this, SourceLocation(),
567 SourceLocation(),
568 CanonParams.data(),
569 CanonParams.size(),
570 SourceLocation()));
571
572 // Get the new insert position for the node we care about.
573 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
574 assert(Canonical == 0 && "Shouldn't be in the map!");
575 (void)Canonical;
576
577 // Create the canonical template template parameter entry.
578 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
579 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
580 return CanonTTP;
581}
582
Charles Davis071cc7d2010-08-16 03:33:14 +0000583CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000584 if (!LangOpts.CPlusPlus) return 0;
585
Charles Davis20cf7172010-08-19 02:18:14 +0000586 switch (T.getCXXABI()) {
John McCallee79a4c2010-08-21 22:46:04 +0000587 case CXXABI_ARM:
588 return CreateARMCXXABI(*this);
589 case CXXABI_Itanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000590 return CreateItaniumCXXABI(*this);
Charles Davis20cf7172010-08-19 02:18:14 +0000591 case CXXABI_Microsoft:
592 return CreateMicrosoftCXXABI(*this);
593 }
David Blaikie7530c032012-01-17 06:56:22 +0000594 llvm_unreachable("Invalid CXXABI type!");
Charles Davis071cc7d2010-08-16 03:33:14 +0000595}
596
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000597static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000598 const LangOptions &LOpts) {
599 if (LOpts.FakeAddressSpaceMap) {
600 // The fake address space map must have a distinct entry for each
601 // language-specific address space.
602 static const unsigned FakeAddrSpaceMap[] = {
603 1, // opencl_global
604 2, // opencl_local
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +0000605 3, // opencl_constant
606 4, // cuda_device
607 5, // cuda_constant
608 6 // cuda_shared
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000609 };
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000610 return &FakeAddrSpaceMap;
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000611 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000612 return &T.getAddressSpaceMap();
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000613 }
614}
615
Douglas Gregor3e3cd932011-09-01 20:23:19 +0000616ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000617 const TargetInfo *t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000618 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000619 Builtin::Context &builtins,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000620 unsigned size_reserve,
621 bool DelayInitialization)
622 : FunctionProtoTypes(this_()),
623 TemplateSpecializationTypes(this_()),
624 DependentTemplateSpecializationTypes(this_()),
625 SubstTemplateTemplateParmPacks(this_()),
626 GlobalNestedNameSpecifier(0),
627 Int128Decl(0), UInt128Decl(0),
Meador Ingec5613b22012-06-16 03:34:49 +0000628 BuiltinVaListDecl(0),
Douglas Gregora6ea10e2012-01-17 18:09:05 +0000629 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanian96171302012-08-30 18:49:41 +0000630 BOOLDecl(0),
Douglas Gregore97179c2011-09-08 01:46:34 +0000631 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000632 FILEDecl(0),
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +0000633 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
634 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
635 cudaConfigureCallDecl(0),
Douglas Gregore6649772011-12-03 00:30:27 +0000636 NullTypeSourceInfo(QualType()),
637 FirstLocalImport(), LastLocalImport(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000638 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor30c42402011-09-27 22:38:19 +0000639 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000640 Idents(idents), Selectors(sels),
641 BuiltinInfo(builtins),
642 DeclarationNames(*this),
Douglas Gregor30c42402011-09-27 22:38:19 +0000643 ExternalSource(0), Listener(0),
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000644 Comments(SM), CommentsLoaded(false),
Dmitri Gribenkoe4330a32012-09-10 20:32:42 +0000645 CommentCommandTraits(BumpAlloc),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000646 LastSDM(0, 0),
Fariborz Jahanianf7992132013-01-04 18:45:40 +0000647 UniqueBlockByRefTypeID(0)
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000648{
Mike Stump1eb44332009-09-09 15:08:12 +0000649 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000650 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000651
652 if (!DelayInitialization) {
653 assert(t && "No target supplied for ASTContext initialization");
654 InitBuiltinTypes(*t);
655 }
Daniel Dunbare91593e2008-08-11 04:54:23 +0000656}
657
Reid Spencer5f016e22007-07-11 17:01:13 +0000658ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000659 // Release the DenseMaps associated with DeclContext objects.
660 // FIXME: Is this the ideal solution?
661 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000662
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000663 // Call all of the deallocation functions.
664 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
665 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000666
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000667 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000668 // because they can contain DenseMaps.
669 for (llvm::DenseMap<const ObjCContainerDecl*,
670 const ASTRecordLayout*>::iterator
671 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
672 // Increment in loop to prevent using deallocated memory.
673 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
674 R->Destroy(*this);
675
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000676 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
677 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
678 // Increment in loop to prevent using deallocated memory.
679 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
680 R->Destroy(*this);
681 }
Douglas Gregor63200642010-08-30 16:49:28 +0000682
683 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
684 AEnd = DeclAttrs.end();
685 A != AEnd; ++A)
686 A->second->~AttrVec();
687}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000688
Douglas Gregor00545312010-05-23 18:26:36 +0000689void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
690 Deallocations.push_back(std::make_pair(Callback, Data));
691}
692
Mike Stump1eb44332009-09-09 15:08:12 +0000693void
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000694ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000695 ExternalSource.reset(Source.take());
696}
697
Reid Spencer5f016e22007-07-11 17:01:13 +0000698void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000699 llvm::errs() << "\n*** AST Context Stats:\n";
700 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000701
Douglas Gregordbe833d2009-05-26 14:40:08 +0000702 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000703#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000704#define ABSTRACT_TYPE(Name, Parent)
705#include "clang/AST/TypeNodes.def"
706 0 // Extra
707 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000708
Reid Spencer5f016e22007-07-11 17:01:13 +0000709 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
710 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000711 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000712 }
713
Douglas Gregordbe833d2009-05-26 14:40:08 +0000714 unsigned Idx = 0;
715 unsigned TotalBytes = 0;
716#define TYPE(Name, Parent) \
717 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000718 llvm::errs() << " " << counts[Idx] << " " << #Name \
719 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000720 TotalBytes += counts[Idx] * sizeof(Name##Type); \
721 ++Idx;
722#define ABSTRACT_TYPE(Name, Parent)
723#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000724
Chandler Carruthcd92a652011-07-04 05:32:14 +0000725 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
726
Douglas Gregor4923aa22010-07-02 20:37:36 +0000727 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000728 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
729 << NumImplicitDefaultConstructors
730 << " implicit default constructors created\n";
731 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
732 << NumImplicitCopyConstructors
733 << " implicit copy constructors created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000734 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000735 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
736 << NumImplicitMoveConstructors
737 << " implicit move constructors created\n";
738 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
739 << NumImplicitCopyAssignmentOperators
740 << " implicit copy assignment operators created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000741 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000742 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
743 << NumImplicitMoveAssignmentOperators
744 << " implicit move assignment operators created\n";
745 llvm::errs() << NumImplicitDestructorsDeclared << "/"
746 << NumImplicitDestructors
747 << " implicit destructors created\n";
748
Douglas Gregor2cf26342009-04-09 22:27:44 +0000749 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000750 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000751 ExternalSource->PrintStats();
752 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000753
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000754 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000755}
756
Douglas Gregor772eeae2011-08-12 06:49:56 +0000757TypedefDecl *ASTContext::getInt128Decl() const {
758 if (!Int128Decl) {
759 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
760 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
761 getTranslationUnitDecl(),
762 SourceLocation(),
763 SourceLocation(),
764 &Idents.get("__int128_t"),
765 TInfo);
766 }
767
768 return Int128Decl;
769}
770
771TypedefDecl *ASTContext::getUInt128Decl() const {
772 if (!UInt128Decl) {
773 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
774 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
775 getTranslationUnitDecl(),
776 SourceLocation(),
777 SourceLocation(),
778 &Idents.get("__uint128_t"),
779 TInfo);
780 }
781
782 return UInt128Decl;
783}
Reid Spencer5f016e22007-07-11 17:01:13 +0000784
John McCalle27ec8a2009-10-23 23:03:21 +0000785void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000786 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000787 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000788 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000789}
790
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000791void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
792 assert((!this->Target || this->Target == &Target) &&
793 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000794 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000795
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000796 this->Target = &Target;
797
798 ABI.reset(createCXXABI(Target));
799 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
800
Reid Spencer5f016e22007-07-11 17:01:13 +0000801 // C99 6.2.5p19.
802 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000803
Reid Spencer5f016e22007-07-11 17:01:13 +0000804 // C99 6.2.5p2.
805 InitBuiltinType(BoolTy, BuiltinType::Bool);
806 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000807 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000808 InitBuiltinType(CharTy, BuiltinType::Char_S);
809 else
810 InitBuiltinType(CharTy, BuiltinType::Char_U);
811 // C99 6.2.5p4.
812 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
813 InitBuiltinType(ShortTy, BuiltinType::Short);
814 InitBuiltinType(IntTy, BuiltinType::Int);
815 InitBuiltinType(LongTy, BuiltinType::Long);
816 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000817
Reid Spencer5f016e22007-07-11 17:01:13 +0000818 // C99 6.2.5p6.
819 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
820 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
821 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
822 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
823 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000824
Reid Spencer5f016e22007-07-11 17:01:13 +0000825 // C99 6.2.5p10.
826 InitBuiltinType(FloatTy, BuiltinType::Float);
827 InitBuiltinType(DoubleTy, BuiltinType::Double);
828 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000829
Chris Lattner2df9ced2009-04-30 02:43:43 +0000830 // GNU extension, 128-bit integers.
831 InitBuiltinType(Int128Ty, BuiltinType::Int128);
832 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
833
Abramo Bagnarae75bb612012-09-09 10:13:32 +0000834 if (LangOpts.CPlusPlus && LangOpts.WChar) { // C++ 3.9.1p5
Eli Friedmand3d77cd2011-04-30 19:24:24 +0000835 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattner3f59c972010-12-25 23:25:43 +0000836 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
837 else // -fshort-wchar makes wchar_t be unsigned.
838 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
Abramo Bagnarae75bb612012-09-09 10:13:32 +0000839 } else // C99 (or C++ using -fno-wchar)
Chris Lattner3a250322009-02-26 23:43:47 +0000840 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000841
James Molloy392da482012-05-04 10:55:22 +0000842 WIntTy = getFromTargetType(Target.getWIntType());
843
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000844 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
845 InitBuiltinType(Char16Ty, BuiltinType::Char16);
846 else // C99
847 Char16Ty = getFromTargetType(Target.getChar16Type());
848
849 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
850 InitBuiltinType(Char32Ty, BuiltinType::Char32);
851 else // C99
852 Char32Ty = getFromTargetType(Target.getChar32Type());
853
Douglas Gregor898574e2008-12-05 23:32:09 +0000854 // Placeholder type for type-dependent expressions whose type is
855 // completely unknown. No code should ever check a type against
856 // DependentTy and users should never see it; however, it is here to
857 // help diagnose failures to properly check for type-dependent
858 // expressions.
859 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000860
John McCall2a984ca2010-10-12 00:20:44 +0000861 // Placeholder type for functions.
862 InitBuiltinType(OverloadTy, BuiltinType::Overload);
863
John McCall864c0412011-04-26 20:42:42 +0000864 // Placeholder type for bound members.
865 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
866
John McCall3c3b7f92011-10-25 17:37:35 +0000867 // Placeholder type for pseudo-objects.
868 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
869
John McCall1de4d4e2011-04-07 08:22:57 +0000870 // "any" type; useful for debugger-like clients.
871 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
872
John McCall0ddaeb92011-10-17 18:09:15 +0000873 // Placeholder type for unbridged ARC casts.
874 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
875
Eli Friedmana6c66ce2012-08-31 00:14:07 +0000876 // Placeholder type for builtin functions.
877 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
878
Reid Spencer5f016e22007-07-11 17:01:13 +0000879 // C99 6.2.5p11.
880 FloatComplexTy = getComplexType(FloatTy);
881 DoubleComplexTy = getComplexType(DoubleTy);
882 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000883
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000884 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000885 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
886 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000887 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeib13621d2012-12-18 14:38:23 +0000888
889 if (LangOpts.OpenCL) {
890 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
891 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
892 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
893 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
894 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
895 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000896
897 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeib13621d2012-12-18 14:38:23 +0000898 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000899
900 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian93a49942012-04-16 21:03:30 +0000901 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
902 SignedCharTy : BoolTy);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000903
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000904 ObjCConstantStringType = QualType();
Fariborz Jahanianf7992132013-01-04 18:45:40 +0000905
906 ObjCSuperType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000907
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000908 // void * type
909 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000910
911 // nullptr type (C++0x 2.14.7)
912 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000913
914 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
915 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingefb40e3f2012-07-01 15:57:25 +0000916
917 // Builtin type used to help define __builtin_va_list.
918 VaListTagTy = QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000919}
920
David Blaikied6471f72011-09-25 23:23:43 +0000921DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000922 return SourceMgr.getDiagnostics();
923}
924
Douglas Gregor63200642010-08-30 16:49:28 +0000925AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
926 AttrVec *&Result = DeclAttrs[D];
927 if (!Result) {
928 void *Mem = Allocate(sizeof(AttrVec));
929 Result = new (Mem) AttrVec;
930 }
931
932 return *Result;
933}
934
935/// \brief Erase the attributes corresponding to the given declaration.
936void ASTContext::eraseDeclAttrs(const Decl *D) {
937 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
938 if (Pos != DeclAttrs.end()) {
939 Pos->second->~AttrVec();
940 DeclAttrs.erase(Pos);
941 }
942}
943
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000944MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000945ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000946 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000947 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000948 = InstantiatedFromStaticDataMember.find(Var);
949 if (Pos == InstantiatedFromStaticDataMember.end())
950 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000951
Douglas Gregor7caa6822009-07-24 20:34:43 +0000952 return Pos->second;
953}
954
Mike Stump1eb44332009-09-09 15:08:12 +0000955void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000956ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000957 TemplateSpecializationKind TSK,
958 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000959 assert(Inst->isStaticDataMember() && "Not a static data member");
960 assert(Tmpl->isStaticDataMember() && "Not a static data member");
961 assert(!InstantiatedFromStaticDataMember[Inst] &&
962 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000963 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000964 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000965}
966
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000967FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
968 const FunctionDecl *FD){
969 assert(FD && "Specialization is 0");
970 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000971 = ClassScopeSpecializationPattern.find(FD);
972 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000973 return 0;
974
975 return Pos->second;
976}
977
978void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
979 FunctionDecl *Pattern) {
980 assert(FD && "Specialization is 0");
981 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000982 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000983}
984
John McCall7ba107a2009-11-18 02:36:19 +0000985NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000986ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000987 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000988 = InstantiatedFromUsingDecl.find(UUD);
989 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000990 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000991
Anders Carlsson0d8df782009-08-29 19:37:28 +0000992 return Pos->second;
993}
994
995void
John McCalled976492009-12-04 22:46:56 +0000996ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
997 assert((isa<UsingDecl>(Pattern) ||
998 isa<UnresolvedUsingValueDecl>(Pattern) ||
999 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1000 "pattern decl is not a using decl");
1001 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1002 InstantiatedFromUsingDecl[Inst] = Pattern;
1003}
1004
1005UsingShadowDecl *
1006ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1007 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1008 = InstantiatedFromUsingShadowDecl.find(Inst);
1009 if (Pos == InstantiatedFromUsingShadowDecl.end())
1010 return 0;
1011
1012 return Pos->second;
1013}
1014
1015void
1016ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1017 UsingShadowDecl *Pattern) {
1018 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1019 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00001020}
1021
Anders Carlssond8b285f2009-09-01 04:26:58 +00001022FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1023 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1024 = InstantiatedFromUnnamedFieldDecl.find(Field);
1025 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1026 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001027
Anders Carlssond8b285f2009-09-01 04:26:58 +00001028 return Pos->second;
1029}
1030
1031void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1032 FieldDecl *Tmpl) {
1033 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1034 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1035 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1036 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +00001037
Anders Carlssond8b285f2009-09-01 04:26:58 +00001038 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1039}
1040
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +00001041bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
1042 const FieldDecl *LastFD) const {
1043 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001044 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +00001045}
1046
Fariborz Jahanian340fa242011-05-02 17:20:56 +00001047bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
1048 const FieldDecl *LastFD) const {
1049 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001050 FD->getBitWidthValue(*this) == 0 &&
1051 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +00001052}
1053
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001054bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
1055 const FieldDecl *LastFD) const {
1056 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001057 FD->getBitWidthValue(*this) &&
1058 LastFD->getBitWidthValue(*this));
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001059}
1060
Chad Rosierdd7fddb2011-08-04 23:34:15 +00001061bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001062 const FieldDecl *LastFD) const {
1063 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001064 LastFD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001065}
1066
Chad Rosierdd7fddb2011-08-04 23:34:15 +00001067bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001068 const FieldDecl *LastFD) const {
1069 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001070 FD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001071}
1072
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001073ASTContext::overridden_cxx_method_iterator
1074ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1075 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001076 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001077 if (Pos == OverriddenMethods.end())
1078 return 0;
1079
1080 return Pos->second.begin();
1081}
1082
1083ASTContext::overridden_cxx_method_iterator
1084ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1085 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001086 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001087 if (Pos == OverriddenMethods.end())
1088 return 0;
1089
1090 return Pos->second.end();
1091}
1092
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001093unsigned
1094ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1095 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001096 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001097 if (Pos == OverriddenMethods.end())
1098 return 0;
1099
1100 return Pos->second.size();
1101}
1102
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001103void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1104 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001105 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001106 OverriddenMethods[Method].push_back(Overridden);
1107}
1108
Dmitri Gribenko1e905da2012-11-03 14:24:57 +00001109void ASTContext::getOverriddenMethods(
1110 const NamedDecl *D,
1111 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001112 assert(D);
1113
1114 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisbc0a2bb2012-10-09 20:08:43 +00001115 Overridden.append(CXXMethod->begin_overridden_methods(),
1116 CXXMethod->end_overridden_methods());
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001117 return;
1118 }
1119
1120 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1121 if (!Method)
1122 return;
1123
Argyrios Kyrtzidis740ae672012-10-09 18:19:01 +00001124 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1125 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisbc0a2bb2012-10-09 20:08:43 +00001126 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001127}
1128
Douglas Gregore6649772011-12-03 00:30:27 +00001129void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1130 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1131 assert(!Import->isFromASTFile() && "Non-local import declaration");
1132 if (!FirstLocalImport) {
1133 FirstLocalImport = Import;
1134 LastLocalImport = Import;
1135 return;
1136 }
1137
1138 LastLocalImport->NextLocalImport = Import;
1139 LastLocalImport = Import;
1140}
1141
Chris Lattner464175b2007-07-18 17:52:12 +00001142//===----------------------------------------------------------------------===//
1143// Type Sizing and Analysis
1144//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +00001145
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001146/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1147/// scalar floating point type.
1148const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +00001149 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001150 assert(BT && "Not a floating point type!");
1151 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001152 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001153 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001154 case BuiltinType::Float: return Target->getFloatFormat();
1155 case BuiltinType::Double: return Target->getDoubleFormat();
1156 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001157 }
1158}
1159
Ken Dyck8b752f12010-01-27 17:10:57 +00001160/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +00001161/// specified decl. Note that bitfields do not have a valid alignment, so
1162/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +00001163/// If @p RefAsPointee, references are treated like their underlying type
1164/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +00001165CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001166 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +00001167
John McCall4081a5c2010-10-08 18:24:19 +00001168 bool UseAlignAttrOnly = false;
1169 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1170 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +00001171
John McCall4081a5c2010-10-08 18:24:19 +00001172 // __attribute__((aligned)) can increase or decrease alignment
1173 // *except* on a struct or struct member, where it only increases
1174 // alignment unless 'packed' is also specified.
1175 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +00001176 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +00001177 // ignore that possibility; Sema should diagnose it.
1178 if (isa<FieldDecl>(D)) {
1179 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1180 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1181 } else {
1182 UseAlignAttrOnly = true;
1183 }
1184 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +00001185 else if (isa<FieldDecl>(D))
1186 UseAlignAttrOnly =
1187 D->hasAttr<PackedAttr>() ||
1188 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +00001189
John McCallba4f5d52011-01-20 07:57:12 +00001190 // If we're using the align attribute only, just ignore everything
1191 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +00001192 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +00001193 // do nothing
1194
John McCall4081a5c2010-10-08 18:24:19 +00001195 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001196 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001197 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001198 if (RefAsPointee)
1199 T = RT->getPointeeType();
1200 else
1201 T = getPointerType(RT->getPointeeType());
1202 }
1203 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +00001204 // Adjust alignments of declarations with array type by the
1205 // large-array alignment on the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001206 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +00001207 const ArrayType *arrayType;
1208 if (MinWidth && (arrayType = getAsArrayType(T))) {
1209 if (isa<VariableArrayType>(arrayType))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001210 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall3b657512011-01-19 10:06:00 +00001211 else if (isa<ConstantArrayType>(arrayType) &&
1212 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001213 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +00001214
John McCall3b657512011-01-19 10:06:00 +00001215 // Walk through any array types while we're at it.
1216 T = getBaseElementType(arrayType);
1217 }
Chad Rosier9f1210c2011-07-26 07:03:04 +00001218 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedmandcdafb62009-02-22 02:56:25 +00001219 }
John McCallba4f5d52011-01-20 07:57:12 +00001220
1221 // Fields can be subject to extra alignment constraints, like if
1222 // the field is packed, the struct is packed, or the struct has a
1223 // a max-field-alignment constraint (#pragma pack). So calculate
1224 // the actual alignment of the field within the struct, and then
1225 // (as we're expected to) constrain that by the alignment of the type.
1226 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1227 // So calculate the alignment of the field.
1228 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1229
1230 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +00001231 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +00001232
1233 // Use the GCD of that and the offset within the record.
1234 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1235 if (offset > 0) {
1236 // Alignment is always a power of 2, so the GCD will be a power of 2,
1237 // which means we get to do this crazy thing instead of Euclid's.
1238 uint64_t lowBitOfOffset = offset & (~offset + 1);
1239 if (lowBitOfOffset < fieldAlign)
1240 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1241 }
1242
1243 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +00001244 }
Chris Lattneraf707ab2009-01-24 21:53:27 +00001245 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001246
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001247 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001248}
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001249
John McCall929bbfb2012-08-21 04:10:00 +00001250// getTypeInfoDataSizeInChars - Return the size of a type, in
1251// chars. If the type is a record, its data size is returned. This is
1252// the size of the memcpy that's performed when assigning this type
1253// using a trivial copy/move assignment operator.
1254std::pair<CharUnits, CharUnits>
1255ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1256 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1257
1258 // In C++, objects can sometimes be allocated into the tail padding
1259 // of a base-class subobject. We decide whether that's possible
1260 // during class layout, so here we can just trust the layout results.
1261 if (getLangOpts().CPlusPlus) {
1262 if (const RecordType *RT = T->getAs<RecordType>()) {
1263 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1264 sizeAndAlign.first = layout.getDataSize();
1265 }
1266 }
1267
1268 return sizeAndAlign;
1269}
1270
John McCallea1471e2010-05-20 01:18:31 +00001271std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001272ASTContext::getTypeInfoInChars(const Type *T) const {
John McCallea1471e2010-05-20 01:18:31 +00001273 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001274 return std::make_pair(toCharUnitsFromBits(Info.first),
1275 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +00001276}
1277
1278std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001279ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +00001280 return getTypeInfoInChars(T.getTypePtr());
1281}
1282
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001283std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1284 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1285 if (it != MemoizedTypeInfo.end())
1286 return it->second;
1287
1288 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1289 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1290 return Info;
1291}
1292
1293/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1294/// method does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +00001295///
1296/// FIXME: Pointers into different addr spaces could have different sizes and
1297/// alignment requirements: getPointerInfo should take an AddrSpace, this
1298/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001299std::pair<uint64_t, unsigned>
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001300ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +00001301 uint64_t Width=0;
1302 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +00001303 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001304#define TYPE(Class, Base)
1305#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +00001306#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +00001307#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1308#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +00001309 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +00001310
Chris Lattner692233e2007-07-13 22:27:08 +00001311 case Type::FunctionNoProto:
1312 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +00001313 // GCC extension: alignof(function) = 32 bits
1314 Width = 0;
1315 Align = 32;
1316 break;
1317
Douglas Gregor72564e72009-02-26 23:50:07 +00001318 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +00001319 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +00001320 Width = 0;
1321 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1322 break;
1323
Steve Narofffb22d962007-08-30 01:06:46 +00001324 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001325 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001326
Chris Lattner98be4942008-03-05 18:54:05 +00001327 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001328 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001329 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1330 "Overflow in array type bit size evaluation");
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001331 Width = EltInfo.first*Size;
Chris Lattner030d8842007-07-19 22:06:24 +00001332 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +00001333 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +00001334 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +00001335 }
Nate Begeman213541a2008-04-18 23:10:10 +00001336 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +00001337 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001338 const VectorType *VT = cast<VectorType>(T);
1339 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1340 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +00001341 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001342 // If the alignment is not a power of 2, round up to the next power of 2.
1343 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +00001344 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001345 Align = llvm::NextPowerOf2(Align);
1346 Width = llvm::RoundUpToAlignment(Width, Align);
1347 }
Chad Rosierf9e9af72012-07-13 23:57:43 +00001348 // Adjust the alignment based on the target max.
1349 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1350 if (TargetVectorAlign && TargetVectorAlign < Align)
1351 Align = TargetVectorAlign;
Chris Lattner030d8842007-07-19 22:06:24 +00001352 break;
1353 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001354
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001355 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +00001356 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001357 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001358 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +00001359 // GCC extension: alignof(void) = 8 bits.
1360 Width = 0;
1361 Align = 8;
1362 break;
1363
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001364 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001365 Width = Target->getBoolWidth();
1366 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001367 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001368 case BuiltinType::Char_S:
1369 case BuiltinType::Char_U:
1370 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001371 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001372 Width = Target->getCharWidth();
1373 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001374 break;
Chris Lattner3f59c972010-12-25 23:25:43 +00001375 case BuiltinType::WChar_S:
1376 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001377 Width = Target->getWCharWidth();
1378 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001379 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001380 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001381 Width = Target->getChar16Width();
1382 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001383 break;
1384 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001385 Width = Target->getChar32Width();
1386 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001387 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001388 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001389 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001390 Width = Target->getShortWidth();
1391 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001392 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001393 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001394 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001395 Width = Target->getIntWidth();
1396 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001397 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001398 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001399 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001400 Width = Target->getLongWidth();
1401 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001402 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001403 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001404 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001405 Width = Target->getLongLongWidth();
1406 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001407 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +00001408 case BuiltinType::Int128:
1409 case BuiltinType::UInt128:
1410 Width = 128;
1411 Align = 128; // int128_t is 128-bit aligned on all targets.
1412 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001413 case BuiltinType::Half:
1414 Width = Target->getHalfWidth();
1415 Align = Target->getHalfAlign();
1416 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001417 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001418 Width = Target->getFloatWidth();
1419 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001420 break;
1421 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001422 Width = Target->getDoubleWidth();
1423 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001424 break;
1425 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001426 Width = Target->getLongDoubleWidth();
1427 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001428 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001429 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001430 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1431 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +00001432 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001433 case BuiltinType::ObjCId:
1434 case BuiltinType::ObjCClass:
1435 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001436 Width = Target->getPointerWidth(0);
1437 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001438 break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00001439 case BuiltinType::OCLEvent:
Guy Benyeib13621d2012-12-18 14:38:23 +00001440 case BuiltinType::OCLImage1d:
1441 case BuiltinType::OCLImage1dArray:
1442 case BuiltinType::OCLImage1dBuffer:
1443 case BuiltinType::OCLImage2d:
1444 case BuiltinType::OCLImage2dArray:
1445 case BuiltinType::OCLImage3d:
1446 // Currently these types are pointers to opaque types.
1447 Width = Target->getPointerWidth(0);
1448 Align = Target->getPointerAlign(0);
1449 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001450 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +00001451 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001452 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001453 Width = Target->getPointerWidth(0);
1454 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001455 break;
Steve Naroff485eeff2008-09-24 15:05:44 +00001456 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001457 unsigned AS = getTargetAddressSpace(
1458 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001459 Width = Target->getPointerWidth(AS);
1460 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +00001461 break;
1462 }
Sebastian Redl5d484e82009-11-23 17:18:46 +00001463 case Type::LValueReference:
1464 case Type::RValueReference: {
1465 // alignof and sizeof should never enter this code path here, so we go
1466 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001467 unsigned AS = getTargetAddressSpace(
1468 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001469 Width = Target->getPointerWidth(AS);
1470 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +00001471 break;
1472 }
Chris Lattnerf72a4432008-03-08 08:34:58 +00001473 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001474 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001475 Width = Target->getPointerWidth(AS);
1476 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +00001477 break;
1478 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00001479 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +00001480 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001481 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001482 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +00001483 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001484 Align = PtrDiffInfo.second;
1485 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001486 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001487 case Type::Complex: {
1488 // Complex types have the same alignment as their elements, but twice the
1489 // size.
Mike Stump1eb44332009-09-09 15:08:12 +00001490 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +00001491 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001492 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +00001493 Align = EltInfo.second;
1494 break;
1495 }
John McCallc12c5bb2010-05-15 11:32:37 +00001496 case Type::ObjCObject:
1497 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +00001498 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001499 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +00001500 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001501 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001502 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +00001503 break;
1504 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001505 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001506 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001507 const TagType *TT = cast<TagType>(T);
1508
1509 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001510 Width = 8;
1511 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001512 break;
1513 }
Mike Stump1eb44332009-09-09 15:08:12 +00001514
Daniel Dunbar1d751182008-11-08 05:48:37 +00001515 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001516 return getTypeInfo(ET->getDecl()->getIntegerType());
1517
Daniel Dunbar1d751182008-11-08 05:48:37 +00001518 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001519 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001520 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001521 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001522 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001523 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001524
Chris Lattner9fcfe922009-10-22 05:17:15 +00001525 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001526 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1527 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001528
Richard Smith34b41d92011-02-20 03:19:35 +00001529 case Type::Auto: {
1530 const AutoType *A = cast<AutoType>(T);
1531 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001532 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001533 }
1534
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001535 case Type::Paren:
1536 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1537
Douglas Gregor18857642009-04-30 17:32:17 +00001538 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001539 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001540 std::pair<uint64_t, unsigned> Info
1541 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001542 // If the typedef has an aligned attribute on it, it overrides any computed
1543 // alignment we have. This violates the GCC documentation (which says that
1544 // attribute(aligned) can only round up) but matches its implementation.
1545 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1546 Align = AttrAlign;
1547 else
1548 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001549 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001550 break;
Chris Lattner71763312008-04-06 22:05:18 +00001551 }
Douglas Gregor18857642009-04-30 17:32:17 +00001552
1553 case Type::TypeOfExpr:
1554 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1555 .getTypePtr());
1556
1557 case Type::TypeOf:
1558 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1559
Anders Carlsson395b4752009-06-24 19:06:50 +00001560 case Type::Decltype:
1561 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1562 .getTypePtr());
1563
Sean Huntca63c202011-05-24 22:41:36 +00001564 case Type::UnaryTransform:
1565 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1566
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001567 case Type::Elaborated:
1568 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001569
John McCall9d156a72011-01-06 01:58:22 +00001570 case Type::Attributed:
1571 return getTypeInfo(
1572 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1573
Richard Smith3e4c6c42011-05-05 21:57:07 +00001574 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00001575 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +00001576 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +00001577 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1578 // A type alias template specialization may refer to a typedef with the
1579 // aligned attribute on it.
1580 if (TST->isTypeAlias())
1581 return getTypeInfo(TST->getAliasedType().getTypePtr());
1582 else
1583 return getTypeInfo(getCanonicalType(T));
1584 }
1585
Eli Friedmanb001de72011-10-06 23:00:33 +00001586 case Type::Atomic: {
Eli Friedman2be46072011-10-14 20:59:01 +00001587 std::pair<uint64_t, unsigned> Info
1588 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1589 Width = Info.first;
1590 Align = Info.second;
1591 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1592 llvm::isPowerOf2_64(Width)) {
1593 // We can potentially perform lock-free atomic operations for this
1594 // type; promote the alignment appropriately.
1595 // FIXME: We could potentially promote the width here as well...
1596 // is that worthwhile? (Non-struct atomic types generally have
1597 // power-of-two size anyway, but structs might not. Requires a bit
1598 // of implementation work to make sure we zero out the extra bits.)
1599 Align = static_cast<unsigned>(Width);
1600 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001601 }
1602
Douglas Gregor18857642009-04-30 17:32:17 +00001603 }
Mike Stump1eb44332009-09-09 15:08:12 +00001604
Eli Friedman2be46072011-10-14 20:59:01 +00001605 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001606 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001607}
1608
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001609/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1610CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1611 return CharUnits::fromQuantity(BitSize / getCharWidth());
1612}
1613
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001614/// toBits - Convert a size in characters to a size in characters.
1615int64_t ASTContext::toBits(CharUnits CharSize) const {
1616 return CharSize.getQuantity() * getCharWidth();
1617}
1618
Ken Dyckbdc601b2009-12-22 14:23:30 +00001619/// getTypeSizeInChars - Return the size of the specified type, in characters.
1620/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001621CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001622 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001623}
Jay Foad4ba2a172011-01-12 09:06:06 +00001624CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001625 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001626}
1627
Ken Dyck16e20cc2010-01-26 17:25:18 +00001628/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001629/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001630CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001631 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001632}
Jay Foad4ba2a172011-01-12 09:06:06 +00001633CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001634 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001635}
1636
Chris Lattner34ebde42009-01-27 18:08:34 +00001637/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1638/// type for the current target in bits. This can be different than the ABI
1639/// alignment in cases where it is beneficial for performance to overalign
1640/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001641unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001642 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001643
1644 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001645 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001646 T = CT->getElementType().getTypePtr();
1647 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosiercde7a1d2012-03-21 20:20:47 +00001648 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1649 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman1eed6022009-05-25 21:27:19 +00001650 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1651
Chris Lattner34ebde42009-01-27 18:08:34 +00001652 return ABIAlign;
1653}
1654
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001655/// DeepCollectObjCIvars -
1656/// This routine first collects all declared, but not synthesized, ivars in
1657/// super class and then collects all ivars, including those synthesized for
1658/// current class. This routine is used for implementation of current class
1659/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001660///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001661void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1662 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001663 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001664 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1665 DeepCollectObjCIvars(SuperClass, false, Ivars);
1666 if (!leafClass) {
1667 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1668 E = OI->ivar_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001669 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001670 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001671 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001672 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001673 Iv= Iv->getNextIvar())
1674 Ivars.push_back(Iv);
1675 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001676}
1677
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001678/// CollectInheritedProtocols - Collect all protocols in current class and
1679/// those inherited by it.
1680void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001681 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001682 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001683 // We can use protocol_iterator here instead of
1684 // all_referenced_protocol_iterator since we are walking all categories.
1685 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1686 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001687 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001688 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001689 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001690 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001691 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001692 CollectInheritedProtocols(*P, Protocols);
1693 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001694 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001695
1696 // Categories of this Interface.
Douglas Gregord3297242013-01-16 23:00:23 +00001697 for (ObjCInterfaceDecl::visible_categories_iterator
1698 Cat = OI->visible_categories_begin(),
1699 CatEnd = OI->visible_categories_end();
1700 Cat != CatEnd; ++Cat) {
1701 CollectInheritedProtocols(*Cat, Protocols);
1702 }
1703
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001704 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1705 while (SD) {
1706 CollectInheritedProtocols(SD, Protocols);
1707 SD = SD->getSuperClass();
1708 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001709 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001710 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001711 PE = OC->protocol_end(); P != PE; ++P) {
1712 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001713 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001714 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1715 PE = Proto->protocol_end(); P != PE; ++P)
1716 CollectInheritedProtocols(*P, Protocols);
1717 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001718 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001719 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1720 PE = OP->protocol_end(); P != PE; ++P) {
1721 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001722 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001723 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1724 PE = Proto->protocol_end(); P != PE; ++P)
1725 CollectInheritedProtocols(*P, Protocols);
1726 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001727 }
1728}
1729
Jay Foad4ba2a172011-01-12 09:06:06 +00001730unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001731 unsigned count = 0;
1732 // Count ivars declared in class extension.
Douglas Gregord3297242013-01-16 23:00:23 +00001733 for (ObjCInterfaceDecl::known_extensions_iterator
1734 Ext = OI->known_extensions_begin(),
1735 ExtEnd = OI->known_extensions_end();
1736 Ext != ExtEnd; ++Ext) {
1737 count += Ext->ivar_size();
1738 }
1739
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001740 // Count ivar defined in this class's implementation. This
1741 // includes synthesized ivars.
1742 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001743 count += ImplDecl->ivar_size();
1744
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001745 return count;
1746}
1747
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +00001748bool ASTContext::isSentinelNullExpr(const Expr *E) {
1749 if (!E)
1750 return false;
1751
1752 // nullptr_t is always treated as null.
1753 if (E->getType()->isNullPtrType()) return true;
1754
1755 if (E->getType()->isAnyPointerType() &&
1756 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1757 Expr::NPC_ValueDependentIsNull))
1758 return true;
1759
1760 // Unfortunately, __null has type 'int'.
1761 if (isa<GNUNullExpr>(E)) return true;
1762
1763 return false;
1764}
1765
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001766/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1767ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1768 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1769 I = ObjCImpls.find(D);
1770 if (I != ObjCImpls.end())
1771 return cast<ObjCImplementationDecl>(I->second);
1772 return 0;
1773}
1774/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1775ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1776 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1777 I = ObjCImpls.find(D);
1778 if (I != ObjCImpls.end())
1779 return cast<ObjCCategoryImplDecl>(I->second);
1780 return 0;
1781}
1782
1783/// \brief Set the implementation of ObjCInterfaceDecl.
1784void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1785 ObjCImplementationDecl *ImplD) {
1786 assert(IFaceD && ImplD && "Passed null params");
1787 ObjCImpls[IFaceD] = ImplD;
1788}
1789/// \brief Set the implementation of ObjCCategoryDecl.
1790void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1791 ObjCCategoryImplDecl *ImplD) {
1792 assert(CatD && ImplD && "Passed null params");
1793 ObjCImpls[CatD] = ImplD;
1794}
1795
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001796ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1797 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1798 return ID;
1799 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1800 return CD->getClassInterface();
1801 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1802 return IMD->getClassInterface();
1803
1804 return 0;
1805}
1806
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001807/// \brief Get the copy initialization expression of VarDecl,or NULL if
1808/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001809Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001810 assert(VD && "Passed null params");
1811 assert(VD->hasAttr<BlocksAttr>() &&
1812 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001813 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001814 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001815 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1816}
1817
1818/// \brief Set the copy inialization expression of a block var decl.
1819void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1820 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001821 assert(VD->hasAttr<BlocksAttr>() &&
1822 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001823 BlockVarCopyInits[VD] = Init;
1824}
1825
John McCalla93c9342009-12-07 02:54:59 +00001826TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001827 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001828 if (!DataSize)
1829 DataSize = TypeLoc::getFullDataSizeForType(T);
1830 else
1831 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001832 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001833
John McCalla93c9342009-12-07 02:54:59 +00001834 TypeSourceInfo *TInfo =
1835 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1836 new (TInfo) TypeSourceInfo(T);
1837 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001838}
1839
John McCalla93c9342009-12-07 02:54:59 +00001840TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001841 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001842 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001843 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001844 return DI;
1845}
1846
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001847const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001848ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001849 return getObjCLayout(D, 0);
1850}
1851
1852const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001853ASTContext::getASTObjCImplementationLayout(
1854 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001855 return getObjCLayout(D->getClassInterface(), D);
1856}
1857
Chris Lattnera7674d82007-07-13 22:13:22 +00001858//===----------------------------------------------------------------------===//
1859// Type creation/memoization methods
1860//===----------------------------------------------------------------------===//
1861
Jay Foad4ba2a172011-01-12 09:06:06 +00001862QualType
John McCall3b657512011-01-19 10:06:00 +00001863ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1864 unsigned fastQuals = quals.getFastQualifiers();
1865 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001866
1867 // Check if we've already instantiated this type.
1868 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001869 ExtQuals::Profile(ID, baseType, quals);
1870 void *insertPos = 0;
1871 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1872 assert(eq->getQualifiers() == quals);
1873 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001874 }
1875
John McCall3b657512011-01-19 10:06:00 +00001876 // If the base type is not canonical, make the appropriate canonical type.
1877 QualType canon;
1878 if (!baseType->isCanonicalUnqualified()) {
1879 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall200fa532012-02-08 00:46:36 +00001880 canonSplit.Quals.addConsistentQualifiers(quals);
1881 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00001882
1883 // Re-find the insert position.
1884 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1885 }
1886
1887 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1888 ExtQualNodes.InsertNode(eq, insertPos);
1889 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001890}
1891
Jay Foad4ba2a172011-01-12 09:06:06 +00001892QualType
1893ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001894 QualType CanT = getCanonicalType(T);
1895 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001896 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001897
John McCall0953e762009-09-24 19:53:00 +00001898 // If we are composing extended qualifiers together, merge together
1899 // into one ExtQuals node.
1900 QualifierCollector Quals;
1901 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001902
John McCall0953e762009-09-24 19:53:00 +00001903 // If this type already has an address space specified, it cannot get
1904 // another one.
1905 assert(!Quals.hasAddressSpace() &&
1906 "Type cannot be in multiple addr spaces!");
1907 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001908
John McCall0953e762009-09-24 19:53:00 +00001909 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001910}
1911
Chris Lattnerb7d25532009-02-18 22:53:11 +00001912QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001913 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001914 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001915 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001916 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001917
John McCall7f040a92010-12-24 02:08:15 +00001918 if (const PointerType *ptr = T->getAs<PointerType>()) {
1919 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001920 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001921 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1922 return getPointerType(ResultType);
1923 }
1924 }
Mike Stump1eb44332009-09-09 15:08:12 +00001925
John McCall0953e762009-09-24 19:53:00 +00001926 // If we are composing extended qualifiers together, merge together
1927 // into one ExtQuals node.
1928 QualifierCollector Quals;
1929 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001930
John McCall0953e762009-09-24 19:53:00 +00001931 // If this type already has an ObjCGC specified, it cannot get
1932 // another one.
1933 assert(!Quals.hasObjCGCAttr() &&
1934 "Type cannot have multiple ObjCGCs!");
1935 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001936
John McCall0953e762009-09-24 19:53:00 +00001937 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001938}
Chris Lattnera7674d82007-07-13 22:13:22 +00001939
John McCalle6a365d2010-12-19 02:44:49 +00001940const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1941 FunctionType::ExtInfo Info) {
1942 if (T->getExtInfo() == Info)
1943 return T;
1944
1945 QualType Result;
1946 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1947 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1948 } else {
1949 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1950 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1951 EPI.ExtInfo = Info;
1952 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1953 FPT->getNumArgs(), EPI);
1954 }
1955
1956 return cast<FunctionType>(Result.getTypePtr());
1957}
1958
Reid Spencer5f016e22007-07-11 17:01:13 +00001959/// getComplexType - Return the uniqued reference to the type for a complex
1960/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001961QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001962 // Unique pointers, to guarantee there is only one pointer of a particular
1963 // structure.
1964 llvm::FoldingSetNodeID ID;
1965 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001966
Reid Spencer5f016e22007-07-11 17:01:13 +00001967 void *InsertPos = 0;
1968 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1969 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001970
Reid Spencer5f016e22007-07-11 17:01:13 +00001971 // If the pointee type isn't canonical, this won't be a canonical type either,
1972 // so fill in the canonical type field.
1973 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001974 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001975 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001976
Reid Spencer5f016e22007-07-11 17:01:13 +00001977 // Get the new insert position for the node we care about.
1978 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001979 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001980 }
John McCall6b304a02009-09-24 23:30:46 +00001981 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001982 Types.push_back(New);
1983 ComplexTypes.InsertNode(New, InsertPos);
1984 return QualType(New, 0);
1985}
1986
Reid Spencer5f016e22007-07-11 17:01:13 +00001987/// getPointerType - Return the uniqued reference to the type for a pointer to
1988/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001989QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001990 // Unique pointers, to guarantee there is only one pointer of a particular
1991 // structure.
1992 llvm::FoldingSetNodeID ID;
1993 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001994
Reid Spencer5f016e22007-07-11 17:01:13 +00001995 void *InsertPos = 0;
1996 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1997 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001998
Reid Spencer5f016e22007-07-11 17:01:13 +00001999 // If the pointee type isn't canonical, this won't be a canonical type either,
2000 // so fill in the canonical type field.
2001 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002002 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002003 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002004
Reid Spencer5f016e22007-07-11 17:01:13 +00002005 // Get the new insert position for the node we care about.
2006 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002007 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002008 }
John McCall6b304a02009-09-24 23:30:46 +00002009 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002010 Types.push_back(New);
2011 PointerTypes.InsertNode(New, InsertPos);
2012 return QualType(New, 0);
2013}
2014
Mike Stump1eb44332009-09-09 15:08:12 +00002015/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00002016/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00002017QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00002018 assert(T->isFunctionType() && "block of function types only");
2019 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00002020 // structure.
2021 llvm::FoldingSetNodeID ID;
2022 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002023
Steve Naroff5618bd42008-08-27 16:04:49 +00002024 void *InsertPos = 0;
2025 if (BlockPointerType *PT =
2026 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2027 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002028
2029 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00002030 // type either so fill in the canonical type field.
2031 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002032 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00002033 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002034
Steve Naroff5618bd42008-08-27 16:04:49 +00002035 // Get the new insert position for the node we care about.
2036 BlockPointerType *NewIP =
2037 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002038 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00002039 }
John McCall6b304a02009-09-24 23:30:46 +00002040 BlockPointerType *New
2041 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00002042 Types.push_back(New);
2043 BlockPointerTypes.InsertNode(New, InsertPos);
2044 return QualType(New, 0);
2045}
2046
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002047/// getLValueReferenceType - Return the uniqued reference to the type for an
2048/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002049QualType
2050ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00002051 assert(getCanonicalType(T) != OverloadTy &&
2052 "Unresolved overloaded function type");
2053
Reid Spencer5f016e22007-07-11 17:01:13 +00002054 // Unique pointers, to guarantee there is only one pointer of a particular
2055 // structure.
2056 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002057 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002058
2059 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002060 if (LValueReferenceType *RT =
2061 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002062 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002063
John McCall54e14c42009-10-22 22:37:11 +00002064 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2065
Reid Spencer5f016e22007-07-11 17:01:13 +00002066 // If the referencee type isn't canonical, this won't be a canonical type
2067 // either, so fill in the canonical type field.
2068 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002069 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2070 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2071 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002072
Reid Spencer5f016e22007-07-11 17:01:13 +00002073 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002074 LValueReferenceType *NewIP =
2075 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002076 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002077 }
2078
John McCall6b304a02009-09-24 23:30:46 +00002079 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00002080 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2081 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002082 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002083 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00002084
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002085 return QualType(New, 0);
2086}
2087
2088/// getRValueReferenceType - Return the uniqued reference to the type for an
2089/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002090QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002091 // Unique pointers, to guarantee there is only one pointer of a particular
2092 // structure.
2093 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002094 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002095
2096 void *InsertPos = 0;
2097 if (RValueReferenceType *RT =
2098 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2099 return QualType(RT, 0);
2100
John McCall54e14c42009-10-22 22:37:11 +00002101 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2102
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002103 // If the referencee type isn't canonical, this won't be a canonical type
2104 // either, so fill in the canonical type field.
2105 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002106 if (InnerRef || !T.isCanonical()) {
2107 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2108 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002109
2110 // Get the new insert position for the node we care about.
2111 RValueReferenceType *NewIP =
2112 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002113 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002114 }
2115
John McCall6b304a02009-09-24 23:30:46 +00002116 RValueReferenceType *New
2117 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002118 Types.push_back(New);
2119 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002120 return QualType(New, 0);
2121}
2122
Sebastian Redlf30208a2009-01-24 21:16:55 +00002123/// getMemberPointerType - Return the uniqued reference to the type for a
2124/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00002125QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002126 // Unique pointers, to guarantee there is only one pointer of a particular
2127 // structure.
2128 llvm::FoldingSetNodeID ID;
2129 MemberPointerType::Profile(ID, T, Cls);
2130
2131 void *InsertPos = 0;
2132 if (MemberPointerType *PT =
2133 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2134 return QualType(PT, 0);
2135
2136 // If the pointee or class type isn't canonical, this won't be a canonical
2137 // type either, so fill in the canonical type field.
2138 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00002139 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002140 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2141
2142 // Get the new insert position for the node we care about.
2143 MemberPointerType *NewIP =
2144 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002145 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00002146 }
John McCall6b304a02009-09-24 23:30:46 +00002147 MemberPointerType *New
2148 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002149 Types.push_back(New);
2150 MemberPointerTypes.InsertNode(New, InsertPos);
2151 return QualType(New, 0);
2152}
2153
Mike Stump1eb44332009-09-09 15:08:12 +00002154/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00002155/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002156QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00002157 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00002158 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002159 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00002160 assert((EltTy->isDependentType() ||
2161 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00002162 "Constant array of VLAs is illegal!");
2163
Chris Lattner38aeec72009-05-13 04:12:56 +00002164 // Convert the array size into a canonical width matching the pointer size for
2165 // the target.
2166 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002167 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002168 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00002169
Reid Spencer5f016e22007-07-11 17:01:13 +00002170 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002171 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00002172
Reid Spencer5f016e22007-07-11 17:01:13 +00002173 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002174 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002175 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002176 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002177
John McCall3b657512011-01-19 10:06:00 +00002178 // If the element type isn't canonical or has qualifiers, this won't
2179 // be a canonical type either, so fill in the canonical type field.
2180 QualType Canon;
2181 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2182 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002183 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002184 ASM, IndexTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002185 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00002186
Reid Spencer5f016e22007-07-11 17:01:13 +00002187 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00002188 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002189 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002190 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002191 }
Mike Stump1eb44332009-09-09 15:08:12 +00002192
John McCall6b304a02009-09-24 23:30:46 +00002193 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002194 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002195 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002196 Types.push_back(New);
2197 return QualType(New, 0);
2198}
2199
John McCallce889032011-01-18 08:40:38 +00002200/// getVariableArrayDecayedType - Turns the given type, which may be
2201/// variably-modified, into the corresponding type with all the known
2202/// sizes replaced with [*].
2203QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2204 // Vastly most common case.
2205 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002206
John McCallce889032011-01-18 08:40:38 +00002207 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002208
John McCallce889032011-01-18 08:40:38 +00002209 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00002210 const Type *ty = split.Ty;
John McCallce889032011-01-18 08:40:38 +00002211 switch (ty->getTypeClass()) {
2212#define TYPE(Class, Base)
2213#define ABSTRACT_TYPE(Class, Base)
2214#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2215#include "clang/AST/TypeNodes.def"
2216 llvm_unreachable("didn't desugar past all non-canonical types?");
2217
2218 // These types should never be variably-modified.
2219 case Type::Builtin:
2220 case Type::Complex:
2221 case Type::Vector:
2222 case Type::ExtVector:
2223 case Type::DependentSizedExtVector:
2224 case Type::ObjCObject:
2225 case Type::ObjCInterface:
2226 case Type::ObjCObjectPointer:
2227 case Type::Record:
2228 case Type::Enum:
2229 case Type::UnresolvedUsing:
2230 case Type::TypeOfExpr:
2231 case Type::TypeOf:
2232 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00002233 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00002234 case Type::DependentName:
2235 case Type::InjectedClassName:
2236 case Type::TemplateSpecialization:
2237 case Type::DependentTemplateSpecialization:
2238 case Type::TemplateTypeParm:
2239 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00002240 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00002241 case Type::PackExpansion:
2242 llvm_unreachable("type should never be variably-modified");
2243
2244 // These types can be variably-modified but should never need to
2245 // further decay.
2246 case Type::FunctionNoProto:
2247 case Type::FunctionProto:
2248 case Type::BlockPointer:
2249 case Type::MemberPointer:
2250 return type;
2251
2252 // These types can be variably-modified. All these modifications
2253 // preserve structure except as noted by comments.
2254 // TODO: if we ever care about optimizing VLAs, there are no-op
2255 // optimizations available here.
2256 case Type::Pointer:
2257 result = getPointerType(getVariableArrayDecayedType(
2258 cast<PointerType>(ty)->getPointeeType()));
2259 break;
2260
2261 case Type::LValueReference: {
2262 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2263 result = getLValueReferenceType(
2264 getVariableArrayDecayedType(lv->getPointeeType()),
2265 lv->isSpelledAsLValue());
2266 break;
2267 }
2268
2269 case Type::RValueReference: {
2270 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2271 result = getRValueReferenceType(
2272 getVariableArrayDecayedType(lv->getPointeeType()));
2273 break;
2274 }
2275
Eli Friedmanb001de72011-10-06 23:00:33 +00002276 case Type::Atomic: {
2277 const AtomicType *at = cast<AtomicType>(ty);
2278 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2279 break;
2280 }
2281
John McCallce889032011-01-18 08:40:38 +00002282 case Type::ConstantArray: {
2283 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2284 result = getConstantArrayType(
2285 getVariableArrayDecayedType(cat->getElementType()),
2286 cat->getSize(),
2287 cat->getSizeModifier(),
2288 cat->getIndexTypeCVRQualifiers());
2289 break;
2290 }
2291
2292 case Type::DependentSizedArray: {
2293 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2294 result = getDependentSizedArrayType(
2295 getVariableArrayDecayedType(dat->getElementType()),
2296 dat->getSizeExpr(),
2297 dat->getSizeModifier(),
2298 dat->getIndexTypeCVRQualifiers(),
2299 dat->getBracketsRange());
2300 break;
2301 }
2302
2303 // Turn incomplete types into [*] types.
2304 case Type::IncompleteArray: {
2305 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2306 result = getVariableArrayType(
2307 getVariableArrayDecayedType(iat->getElementType()),
2308 /*size*/ 0,
2309 ArrayType::Normal,
2310 iat->getIndexTypeCVRQualifiers(),
2311 SourceRange());
2312 break;
2313 }
2314
2315 // Turn VLA types into [*] types.
2316 case Type::VariableArray: {
2317 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2318 result = getVariableArrayType(
2319 getVariableArrayDecayedType(vat->getElementType()),
2320 /*size*/ 0,
2321 ArrayType::Star,
2322 vat->getIndexTypeCVRQualifiers(),
2323 vat->getBracketsRange());
2324 break;
2325 }
2326 }
2327
2328 // Apply the top-level qualifiers from the original.
John McCall200fa532012-02-08 00:46:36 +00002329 return getQualifiedType(result, split.Quals);
John McCallce889032011-01-18 08:40:38 +00002330}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002331
Steve Naroffbdbf7b02007-08-30 18:14:25 +00002332/// getVariableArrayType - Returns a non-unique reference to the type for a
2333/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002334QualType ASTContext::getVariableArrayType(QualType EltTy,
2335 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00002336 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002337 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00002338 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002339 // Since we don't unique expressions, it isn't possible to unique VLA's
2340 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00002341 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00002342
John McCall3b657512011-01-19 10:06:00 +00002343 // Be sure to pull qualifiers off the element type.
2344 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2345 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002346 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002347 IndexTypeQuals, Brackets);
John McCall200fa532012-02-08 00:46:36 +00002348 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor715e9c82010-05-23 16:10:32 +00002349 }
2350
John McCall6b304a02009-09-24 23:30:46 +00002351 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002352 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002353
2354 VariableArrayTypes.push_back(New);
2355 Types.push_back(New);
2356 return QualType(New, 0);
2357}
2358
Douglas Gregor898574e2008-12-05 23:32:09 +00002359/// getDependentSizedArrayType - Returns a non-unique reference to
2360/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00002361/// type.
John McCall3b657512011-01-19 10:06:00 +00002362QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2363 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00002364 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002365 unsigned elementTypeQuals,
2366 SourceRange brackets) const {
2367 assert((!numElements || numElements->isTypeDependent() ||
2368 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00002369 "Size must be type- or value-dependent!");
2370
John McCall3b657512011-01-19 10:06:00 +00002371 // Dependently-sized array types that do not have a specified number
2372 // of elements will have their sizes deduced from a dependent
2373 // initializer. We do no canonicalization here at all, which is okay
2374 // because they can't be used in most locations.
2375 if (!numElements) {
2376 DependentSizedArrayType *newType
2377 = new (*this, TypeAlignment)
2378 DependentSizedArrayType(*this, elementType, QualType(),
2379 numElements, ASM, elementTypeQuals,
2380 brackets);
2381 Types.push_back(newType);
2382 return QualType(newType, 0);
2383 }
2384
2385 // Otherwise, we actually build a new type every time, but we
2386 // also build a canonical type.
2387
2388 SplitQualType canonElementType = getCanonicalType(elementType).split();
2389
2390 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00002391 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002392 DependentSizedArrayType::Profile(ID, *this,
John McCall200fa532012-02-08 00:46:36 +00002393 QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002394 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002395
John McCall3b657512011-01-19 10:06:00 +00002396 // Look for an existing type with these properties.
2397 DependentSizedArrayType *canonTy =
2398 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002399
John McCall3b657512011-01-19 10:06:00 +00002400 // If we don't have one, build one.
2401 if (!canonTy) {
2402 canonTy = new (*this, TypeAlignment)
John McCall200fa532012-02-08 00:46:36 +00002403 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002404 QualType(), numElements, ASM, elementTypeQuals,
2405 brackets);
2406 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2407 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002408 }
2409
John McCall3b657512011-01-19 10:06:00 +00002410 // Apply qualifiers from the element type to the array.
2411 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall200fa532012-02-08 00:46:36 +00002412 canonElementType.Quals);
Mike Stump1eb44332009-09-09 15:08:12 +00002413
John McCall3b657512011-01-19 10:06:00 +00002414 // If we didn't need extra canonicalization for the element type,
2415 // then just use that as our result.
John McCall200fa532012-02-08 00:46:36 +00002416 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall3b657512011-01-19 10:06:00 +00002417 return canon;
2418
2419 // Otherwise, we need to build a type which follows the spelling
2420 // of the element type.
2421 DependentSizedArrayType *sugaredType
2422 = new (*this, TypeAlignment)
2423 DependentSizedArrayType(*this, elementType, canon, numElements,
2424 ASM, elementTypeQuals, brackets);
2425 Types.push_back(sugaredType);
2426 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00002427}
2428
John McCall3b657512011-01-19 10:06:00 +00002429QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00002430 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002431 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002432 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002433 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002434
John McCall3b657512011-01-19 10:06:00 +00002435 void *insertPos = 0;
2436 if (IncompleteArrayType *iat =
2437 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2438 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002439
2440 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00002441 // either, so fill in the canonical type field. We also have to pull
2442 // qualifiers off the element type.
2443 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00002444
John McCall3b657512011-01-19 10:06:00 +00002445 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2446 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall200fa532012-02-08 00:46:36 +00002447 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002448 ASM, elementTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002449 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002450
2451 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00002452 IncompleteArrayType *existing =
2453 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2454 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00002455 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00002456
John McCall3b657512011-01-19 10:06:00 +00002457 IncompleteArrayType *newType = new (*this, TypeAlignment)
2458 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002459
John McCall3b657512011-01-19 10:06:00 +00002460 IncompleteArrayTypes.InsertNode(newType, insertPos);
2461 Types.push_back(newType);
2462 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00002463}
2464
Steve Naroff73322922007-07-18 18:00:27 +00002465/// getVectorType - Return the unique reference to a vector type of
2466/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00002467QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00002468 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00002469 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00002470
Reid Spencer5f016e22007-07-11 17:01:13 +00002471 // Check if we've already instantiated a vector of this type.
2472 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00002473 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00002474
Reid Spencer5f016e22007-07-11 17:01:13 +00002475 void *InsertPos = 0;
2476 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2477 return QualType(VTP, 0);
2478
2479 // If the element type isn't canonical, this won't be a canonical type either,
2480 // so fill in the canonical type field.
2481 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00002482 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00002483 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002484
Reid Spencer5f016e22007-07-11 17:01:13 +00002485 // Get the new insert position for the node we care about.
2486 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002487 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002488 }
John McCall6b304a02009-09-24 23:30:46 +00002489 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00002490 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002491 VectorTypes.InsertNode(New, InsertPos);
2492 Types.push_back(New);
2493 return QualType(New, 0);
2494}
2495
Nate Begeman213541a2008-04-18 23:10:10 +00002496/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00002497/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002498QualType
2499ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00002500 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00002501
Steve Naroff73322922007-07-18 18:00:27 +00002502 // Check if we've already instantiated a vector of this type.
2503 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00002504 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002505 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00002506 void *InsertPos = 0;
2507 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2508 return QualType(VTP, 0);
2509
2510 // If the element type isn't canonical, this won't be a canonical type either,
2511 // so fill in the canonical type field.
2512 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002513 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002514 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00002515
Steve Naroff73322922007-07-18 18:00:27 +00002516 // Get the new insert position for the node we care about.
2517 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002518 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00002519 }
John McCall6b304a02009-09-24 23:30:46 +00002520 ExtVectorType *New = new (*this, TypeAlignment)
2521 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00002522 VectorTypes.InsertNode(New, InsertPos);
2523 Types.push_back(New);
2524 return QualType(New, 0);
2525}
2526
Jay Foad4ba2a172011-01-12 09:06:06 +00002527QualType
2528ASTContext::getDependentSizedExtVectorType(QualType vecType,
2529 Expr *SizeExpr,
2530 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002531 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002532 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002533 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002534
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002535 void *InsertPos = 0;
2536 DependentSizedExtVectorType *Canon
2537 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2538 DependentSizedExtVectorType *New;
2539 if (Canon) {
2540 // We already have a canonical version of this array type; use it as
2541 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002542 New = new (*this, TypeAlignment)
2543 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2544 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002545 } else {
2546 QualType CanonVecTy = getCanonicalType(vecType);
2547 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002548 New = new (*this, TypeAlignment)
2549 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2550 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002551
2552 DependentSizedExtVectorType *CanonCheck
2553 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2554 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2555 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002556 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2557 } else {
2558 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2559 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002560 New = new (*this, TypeAlignment)
2561 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002562 }
2563 }
Mike Stump1eb44332009-09-09 15:08:12 +00002564
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002565 Types.push_back(New);
2566 return QualType(New, 0);
2567}
2568
Douglas Gregor72564e72009-02-26 23:50:07 +00002569/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002570///
Jay Foad4ba2a172011-01-12 09:06:06 +00002571QualType
2572ASTContext::getFunctionNoProtoType(QualType ResultTy,
2573 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00002574 const CallingConv DefaultCC = Info.getCC();
2575 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2576 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00002577 // Unique functions, to guarantee there is only one function of a particular
2578 // structure.
2579 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002580 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002581
Reid Spencer5f016e22007-07-11 17:01:13 +00002582 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002583 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002584 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002585 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002586
Reid Spencer5f016e22007-07-11 17:01:13 +00002587 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00002588 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00002589 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00002590 Canonical =
2591 getFunctionNoProtoType(getCanonicalType(ResultTy),
2592 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00002593
Reid Spencer5f016e22007-07-11 17:01:13 +00002594 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002595 FunctionNoProtoType *NewIP =
2596 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002597 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002598 }
Mike Stump1eb44332009-09-09 15:08:12 +00002599
Roman Divackycfe9af22011-03-01 17:40:53 +00002600 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002601 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002602 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002603 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002604 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002605 return QualType(New, 0);
2606}
2607
Douglas Gregor02dd7982013-01-17 23:36:45 +00002608/// \brief Determine whether \p T is canonical as the result type of a function.
2609static bool isCanonicalResultType(QualType T) {
2610 return T.isCanonical() &&
2611 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2612 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2613}
2614
Reid Spencer5f016e22007-07-11 17:01:13 +00002615/// getFunctionType - Return a normal function type with a typed argument
2616/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002617QualType
2618ASTContext::getFunctionType(QualType ResultTy,
2619 const QualType *ArgArray, unsigned NumArgs,
2620 const FunctionProtoType::ExtProtoInfo &EPI) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002621 // Unique functions, to guarantee there is only one function of a particular
2622 // structure.
2623 llvm::FoldingSetNodeID ID;
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002624 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002625
2626 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002627 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002628 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002629 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002630
2631 // Determine whether the type being created is already canonical or not.
Richard Smitheefb3d52012-02-10 09:58:53 +00002632 bool isCanonical =
Douglas Gregor02dd7982013-01-17 23:36:45 +00002633 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smitheefb3d52012-02-10 09:58:53 +00002634 !EPI.HasTrailingReturn;
Reid Spencer5f016e22007-07-11 17:01:13 +00002635 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002636 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002637 isCanonical = false;
2638
Roman Divackycfe9af22011-03-01 17:40:53 +00002639 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2640 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2641 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002642
Reid Spencer5f016e22007-07-11 17:01:13 +00002643 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002644 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002645 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002646 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002647 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002648 CanonicalArgs.reserve(NumArgs);
2649 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002650 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002651
John McCalle23cf432010-12-14 08:05:40 +00002652 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +00002653 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002654 CanonicalEPI.ExceptionSpecType = EST_None;
2655 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002656 CanonicalEPI.ExtInfo
2657 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2658
Douglas Gregor02dd7982013-01-17 23:36:45 +00002659 // Result types do not have ARC lifetime qualifiers.
2660 QualType CanResultTy = getCanonicalType(ResultTy);
2661 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2662 Qualifiers Qs = CanResultTy.getQualifiers();
2663 Qs.removeObjCLifetime();
2664 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2665 }
2666
2667 Canonical = getFunctionType(CanResultTy,
Jay Foadbeaaccd2009-05-21 09:52:38 +00002668 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00002669 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002670
Reid Spencer5f016e22007-07-11 17:01:13 +00002671 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002672 FunctionProtoType *NewIP =
2673 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002674 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002675 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002676
John McCallf85e1932011-06-15 23:02:42 +00002677 // FunctionProtoType objects are allocated with extra bytes after
2678 // them for three variable size arrays at the end:
2679 // - parameter types
2680 // - exception types
2681 // - consumed-arguments flags
2682 // Instead of the exception types, there could be a noexcept
Richard Smithb9d0b762012-07-27 04:22:15 +00002683 // expression, or information used to resolve the exception
2684 // specification.
John McCalle23cf432010-12-14 08:05:40 +00002685 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002686 NumArgs * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002687 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00002688 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002689 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002690 Size += sizeof(Expr*);
Richard Smithe6975e92012-04-17 00:58:00 +00002691 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smith13bffc52012-04-19 00:08:28 +00002692 Size += 2 * sizeof(FunctionDecl*);
Richard Smithb9d0b762012-07-27 04:22:15 +00002693 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2694 Size += sizeof(FunctionDecl*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002695 }
John McCallf85e1932011-06-15 23:02:42 +00002696 if (EPI.ConsumedArguments)
2697 Size += NumArgs * sizeof(bool);
2698
John McCalle23cf432010-12-14 08:05:40 +00002699 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002700 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2701 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002702 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002703 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002704 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002705 return QualType(FTP, 0);
2706}
2707
John McCall3cb0ebd2010-03-10 03:28:59 +00002708#ifndef NDEBUG
2709static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2710 if (!isa<CXXRecordDecl>(D)) return false;
2711 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2712 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2713 return true;
2714 if (RD->getDescribedClassTemplate() &&
2715 !isa<ClassTemplateSpecializationDecl>(RD))
2716 return true;
2717 return false;
2718}
2719#endif
2720
2721/// getInjectedClassNameType - Return the unique reference to the
2722/// injected class name type for the specified templated declaration.
2723QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002724 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002725 assert(NeedsInjectedClassNameType(Decl));
2726 if (Decl->TypeForDecl) {
2727 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregoref96ee02012-01-14 16:38:05 +00002728 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002729 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2730 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2731 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2732 } else {
John McCallf4c73712011-01-19 06:33:43 +00002733 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002734 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002735 Decl->TypeForDecl = newType;
2736 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002737 }
2738 return QualType(Decl->TypeForDecl, 0);
2739}
2740
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002741/// getTypeDeclType - Return the unique reference to the type for the
2742/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002743QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002744 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002745 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002746
Richard Smith162e1c12011-04-15 14:24:37 +00002747 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002748 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002749
John McCallbecb8d52010-03-10 06:48:02 +00002750 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2751 "Template type parameter types are always available.");
2752
John McCall19c85762010-02-16 03:57:14 +00002753 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002754 assert(!Record->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002755 "struct/union has previous declaration");
2756 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002757 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002758 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002759 assert(!Enum->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002760 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002761 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002762 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002763 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002764 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2765 Decl->TypeForDecl = newType;
2766 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002767 } else
John McCallbecb8d52010-03-10 06:48:02 +00002768 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002769
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002770 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002771}
2772
Reid Spencer5f016e22007-07-11 17:01:13 +00002773/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002774/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002775QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002776ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2777 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002778 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002779
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002780 if (Canonical.isNull())
2781 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002782 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002783 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002784 Decl->TypeForDecl = newType;
2785 Types.push_back(newType);
2786 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002787}
2788
Jay Foad4ba2a172011-01-12 09:06:06 +00002789QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002790 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2791
Douglas Gregoref96ee02012-01-14 16:38:05 +00002792 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002793 if (PrevDecl->TypeForDecl)
2794 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2795
John McCallf4c73712011-01-19 06:33:43 +00002796 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2797 Decl->TypeForDecl = newType;
2798 Types.push_back(newType);
2799 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002800}
2801
Jay Foad4ba2a172011-01-12 09:06:06 +00002802QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002803 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2804
Douglas Gregoref96ee02012-01-14 16:38:05 +00002805 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002806 if (PrevDecl->TypeForDecl)
2807 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2808
John McCallf4c73712011-01-19 06:33:43 +00002809 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2810 Decl->TypeForDecl = newType;
2811 Types.push_back(newType);
2812 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002813}
2814
John McCall9d156a72011-01-06 01:58:22 +00002815QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2816 QualType modifiedType,
2817 QualType equivalentType) {
2818 llvm::FoldingSetNodeID id;
2819 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2820
2821 void *insertPos = 0;
2822 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2823 if (type) return QualType(type, 0);
2824
2825 QualType canon = getCanonicalType(equivalentType);
2826 type = new (*this, TypeAlignment)
2827 AttributedType(canon, attrKind, modifiedType, equivalentType);
2828
2829 Types.push_back(type);
2830 AttributedTypes.InsertNode(type, insertPos);
2831
2832 return QualType(type, 0);
2833}
2834
2835
John McCall49a832b2009-10-18 09:09:24 +00002836/// \brief Retrieve a substitution-result type.
2837QualType
2838ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002839 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002840 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002841 && "replacement types must always be canonical");
2842
2843 llvm::FoldingSetNodeID ID;
2844 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2845 void *InsertPos = 0;
2846 SubstTemplateTypeParmType *SubstParm
2847 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2848
2849 if (!SubstParm) {
2850 SubstParm = new (*this, TypeAlignment)
2851 SubstTemplateTypeParmType(Parm, Replacement);
2852 Types.push_back(SubstParm);
2853 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2854 }
2855
2856 return QualType(SubstParm, 0);
2857}
2858
Douglas Gregorc3069d62011-01-14 02:55:32 +00002859/// \brief Retrieve a
2860QualType ASTContext::getSubstTemplateTypeParmPackType(
2861 const TemplateTypeParmType *Parm,
2862 const TemplateArgument &ArgPack) {
2863#ifndef NDEBUG
2864 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2865 PEnd = ArgPack.pack_end();
2866 P != PEnd; ++P) {
2867 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2868 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2869 }
2870#endif
2871
2872 llvm::FoldingSetNodeID ID;
2873 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2874 void *InsertPos = 0;
2875 if (SubstTemplateTypeParmPackType *SubstParm
2876 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2877 return QualType(SubstParm, 0);
2878
2879 QualType Canon;
2880 if (!Parm->isCanonicalUnqualified()) {
2881 Canon = getCanonicalType(QualType(Parm, 0));
2882 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2883 ArgPack);
2884 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2885 }
2886
2887 SubstTemplateTypeParmPackType *SubstParm
2888 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2889 ArgPack);
2890 Types.push_back(SubstParm);
2891 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2892 return QualType(SubstParm, 0);
2893}
2894
Douglas Gregorfab9d672009-02-05 23:33:38 +00002895/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002896/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002897/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002898QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002899 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002900 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00002901 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002902 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002903 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002904 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002905 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2906
2907 if (TypeParm)
2908 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002909
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002910 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002911 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002912 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002913
2914 TemplateTypeParmType *TypeCheck
2915 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2916 assert(!TypeCheck && "Template type parameter canonical type broken");
2917 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002918 } else
John McCall6b304a02009-09-24 23:30:46 +00002919 TypeParm = new (*this, TypeAlignment)
2920 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002921
2922 Types.push_back(TypeParm);
2923 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2924
2925 return QualType(TypeParm, 0);
2926}
2927
John McCall3cb0ebd2010-03-10 03:28:59 +00002928TypeSourceInfo *
2929ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2930 SourceLocation NameLoc,
2931 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002932 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002933 assert(!Name.getAsDependentTemplateName() &&
2934 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002935 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00002936
2937 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2938 TemplateSpecializationTypeLoc TL
2939 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002940 TL.setTemplateKeywordLoc(SourceLocation());
John McCall3cb0ebd2010-03-10 03:28:59 +00002941 TL.setTemplateNameLoc(NameLoc);
2942 TL.setLAngleLoc(Args.getLAngleLoc());
2943 TL.setRAngleLoc(Args.getRAngleLoc());
2944 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2945 TL.setArgLocInfo(i, Args[i].getLocInfo());
2946 return DI;
2947}
2948
Mike Stump1eb44332009-09-09 15:08:12 +00002949QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002950ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002951 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002952 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002953 assert(!Template.getAsDependentTemplateName() &&
2954 "No dependent template names here!");
2955
John McCalld5532b62009-11-23 01:53:49 +00002956 unsigned NumArgs = Args.size();
2957
Chris Lattner5f9e2722011-07-23 10:55:15 +00002958 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00002959 ArgVec.reserve(NumArgs);
2960 for (unsigned i = 0; i != NumArgs; ++i)
2961 ArgVec.push_back(Args[i].getArgument());
2962
John McCall31f17ec2010-04-27 00:57:59 +00002963 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002964 Underlying);
John McCall833ca992009-10-29 08:12:44 +00002965}
2966
Douglas Gregorb70126a2012-02-03 17:16:23 +00002967#ifndef NDEBUG
2968static bool hasAnyPackExpansions(const TemplateArgument *Args,
2969 unsigned NumArgs) {
2970 for (unsigned I = 0; I != NumArgs; ++I)
2971 if (Args[I].isPackExpansion())
2972 return true;
2973
2974 return true;
2975}
2976#endif
2977
John McCall833ca992009-10-29 08:12:44 +00002978QualType
2979ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002980 const TemplateArgument *Args,
2981 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002982 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002983 assert(!Template.getAsDependentTemplateName() &&
2984 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002985 // Look through qualified template names.
2986 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2987 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002988
Douglas Gregorb70126a2012-02-03 17:16:23 +00002989 bool IsTypeAlias =
Richard Smith3e4c6c42011-05-05 21:57:07 +00002990 Template.getAsTemplateDecl() &&
2991 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00002992 QualType CanonType;
2993 if (!Underlying.isNull())
2994 CanonType = getCanonicalType(Underlying);
2995 else {
Douglas Gregorb70126a2012-02-03 17:16:23 +00002996 // We can get here with an alias template when the specialization contains
2997 // a pack expansion that does not match up with a parameter pack.
2998 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2999 "Caller must compute aliased type");
3000 IsTypeAlias = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00003001 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3002 NumArgs);
3003 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00003004
Douglas Gregor1275ae02009-07-28 23:00:59 +00003005 // Allocate the (non-canonical) template specialization type, but don't
3006 // try to unique it: these types typically have location information that
3007 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00003008 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3009 sizeof(TemplateArgument) * NumArgs +
Douglas Gregorb70126a2012-02-03 17:16:23 +00003010 (IsTypeAlias? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00003011 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00003012 TemplateSpecializationType *Spec
Douglas Gregorb70126a2012-02-03 17:16:23 +00003013 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3014 IsTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00003015
Douglas Gregor55f6b142009-02-09 18:46:07 +00003016 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00003017 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00003018}
3019
Mike Stump1eb44332009-09-09 15:08:12 +00003020QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003021ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3022 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00003023 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003024 assert(!Template.getAsDependentTemplateName() &&
3025 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00003026
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003027 // Look through qualified template names.
3028 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3029 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003030
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003031 // Build the canonical template specialization type.
3032 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003033 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003034 CanonArgs.reserve(NumArgs);
3035 for (unsigned I = 0; I != NumArgs; ++I)
3036 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3037
3038 // Determine whether this canonical template specialization type already
3039 // exists.
3040 llvm::FoldingSetNodeID ID;
3041 TemplateSpecializationType::Profile(ID, CanonTemplate,
3042 CanonArgs.data(), NumArgs, *this);
3043
3044 void *InsertPos = 0;
3045 TemplateSpecializationType *Spec
3046 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3047
3048 if (!Spec) {
3049 // Allocate a new canonical template specialization type.
3050 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3051 sizeof(TemplateArgument) * NumArgs),
3052 TypeAlignment);
3053 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3054 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003055 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003056 Types.push_back(Spec);
3057 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3058 }
3059
3060 assert(Spec->isDependentType() &&
3061 "Non-dependent template-id type must have a canonical type");
3062 return QualType(Spec, 0);
3063}
3064
3065QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003066ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3067 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00003068 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00003069 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003070 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003071
3072 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003073 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003074 if (T)
3075 return QualType(T, 0);
3076
Douglas Gregor789b1f62010-02-04 18:10:26 +00003077 QualType Canon = NamedType;
3078 if (!Canon.isCanonical()) {
3079 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003080 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3081 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00003082 (void)CheckT;
3083 }
3084
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003085 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003086 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003087 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003088 return QualType(T, 0);
3089}
3090
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003091QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00003092ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003093 llvm::FoldingSetNodeID ID;
3094 ParenType::Profile(ID, InnerType);
3095
3096 void *InsertPos = 0;
3097 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3098 if (T)
3099 return QualType(T, 0);
3100
3101 QualType Canon = InnerType;
3102 if (!Canon.isCanonical()) {
3103 Canon = getCanonicalType(InnerType);
3104 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3105 assert(!CheckT && "Paren canonical type broken");
3106 (void)CheckT;
3107 }
3108
3109 T = new (*this) ParenType(InnerType, Canon);
3110 Types.push_back(T);
3111 ParenTypes.InsertNode(T, InsertPos);
3112 return QualType(T, 0);
3113}
3114
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003115QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3116 NestedNameSpecifier *NNS,
3117 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003118 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00003119 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3120
3121 if (Canon.isNull()) {
3122 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003123 ElaboratedTypeKeyword CanonKeyword = Keyword;
3124 if (Keyword == ETK_None)
3125 CanonKeyword = ETK_Typename;
3126
3127 if (CanonNNS != NNS || CanonKeyword != Keyword)
3128 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003129 }
3130
3131 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003132 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003133
3134 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00003135 DependentNameType *T
3136 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00003137 if (T)
3138 return QualType(T, 0);
3139
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003140 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00003141 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00003142 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003143 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00003144}
3145
Mike Stump1eb44332009-09-09 15:08:12 +00003146QualType
John McCall33500952010-06-11 00:33:02 +00003147ASTContext::getDependentTemplateSpecializationType(
3148 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003149 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00003150 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003151 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00003152 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00003153 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00003154 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3155 ArgCopy.push_back(Args[I].getArgument());
3156 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3157 ArgCopy.size(),
3158 ArgCopy.data());
3159}
3160
3161QualType
3162ASTContext::getDependentTemplateSpecializationType(
3163 ElaboratedTypeKeyword Keyword,
3164 NestedNameSpecifier *NNS,
3165 const IdentifierInfo *Name,
3166 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00003167 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003168 assert((!NNS || NNS->isDependent()) &&
3169 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00003170
Douglas Gregor789b1f62010-02-04 18:10:26 +00003171 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00003172 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3173 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003174
3175 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00003176 DependentTemplateSpecializationType *T
3177 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003178 if (T)
3179 return QualType(T, 0);
3180
John McCall33500952010-06-11 00:33:02 +00003181 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003182
John McCall33500952010-06-11 00:33:02 +00003183 ElaboratedTypeKeyword CanonKeyword = Keyword;
3184 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3185
3186 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003187 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00003188 for (unsigned I = 0; I != NumArgs; ++I) {
3189 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3190 if (!CanonArgs[I].structurallyEquals(Args[I]))
3191 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00003192 }
3193
John McCall33500952010-06-11 00:33:02 +00003194 QualType Canon;
3195 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3196 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3197 Name, NumArgs,
3198 CanonArgs.data());
3199
3200 // Find the insert position again.
3201 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3202 }
3203
3204 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3205 sizeof(TemplateArgument) * NumArgs),
3206 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00003207 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00003208 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00003209 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00003210 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003211 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00003212}
3213
Douglas Gregorcded4f62011-01-14 17:04:44 +00003214QualType ASTContext::getPackExpansionType(QualType Pattern,
3215 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00003216 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00003217 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003218
3219 assert(Pattern->containsUnexpandedParameterPack() &&
3220 "Pack expansions must expand one or more parameter packs");
3221 void *InsertPos = 0;
3222 PackExpansionType *T
3223 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3224 if (T)
3225 return QualType(T, 0);
3226
3227 QualType Canon;
3228 if (!Pattern.isCanonical()) {
Richard Smithd8672ef2012-07-16 00:20:35 +00003229 Canon = getCanonicalType(Pattern);
3230 // The canonical type might not contain an unexpanded parameter pack, if it
3231 // contains an alias template specialization which ignores one of its
3232 // parameters.
3233 if (Canon->containsUnexpandedParameterPack()) {
3234 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003235
Richard Smithd8672ef2012-07-16 00:20:35 +00003236 // Find the insert position again, in case we inserted an element into
3237 // PackExpansionTypes and invalidated our insert position.
3238 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3239 }
Douglas Gregor7536dd52010-12-20 02:24:11 +00003240 }
3241
Douglas Gregorcded4f62011-01-14 17:04:44 +00003242 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003243 Types.push_back(T);
3244 PackExpansionTypes.InsertNode(T, InsertPos);
3245 return QualType(T, 0);
3246}
3247
Chris Lattner88cb27a2008-04-07 04:56:42 +00003248/// CmpProtocolNames - Comparison predicate for sorting protocols
3249/// alphabetically.
3250static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3251 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003252 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00003253}
3254
John McCallc12c5bb2010-05-15 11:32:37 +00003255static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00003256 unsigned NumProtocols) {
3257 if (NumProtocols == 0) return true;
3258
Douglas Gregor61cc2962012-01-02 02:00:30 +00003259 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3260 return false;
3261
John McCall54e14c42009-10-22 22:37:11 +00003262 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregor61cc2962012-01-02 02:00:30 +00003263 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3264 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCall54e14c42009-10-22 22:37:11 +00003265 return false;
3266 return true;
3267}
3268
3269static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00003270 unsigned &NumProtocols) {
3271 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00003272
Chris Lattner88cb27a2008-04-07 04:56:42 +00003273 // Sort protocols, keyed by name.
3274 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3275
Douglas Gregor61cc2962012-01-02 02:00:30 +00003276 // Canonicalize.
3277 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3278 Protocols[I] = Protocols[I]->getCanonicalDecl();
3279
Chris Lattner88cb27a2008-04-07 04:56:42 +00003280 // Remove duplicates.
3281 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3282 NumProtocols = ProtocolsEnd-Protocols;
3283}
3284
John McCallc12c5bb2010-05-15 11:32:37 +00003285QualType ASTContext::getObjCObjectType(QualType BaseType,
3286 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00003287 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003288 // If the base type is an interface and there aren't any protocols
3289 // to add, then the interface type will do just fine.
3290 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3291 return BaseType;
3292
3293 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003294 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00003295 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003296 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00003297 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3298 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003299
John McCallc12c5bb2010-05-15 11:32:37 +00003300 // Build the canonical type, which has the canonical base type and
3301 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00003302 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00003303 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3304 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3305 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003306 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00003307 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003308 unsigned UniqueCount = NumProtocols;
3309
John McCall54e14c42009-10-22 22:37:11 +00003310 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00003311 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3312 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00003313 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00003314 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3315 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003316 }
3317
3318 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00003319 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3320 }
3321
3322 unsigned Size = sizeof(ObjCObjectTypeImpl);
3323 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3324 void *Mem = Allocate(Size, TypeAlignment);
3325 ObjCObjectTypeImpl *T =
3326 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3327
3328 Types.push_back(T);
3329 ObjCObjectTypes.InsertNode(T, InsertPos);
3330 return QualType(T, 0);
3331}
3332
3333/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3334/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003335QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003336 llvm::FoldingSetNodeID ID;
3337 ObjCObjectPointerType::Profile(ID, ObjectT);
3338
3339 void *InsertPos = 0;
3340 if (ObjCObjectPointerType *QT =
3341 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3342 return QualType(QT, 0);
3343
3344 // Find the canonical object type.
3345 QualType Canonical;
3346 if (!ObjectT.isCanonical()) {
3347 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3348
3349 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00003350 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3351 }
3352
Douglas Gregorfd6a0882010-02-08 22:59:26 +00003353 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00003354 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3355 ObjCObjectPointerType *QType =
3356 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00003357
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003358 Types.push_back(QType);
3359 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00003360 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003361}
Chris Lattner88cb27a2008-04-07 04:56:42 +00003362
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003363/// getObjCInterfaceType - Return the unique reference to the type for the
3364/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00003365QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3366 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003367 if (Decl->TypeForDecl)
3368 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003369
Douglas Gregor0af55012011-12-16 03:12:41 +00003370 if (PrevDecl) {
3371 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3372 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3373 return QualType(PrevDecl->TypeForDecl, 0);
3374 }
3375
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00003376 // Prefer the definition, if there is one.
3377 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3378 Decl = Def;
3379
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003380 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3381 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3382 Decl->TypeForDecl = T;
3383 Types.push_back(T);
3384 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00003385}
3386
Douglas Gregor72564e72009-02-26 23:50:07 +00003387/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3388/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00003389/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00003390/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003391/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003392QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003393 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00003394 if (tofExpr->isTypeDependent()) {
3395 llvm::FoldingSetNodeID ID;
3396 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00003397
Douglas Gregorb1975722009-07-30 23:18:24 +00003398 void *InsertPos = 0;
3399 DependentTypeOfExprType *Canon
3400 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3401 if (Canon) {
3402 // We already have a "canonical" version of an identical, dependent
3403 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00003404 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00003405 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003406 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00003407 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003408 Canon
3409 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00003410 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3411 toe = Canon;
3412 }
3413 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003414 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00003415 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00003416 }
Steve Naroff9752f252007-08-01 18:02:17 +00003417 Types.push_back(toe);
3418 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003419}
3420
Steve Naroff9752f252007-08-01 18:02:17 +00003421/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3422/// TypeOfType AST's. The only motivation to unique these nodes would be
3423/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003424/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003425/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003426QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00003427 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00003428 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00003429 Types.push_back(tot);
3430 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003431}
3432
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00003433
Anders Carlsson395b4752009-06-24 19:06:50 +00003434/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3435/// DecltypeType AST's. The only motivation to unique these nodes would be
3436/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003437/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00003438/// on canonical types (which are always unique).
Douglas Gregorf8af9822012-02-12 18:42:33 +00003439QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003440 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00003441
3442 // C++0x [temp.type]p2:
3443 // If an expression e involves a template parameter, decltype(e) denotes a
3444 // unique dependent type. Two such decltype-specifiers refer to the same
3445 // type only if their expressions are equivalent (14.5.6.1).
3446 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003447 llvm::FoldingSetNodeID ID;
3448 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00003449
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003450 void *InsertPos = 0;
3451 DependentDecltypeType *Canon
3452 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3453 if (Canon) {
3454 // We already have a "canonical" version of an equivalent, dependent
3455 // decltype type. Use that as our canonical type.
Richard Smith0d729102012-08-13 20:08:14 +00003456 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003457 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003458 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003459 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003460 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003461 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3462 dt = Canon;
3463 }
3464 } else {
Douglas Gregorf8af9822012-02-12 18:42:33 +00003465 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3466 getCanonicalType(UnderlyingType));
Douglas Gregordd0257c2009-07-08 00:03:05 +00003467 }
Anders Carlsson395b4752009-06-24 19:06:50 +00003468 Types.push_back(dt);
3469 return QualType(dt, 0);
3470}
3471
Sean Huntca63c202011-05-24 22:41:36 +00003472/// getUnaryTransformationType - We don't unique these, since the memory
3473/// savings are minimal and these are rare.
3474QualType ASTContext::getUnaryTransformType(QualType BaseType,
3475 QualType UnderlyingType,
3476 UnaryTransformType::UTTKind Kind)
3477 const {
3478 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00003479 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3480 Kind,
3481 UnderlyingType->isDependentType() ?
Peter Collingbourne12fc4b02012-03-05 16:02:06 +00003482 QualType() : getCanonicalType(UnderlyingType));
Sean Huntca63c202011-05-24 22:41:36 +00003483 Types.push_back(Ty);
3484 return QualType(Ty, 0);
3485}
3486
Richard Smith483b9f32011-02-21 20:05:19 +00003487/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith34b41d92011-02-20 03:19:35 +00003488QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smith483b9f32011-02-21 20:05:19 +00003489 void *InsertPos = 0;
3490 if (!DeducedType.isNull()) {
3491 // Look in the folding set for an existing type.
3492 llvm::FoldingSetNodeID ID;
3493 AutoType::Profile(ID, DeducedType);
3494 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3495 return QualType(AT, 0);
3496 }
3497
3498 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3499 Types.push_back(AT);
3500 if (InsertPos)
3501 AutoTypes.InsertNode(AT, InsertPos);
3502 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00003503}
3504
Eli Friedmanb001de72011-10-06 23:00:33 +00003505/// getAtomicType - Return the uniqued reference to the atomic type for
3506/// the given value type.
3507QualType ASTContext::getAtomicType(QualType T) const {
3508 // Unique pointers, to guarantee there is only one pointer of a particular
3509 // structure.
3510 llvm::FoldingSetNodeID ID;
3511 AtomicType::Profile(ID, T);
3512
3513 void *InsertPos = 0;
3514 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3515 return QualType(AT, 0);
3516
3517 // If the atomic value type isn't canonical, this won't be a canonical type
3518 // either, so fill in the canonical type field.
3519 QualType Canonical;
3520 if (!T.isCanonical()) {
3521 Canonical = getAtomicType(getCanonicalType(T));
3522
3523 // Get the new insert position for the node we care about.
3524 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3525 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3526 }
3527 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3528 Types.push_back(New);
3529 AtomicTypes.InsertNode(New, InsertPos);
3530 return QualType(New, 0);
3531}
3532
Richard Smithad762fc2011-04-14 22:09:26 +00003533/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3534QualType ASTContext::getAutoDeductType() const {
3535 if (AutoDeductTy.isNull())
3536 AutoDeductTy = getAutoType(QualType());
3537 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3538 return AutoDeductTy;
3539}
3540
3541/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3542QualType ASTContext::getAutoRRefDeductType() const {
3543 if (AutoRRefDeductTy.isNull())
3544 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3545 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3546 return AutoRRefDeductTy;
3547}
3548
Reid Spencer5f016e22007-07-11 17:01:13 +00003549/// getTagDeclType - Return the unique reference to the type for the
3550/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003551QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003552 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003553 // FIXME: What is the design on getTagDeclType when it requires casting
3554 // away const? mutable?
3555 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003556}
3557
Mike Stump1eb44332009-09-09 15:08:12 +00003558/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3559/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3560/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003561CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003562 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003563}
3564
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003565/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3566CanQualType ASTContext::getIntMaxType() const {
3567 return getFromTargetType(Target->getIntMaxType());
3568}
3569
3570/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3571CanQualType ASTContext::getUIntMaxType() const {
3572 return getFromTargetType(Target->getUIntMaxType());
3573}
3574
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003575/// getSignedWCharType - Return the type of "signed wchar_t".
3576/// Used when in C++, as a GCC extension.
3577QualType ASTContext::getSignedWCharType() const {
3578 // FIXME: derive from "Target" ?
3579 return WCharTy;
3580}
3581
3582/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3583/// Used when in C++, as a GCC extension.
3584QualType ASTContext::getUnsignedWCharType() const {
3585 // FIXME: derive from "Target" ?
3586 return UnsignedIntTy;
3587}
3588
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003589/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003590/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3591QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003592 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003593}
3594
Eli Friedman6902e412012-11-27 02:58:24 +00003595/// \brief Return the unique type for "pid_t" defined in
3596/// <sys/types.h>. We need this to compute the correct type for vfork().
3597QualType ASTContext::getProcessIDType() const {
3598 return getFromTargetType(Target->getProcessIDType());
3599}
3600
Chris Lattnere6327742008-04-02 05:18:44 +00003601//===----------------------------------------------------------------------===//
3602// Type Operators
3603//===----------------------------------------------------------------------===//
3604
Jay Foad4ba2a172011-01-12 09:06:06 +00003605CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003606 // Push qualifiers into arrays, and then discard any remaining
3607 // qualifiers.
3608 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003609 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003610 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003611 QualType Result;
3612 if (isa<ArrayType>(Ty)) {
3613 Result = getArrayDecayedType(QualType(Ty,0));
3614 } else if (isa<FunctionType>(Ty)) {
3615 Result = getPointerType(QualType(Ty, 0));
3616 } else {
3617 Result = QualType(Ty, 0);
3618 }
3619
3620 return CanQualType::CreateUnsafe(Result);
3621}
3622
John McCall62c28c82011-01-18 07:41:22 +00003623QualType ASTContext::getUnqualifiedArrayType(QualType type,
3624 Qualifiers &quals) {
3625 SplitQualType splitType = type.getSplitUnqualifiedType();
3626
3627 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3628 // the unqualified desugared type and then drops it on the floor.
3629 // We then have to strip that sugar back off with
3630 // getUnqualifiedDesugaredType(), which is silly.
3631 const ArrayType *AT =
John McCall200fa532012-02-08 00:46:36 +00003632 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall62c28c82011-01-18 07:41:22 +00003633
3634 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003635 if (!AT) {
John McCall200fa532012-02-08 00:46:36 +00003636 quals = splitType.Quals;
3637 return QualType(splitType.Ty, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003638 }
3639
John McCall62c28c82011-01-18 07:41:22 +00003640 // Otherwise, recurse on the array's element type.
3641 QualType elementType = AT->getElementType();
3642 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3643
3644 // If that didn't change the element type, AT has no qualifiers, so we
3645 // can just use the results in splitType.
3646 if (elementType == unqualElementType) {
3647 assert(quals.empty()); // from the recursive call
John McCall200fa532012-02-08 00:46:36 +00003648 quals = splitType.Quals;
3649 return QualType(splitType.Ty, 0);
John McCall62c28c82011-01-18 07:41:22 +00003650 }
3651
3652 // Otherwise, add in the qualifiers from the outermost type, then
3653 // build the type back up.
John McCall200fa532012-02-08 00:46:36 +00003654 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003655
Douglas Gregor9dadd942010-05-17 18:45:21 +00003656 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003657 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003658 CAT->getSizeModifier(), 0);
3659 }
3660
Douglas Gregor9dadd942010-05-17 18:45:21 +00003661 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003662 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003663 }
3664
Douglas Gregor9dadd942010-05-17 18:45:21 +00003665 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003666 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003667 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003668 VAT->getSizeModifier(),
3669 VAT->getIndexTypeCVRQualifiers(),
3670 VAT->getBracketsRange());
3671 }
3672
3673 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003674 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003675 DSAT->getSizeModifier(), 0,
3676 SourceRange());
3677}
3678
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003679/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3680/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3681/// they point to and return true. If T1 and T2 aren't pointer types
3682/// or pointer-to-member types, or if they are not similar at this
3683/// level, returns false and leaves T1 and T2 unchanged. Top-level
3684/// qualifiers on T1 and T2 are ignored. This function will typically
3685/// be called in a loop that successively "unwraps" pointer and
3686/// pointer-to-member types to compare them at each level.
3687bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3688 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3689 *T2PtrType = T2->getAs<PointerType>();
3690 if (T1PtrType && T2PtrType) {
3691 T1 = T1PtrType->getPointeeType();
3692 T2 = T2PtrType->getPointeeType();
3693 return true;
3694 }
3695
3696 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3697 *T2MPType = T2->getAs<MemberPointerType>();
3698 if (T1MPType && T2MPType &&
3699 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3700 QualType(T2MPType->getClass(), 0))) {
3701 T1 = T1MPType->getPointeeType();
3702 T2 = T2MPType->getPointeeType();
3703 return true;
3704 }
3705
David Blaikie4e4d0842012-03-11 07:00:24 +00003706 if (getLangOpts().ObjC1) {
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003707 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3708 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3709 if (T1OPType && T2OPType) {
3710 T1 = T1OPType->getPointeeType();
3711 T2 = T2OPType->getPointeeType();
3712 return true;
3713 }
3714 }
3715
3716 // FIXME: Block pointers, too?
3717
3718 return false;
3719}
3720
Jay Foad4ba2a172011-01-12 09:06:06 +00003721DeclarationNameInfo
3722ASTContext::getNameForTemplate(TemplateName Name,
3723 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003724 switch (Name.getKind()) {
3725 case TemplateName::QualifiedTemplate:
3726 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003727 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003728 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3729 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003730
John McCall14606042011-06-30 08:33:18 +00003731 case TemplateName::OverloadedTemplate: {
3732 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3733 // DNInfo work in progress: CHECKME: what about DNLoc?
3734 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3735 }
3736
3737 case TemplateName::DependentTemplate: {
3738 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003739 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003740 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003741 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3742 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003743 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003744 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3745 // DNInfo work in progress: FIXME: source locations?
3746 DeclarationNameLoc DNLoc;
3747 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3748 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3749 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003750 }
3751 }
3752
John McCall14606042011-06-30 08:33:18 +00003753 case TemplateName::SubstTemplateTemplateParm: {
3754 SubstTemplateTemplateParmStorage *subst
3755 = Name.getAsSubstTemplateTemplateParm();
3756 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3757 NameLoc);
3758 }
3759
3760 case TemplateName::SubstTemplateTemplateParmPack: {
3761 SubstTemplateTemplateParmPackStorage *subst
3762 = Name.getAsSubstTemplateTemplateParmPack();
3763 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3764 NameLoc);
3765 }
3766 }
3767
3768 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003769}
3770
Jay Foad4ba2a172011-01-12 09:06:06 +00003771TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003772 switch (Name.getKind()) {
3773 case TemplateName::QualifiedTemplate:
3774 case TemplateName::Template: {
3775 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003776 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003777 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003778 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3779
3780 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003781 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003782 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003783
John McCall14606042011-06-30 08:33:18 +00003784 case TemplateName::OverloadedTemplate:
3785 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003786
John McCall14606042011-06-30 08:33:18 +00003787 case TemplateName::DependentTemplate: {
3788 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3789 assert(DTN && "Non-dependent template names must refer to template decls.");
3790 return DTN->CanonicalTemplateName;
3791 }
3792
3793 case TemplateName::SubstTemplateTemplateParm: {
3794 SubstTemplateTemplateParmStorage *subst
3795 = Name.getAsSubstTemplateTemplateParm();
3796 return getCanonicalTemplateName(subst->getReplacement());
3797 }
3798
3799 case TemplateName::SubstTemplateTemplateParmPack: {
3800 SubstTemplateTemplateParmPackStorage *subst
3801 = Name.getAsSubstTemplateTemplateParmPack();
3802 TemplateTemplateParmDecl *canonParameter
3803 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3804 TemplateArgument canonArgPack
3805 = getCanonicalTemplateArgument(subst->getArgumentPack());
3806 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3807 }
3808 }
3809
3810 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003811}
3812
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003813bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3814 X = getCanonicalTemplateName(X);
3815 Y = getCanonicalTemplateName(Y);
3816 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3817}
3818
Mike Stump1eb44332009-09-09 15:08:12 +00003819TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003820ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003821 switch (Arg.getKind()) {
3822 case TemplateArgument::Null:
3823 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003824
Douglas Gregor1275ae02009-07-28 23:00:59 +00003825 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003826 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003827
Douglas Gregord2008e22012-04-06 22:40:38 +00003828 case TemplateArgument::Declaration: {
Eli Friedmand7a6b162012-09-26 02:36:12 +00003829 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
3830 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregord2008e22012-04-06 22:40:38 +00003831 }
Mike Stump1eb44332009-09-09 15:08:12 +00003832
Eli Friedmand7a6b162012-09-26 02:36:12 +00003833 case TemplateArgument::NullPtr:
3834 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
3835 /*isNullPtr*/true);
3836
Douglas Gregor788cd062009-11-11 01:00:40 +00003837 case TemplateArgument::Template:
3838 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003839
3840 case TemplateArgument::TemplateExpansion:
3841 return TemplateArgument(getCanonicalTemplateName(
3842 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00003843 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00003844
Douglas Gregor1275ae02009-07-28 23:00:59 +00003845 case TemplateArgument::Integral:
Benjamin Kramer85524372012-06-07 15:09:51 +00003846 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003847
Douglas Gregor1275ae02009-07-28 23:00:59 +00003848 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00003849 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003850
Douglas Gregor1275ae02009-07-28 23:00:59 +00003851 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00003852 if (Arg.pack_size() == 0)
3853 return Arg;
3854
Douglas Gregor910f8002010-11-07 23:05:16 +00003855 TemplateArgument *CanonArgs
3856 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00003857 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003858 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003859 AEnd = Arg.pack_end();
3860 A != AEnd; (void)++A, ++Idx)
3861 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00003862
Douglas Gregor910f8002010-11-07 23:05:16 +00003863 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00003864 }
3865 }
3866
3867 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00003868 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00003869}
3870
Douglas Gregord57959a2009-03-27 23:10:48 +00003871NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00003872ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00003873 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00003874 return 0;
3875
3876 switch (NNS->getKind()) {
3877 case NestedNameSpecifier::Identifier:
3878 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00003879 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00003880 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3881 NNS->getAsIdentifier());
3882
3883 case NestedNameSpecifier::Namespace:
3884 // A namespace is canonical; build a nested-name-specifier with
3885 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00003886 return NestedNameSpecifier::Create(*this, 0,
3887 NNS->getAsNamespace()->getOriginalNamespace());
3888
3889 case NestedNameSpecifier::NamespaceAlias:
3890 // A namespace is canonical; build a nested-name-specifier with
3891 // this namespace and no prefix.
3892 return NestedNameSpecifier::Create(*this, 0,
3893 NNS->getAsNamespaceAlias()->getNamespace()
3894 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00003895
3896 case NestedNameSpecifier::TypeSpec:
3897 case NestedNameSpecifier::TypeSpecWithTemplate: {
3898 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00003899
3900 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3901 // break it apart into its prefix and identifier, then reconsititute those
3902 // as the canonical nested-name-specifier. This is required to canonicalize
3903 // a dependent nested-name-specifier involving typedefs of dependent-name
3904 // types, e.g.,
3905 // typedef typename T::type T1;
3906 // typedef typename T1::type T2;
Eli Friedman16412ef2012-03-03 04:09:56 +00003907 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3908 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor264bf662010-11-04 00:09:33 +00003909 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor264bf662010-11-04 00:09:33 +00003910
Eli Friedman16412ef2012-03-03 04:09:56 +00003911 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3912 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3913 // first place?
John McCall3b657512011-01-19 10:06:00 +00003914 return NestedNameSpecifier::Create(*this, 0, false,
3915 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00003916 }
3917
3918 case NestedNameSpecifier::Global:
3919 // The global specifier is canonical and unique.
3920 return NNS;
3921 }
3922
David Blaikie7530c032012-01-17 06:56:22 +00003923 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregord57959a2009-03-27 23:10:48 +00003924}
3925
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003926
Jay Foad4ba2a172011-01-12 09:06:06 +00003927const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003928 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003929 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003930 // Handle the common positive case fast.
3931 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3932 return AT;
3933 }
Mike Stump1eb44332009-09-09 15:08:12 +00003934
John McCall0953e762009-09-24 19:53:00 +00003935 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003936 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003937 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003938
John McCall0953e762009-09-24 19:53:00 +00003939 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003940 // implements C99 6.7.3p8: "If the specification of an array type includes
3941 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00003942
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003943 // If we get here, we either have type qualifiers on the type, or we have
3944 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00003945 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003946
John McCall3b657512011-01-19 10:06:00 +00003947 SplitQualType split = T.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00003948 Qualifiers qs = split.Quals;
Mike Stump1eb44332009-09-09 15:08:12 +00003949
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003950 // If we have a simple case, just return now.
John McCall200fa532012-02-08 00:46:36 +00003951 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall3b657512011-01-19 10:06:00 +00003952 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003953 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003954
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003955 // Otherwise, we have an array and we have qualifiers on it. Push the
3956 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00003957 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003958
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003959 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3960 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3961 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003962 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003963 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3964 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3965 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003966 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00003967
Mike Stump1eb44332009-09-09 15:08:12 +00003968 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00003969 = dyn_cast<DependentSizedArrayType>(ATy))
3970 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00003971 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003972 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00003973 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003974 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003975 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00003976
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003977 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003978 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003979 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003980 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003981 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003982 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00003983}
3984
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00003985QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003986 // C99 6.7.5.3p7:
3987 // A declaration of a parameter as "array of type" shall be
3988 // adjusted to "qualified pointer to type", where the type
3989 // qualifiers (if any) are those specified within the [ and ] of
3990 // the array type derivation.
3991 if (T->isArrayType())
3992 return getArrayDecayedType(T);
3993
3994 // C99 6.7.5.3p8:
3995 // A declaration of a parameter as "function returning type"
3996 // shall be adjusted to "pointer to function returning type", as
3997 // in 6.3.2.1.
3998 if (T->isFunctionType())
3999 return getPointerType(T);
4000
4001 return T;
4002}
4003
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004004QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004005 T = getVariableArrayDecayedType(T);
4006 T = getAdjustedParameterType(T);
4007 return T.getUnqualifiedType();
4008}
4009
Chris Lattnere6327742008-04-02 05:18:44 +00004010/// getArrayDecayedType - Return the properly qualified result of decaying the
4011/// specified array type to a pointer. This operation is non-trivial when
4012/// handling typedefs etc. The canonical type of "T" must be an array type,
4013/// this returns a pointer to a properly qualified element of the array.
4014///
4015/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00004016QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004017 // Get the element type with 'getAsArrayType' so that we don't lose any
4018 // typedefs in the element type of the array. This also handles propagation
4019 // of type qualifiers from the array type into the element type if present
4020 // (C99 6.7.3p8).
4021 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4022 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00004023
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004024 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00004025
4026 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00004027 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00004028}
4029
John McCall3b657512011-01-19 10:06:00 +00004030QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4031 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00004032}
4033
John McCall3b657512011-01-19 10:06:00 +00004034QualType ASTContext::getBaseElementType(QualType type) const {
4035 Qualifiers qs;
4036 while (true) {
4037 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004038 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall3b657512011-01-19 10:06:00 +00004039 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00004040
John McCall3b657512011-01-19 10:06:00 +00004041 type = array->getElementType();
John McCall200fa532012-02-08 00:46:36 +00004042 qs.addConsistentQualifiers(split.Quals);
John McCall3b657512011-01-19 10:06:00 +00004043 }
Mike Stump1eb44332009-09-09 15:08:12 +00004044
John McCall3b657512011-01-19 10:06:00 +00004045 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00004046}
4047
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004048/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00004049uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004050ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4051 uint64_t ElementCount = 1;
4052 do {
4053 ElementCount *= CA->getSize().getZExtValue();
Richard Smithd5e83942012-12-06 03:04:50 +00004054 CA = dyn_cast_or_null<ConstantArrayType>(
4055 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004056 } while (CA);
4057 return ElementCount;
4058}
4059
Reid Spencer5f016e22007-07-11 17:01:13 +00004060/// getFloatingRank - Return a relative rank for floating point types.
4061/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00004062static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00004063 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00004064 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00004065
John McCall183700f2009-09-21 23:43:11 +00004066 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4067 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004068 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00004069 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00004070 case BuiltinType::Float: return FloatRank;
4071 case BuiltinType::Double: return DoubleRank;
4072 case BuiltinType::LongDouble: return LongDoubleRank;
4073 }
4074}
4075
Mike Stump1eb44332009-09-09 15:08:12 +00004076/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4077/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00004078/// 'typeDomain' is a real floating point or complex type.
4079/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00004080QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4081 QualType Domain) const {
4082 FloatingRank EltRank = getFloatingRank(Size);
4083 if (Domain->isComplexType()) {
4084 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00004085 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Narofff1448a02007-08-27 01:27:54 +00004086 case FloatRank: return FloatComplexTy;
4087 case DoubleRank: return DoubleComplexTy;
4088 case LongDoubleRank: return LongDoubleComplexTy;
4089 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004090 }
Chris Lattner1361b112008-04-06 23:58:54 +00004091
4092 assert(Domain->isRealFloatingType() && "Unknown domain!");
4093 switch (EltRank) {
Joey Gouly19dbb202013-01-23 11:56:20 +00004094 case HalfRank: return HalfTy;
Chris Lattner1361b112008-04-06 23:58:54 +00004095 case FloatRank: return FloatTy;
4096 case DoubleRank: return DoubleTy;
4097 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00004098 }
David Blaikie561d3ab2012-01-17 02:30:50 +00004099 llvm_unreachable("getFloatingRank(): illegal value for rank");
Reid Spencer5f016e22007-07-11 17:01:13 +00004100}
4101
Chris Lattner7cfeb082008-04-06 23:55:33 +00004102/// getFloatingTypeOrder - Compare the rank of the two specified floating
4103/// point types, ignoring the domain of the type (i.e. 'double' ==
4104/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004105/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004106int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00004107 FloatingRank LHSR = getFloatingRank(LHS);
4108 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004109
Chris Lattnera75cea32008-04-06 23:38:49 +00004110 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004111 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00004112 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004113 return 1;
4114 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004115}
4116
Chris Lattnerf52ab252008-04-06 22:59:24 +00004117/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4118/// routine will assert if passed a built-in type that isn't an integer or enum,
4119/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00004120unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00004121 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00004122
Chris Lattnerf52ab252008-04-06 22:59:24 +00004123 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004124 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00004125 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004126 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004127 case BuiltinType::Char_S:
4128 case BuiltinType::Char_U:
4129 case BuiltinType::SChar:
4130 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004131 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004132 case BuiltinType::Short:
4133 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004134 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004135 case BuiltinType::Int:
4136 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004137 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004138 case BuiltinType::Long:
4139 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004140 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004141 case BuiltinType::LongLong:
4142 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004143 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00004144 case BuiltinType::Int128:
4145 case BuiltinType::UInt128:
4146 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00004147 }
4148}
4149
Eli Friedman04e83572009-08-20 04:21:42 +00004150/// \brief Whether this is a promotable bitfield reference according
4151/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4152///
4153/// \returns the type this bit-field will promote to, or NULL if no
4154/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00004155QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00004156 if (E->isTypeDependent() || E->isValueDependent())
4157 return QualType();
4158
Eli Friedman04e83572009-08-20 04:21:42 +00004159 FieldDecl *Field = E->getBitField();
4160 if (!Field)
4161 return QualType();
4162
4163 QualType FT = Field->getType();
4164
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004165 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00004166 uint64_t IntSize = getTypeSize(IntTy);
4167 // GCC extension compatibility: if the bit-field size is less than or equal
4168 // to the size of int, it gets promoted no matter what its type is.
4169 // For instance, unsigned long bf : 4 gets promoted to signed int.
4170 if (BitWidth < IntSize)
4171 return IntTy;
4172
4173 if (BitWidth == IntSize)
4174 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4175
4176 // Types bigger than int are not subject to promotions, and therefore act
4177 // like the base type.
4178 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4179 // is ridiculous.
4180 return QualType();
4181}
4182
Eli Friedmana95d7572009-08-19 07:44:53 +00004183/// getPromotedIntegerType - Returns the type that Promotable will
4184/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4185/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00004186QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00004187 assert(!Promotable.isNull());
4188 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00004189 if (const EnumType *ET = Promotable->getAs<EnumType>())
4190 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00004191
4192 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4193 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4194 // (3.9.1) can be converted to a prvalue of the first of the following
4195 // types that can represent all the values of its underlying type:
4196 // int, unsigned int, long int, unsigned long int, long long int, or
4197 // unsigned long long int [...]
4198 // FIXME: Is there some better way to compute this?
4199 if (BT->getKind() == BuiltinType::WChar_S ||
4200 BT->getKind() == BuiltinType::WChar_U ||
4201 BT->getKind() == BuiltinType::Char16 ||
4202 BT->getKind() == BuiltinType::Char32) {
4203 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4204 uint64_t FromSize = getTypeSize(BT);
4205 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4206 LongLongTy, UnsignedLongLongTy };
4207 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4208 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4209 if (FromSize < ToSize ||
4210 (FromSize == ToSize &&
4211 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4212 return PromoteTypes[Idx];
4213 }
4214 llvm_unreachable("char type should fit into long long");
4215 }
4216 }
4217
4218 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00004219 if (Promotable->isSignedIntegerType())
4220 return IntTy;
Eli Friedman5b64e772012-11-15 01:21:59 +00004221 uint64_t PromotableSize = getIntWidth(Promotable);
4222 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedmana95d7572009-08-19 07:44:53 +00004223 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4224 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4225}
4226
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004227/// \brief Recurses in pointer/array types until it finds an objc retainable
4228/// type and returns its ownership.
4229Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4230 while (!T.isNull()) {
4231 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4232 return T.getObjCLifetime();
4233 if (T->isArrayType())
4234 T = getBaseElementType(T);
4235 else if (const PointerType *PT = T->getAs<PointerType>())
4236 T = PT->getPointeeType();
4237 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00004238 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004239 else
4240 break;
4241 }
4242
4243 return Qualifiers::OCL_None;
4244}
4245
Mike Stump1eb44332009-09-09 15:08:12 +00004246/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00004247/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004248/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004249int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00004250 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4251 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00004252 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004253
Chris Lattnerf52ab252008-04-06 22:59:24 +00004254 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4255 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00004256
Chris Lattner7cfeb082008-04-06 23:55:33 +00004257 unsigned LHSRank = getIntegerRank(LHSC);
4258 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00004259
Chris Lattner7cfeb082008-04-06 23:55:33 +00004260 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4261 if (LHSRank == RHSRank) return 0;
4262 return LHSRank > RHSRank ? 1 : -1;
4263 }
Mike Stump1eb44332009-09-09 15:08:12 +00004264
Chris Lattner7cfeb082008-04-06 23:55:33 +00004265 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4266 if (LHSUnsigned) {
4267 // If the unsigned [LHS] type is larger, return it.
4268 if (LHSRank >= RHSRank)
4269 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004270
Chris Lattner7cfeb082008-04-06 23:55:33 +00004271 // If the signed type can represent all values of the unsigned type, it
4272 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004273 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004274 return -1;
4275 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00004276
Chris Lattner7cfeb082008-04-06 23:55:33 +00004277 // If the unsigned [RHS] type is larger, return it.
4278 if (RHSRank >= LHSRank)
4279 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00004280
Chris Lattner7cfeb082008-04-06 23:55:33 +00004281 // If the signed type can represent all values of the unsigned type, it
4282 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004283 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004284 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004285}
Anders Carlsson71993dd2007-08-17 05:31:46 +00004286
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004287static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004288CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4289 DeclContext *DC, IdentifierInfo *Id) {
4290 SourceLocation Loc;
David Blaikie4e4d0842012-03-11 07:00:24 +00004291 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004292 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004293 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004294 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004295}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004296
Mike Stump1eb44332009-09-09 15:08:12 +00004297// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00004298QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00004299 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004300 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004301 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004302 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00004303 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004304
Anders Carlssonf06273f2007-11-19 00:25:30 +00004305 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00004306
Anders Carlsson71993dd2007-08-17 05:31:46 +00004307 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00004308 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00004309 // int flags;
4310 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00004311 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00004312 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00004313 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00004314 FieldTypes[3] = LongTy;
4315
Anders Carlsson71993dd2007-08-17 05:31:46 +00004316 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00004317 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00004318 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004319 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00004320 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00004321 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00004322 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004323 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004324 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004325 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004326 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00004327 }
4328
Douglas Gregor838db382010-02-11 01:19:42 +00004329 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00004330 }
Mike Stump1eb44332009-09-09 15:08:12 +00004331
Anders Carlsson71993dd2007-08-17 05:31:46 +00004332 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00004333}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004334
Fariborz Jahanianf7992132013-01-04 18:45:40 +00004335QualType ASTContext::getObjCSuperType() const {
4336 if (ObjCSuperType.isNull()) {
4337 RecordDecl *ObjCSuperTypeDecl =
4338 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4339 TUDecl->addDecl(ObjCSuperTypeDecl);
4340 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4341 }
4342 return ObjCSuperType;
4343}
4344
Douglas Gregor319ac892009-04-23 22:29:11 +00004345void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004346 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00004347 assert(Rec && "Invalid CFConstantStringType");
4348 CFConstantStringTypeDecl = Rec->getDecl();
4349}
4350
Jay Foad4ba2a172011-01-12 09:06:06 +00004351QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00004352 if (BlockDescriptorType)
4353 return getTagDeclType(BlockDescriptorType);
4354
4355 RecordDecl *T;
4356 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004357 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004358 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00004359 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004360
4361 QualType FieldTypes[] = {
4362 UnsignedLongTy,
4363 UnsignedLongTy,
4364 };
4365
4366 const char *FieldNames[] = {
4367 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00004368 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00004369 };
4370
4371 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004372 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00004373 SourceLocation(),
4374 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004375 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00004376 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004377 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004378 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004379 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00004380 T->addDecl(Field);
4381 }
4382
Douglas Gregor838db382010-02-11 01:19:42 +00004383 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004384
4385 BlockDescriptorType = T;
4386
4387 return getTagDeclType(BlockDescriptorType);
4388}
4389
Jay Foad4ba2a172011-01-12 09:06:06 +00004390QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00004391 if (BlockDescriptorExtendedType)
4392 return getTagDeclType(BlockDescriptorExtendedType);
4393
4394 RecordDecl *T;
4395 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004396 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004397 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00004398 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004399
4400 QualType FieldTypes[] = {
4401 UnsignedLongTy,
4402 UnsignedLongTy,
4403 getPointerType(VoidPtrTy),
4404 getPointerType(VoidPtrTy)
4405 };
4406
4407 const char *FieldNames[] = {
4408 "reserved",
4409 "Size",
4410 "CopyFuncPtr",
4411 "DestroyFuncPtr"
4412 };
4413
4414 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004415 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00004416 SourceLocation(),
4417 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004418 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00004419 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004420 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004421 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004422 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00004423 T->addDecl(Field);
4424 }
4425
Douglas Gregor838db382010-02-11 01:19:42 +00004426 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004427
4428 BlockDescriptorExtendedType = T;
4429
4430 return getTagDeclType(BlockDescriptorExtendedType);
4431}
4432
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004433/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4434/// requires copy/dispose. Note that this must match the logic
4435/// in buildByrefHelpers.
4436bool ASTContext::BlockRequiresCopying(QualType Ty,
4437 const VarDecl *D) {
4438 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4439 const Expr *copyExpr = getBlockVarCopyInits(D);
4440 if (!copyExpr && record->hasTrivialDestructor()) return false;
4441
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004442 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00004443 }
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004444
4445 if (!Ty->isObjCRetainableType()) return false;
4446
4447 Qualifiers qs = Ty.getQualifiers();
4448
4449 // If we have lifetime, that dominates.
4450 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4451 assert(getLangOpts().ObjCAutoRefCount);
4452
4453 switch (lifetime) {
4454 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4455
4456 // These are just bits as far as the runtime is concerned.
4457 case Qualifiers::OCL_ExplicitNone:
4458 case Qualifiers::OCL_Autoreleasing:
4459 return false;
4460
4461 // Tell the runtime that this is ARC __weak, called by the
4462 // byref routines.
4463 case Qualifiers::OCL_Weak:
4464 // ARC __strong __block variables need to be retained.
4465 case Qualifiers::OCL_Strong:
4466 return true;
4467 }
4468 llvm_unreachable("fell out of lifetime switch!");
4469 }
4470 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4471 Ty->isObjCObjectPointerType());
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004472}
4473
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004474bool ASTContext::getByrefLifetime(QualType Ty,
4475 Qualifiers::ObjCLifetime &LifeTime,
4476 bool &HasByrefExtendedLayout) const {
4477
4478 if (!getLangOpts().ObjC1 ||
4479 getLangOpts().getGC() != LangOptions::NonGC)
4480 return false;
4481
4482 HasByrefExtendedLayout = false;
Fariborz Jahanian34db84f2012-12-11 19:58:01 +00004483 if (Ty->isRecordType()) {
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004484 HasByrefExtendedLayout = true;
4485 LifeTime = Qualifiers::OCL_None;
4486 }
4487 else if (getLangOpts().ObjCAutoRefCount)
4488 LifeTime = Ty.getObjCLifetime();
4489 // MRR.
4490 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4491 LifeTime = Qualifiers::OCL_ExplicitNone;
4492 else
4493 LifeTime = Qualifiers::OCL_None;
4494 return true;
4495}
4496
Douglas Gregore97179c2011-09-08 01:46:34 +00004497TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4498 if (!ObjCInstanceTypeDecl)
4499 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4500 getTranslationUnitDecl(),
4501 SourceLocation(),
4502 SourceLocation(),
4503 &Idents.get("instancetype"),
4504 getTrivialTypeSourceInfo(getObjCIdType()));
4505 return ObjCInstanceTypeDecl;
4506}
4507
Anders Carlssone8c49532007-10-29 06:33:42 +00004508// This returns true if a type has been typedefed to BOOL:
4509// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00004510static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00004511 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00004512 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4513 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00004514
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004515 return false;
4516}
4517
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004518/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004519/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00004520CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00004521 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4522 return CharUnits::Zero();
4523
Ken Dyck199c3d62010-01-11 17:06:35 +00004524 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004525
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004526 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004527 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004528 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004529 // Treat arrays as pointers, since that's how they're passed in.
4530 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004531 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004532 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004533}
4534
4535static inline
4536std::string charUnitsToString(const CharUnits &CU) {
4537 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004538}
4539
John McCall6b5a61b2011-02-07 10:33:21 +00004540/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004541/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004542std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4543 std::string S;
4544
David Chisnall5e530af2009-11-17 19:33:30 +00004545 const BlockDecl *Decl = Expr->getBlockDecl();
4546 QualType BlockTy =
4547 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4548 // Encode result type.
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004549 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004550 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4551 BlockTy->getAs<FunctionType>()->getResultType(),
4552 S, true /*Extended*/);
4553 else
4554 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4555 S);
David Chisnall5e530af2009-11-17 19:33:30 +00004556 // Compute size of all parameters.
4557 // Start with computing size of a pointer in number of bytes.
4558 // FIXME: There might(should) be a better way of doing this computation!
4559 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004560 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4561 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004562 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004563 E = Decl->param_end(); PI != E; ++PI) {
4564 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004565 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahanian075a5432012-06-30 00:48:59 +00004566 if (sz.isZero())
4567 continue;
Ken Dyck199c3d62010-01-11 17:06:35 +00004568 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004569 ParmOffset += sz;
4570 }
4571 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004572 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004573 // Block pointer and offset.
4574 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004575
4576 // Argument types.
4577 ParmOffset = PtrSize;
4578 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4579 Decl->param_end(); PI != E; ++PI) {
4580 ParmVarDecl *PVDecl = *PI;
4581 QualType PType = PVDecl->getOriginalType();
4582 if (const ArrayType *AT =
4583 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4584 // Use array's original type only if it has known number of
4585 // elements.
4586 if (!isa<ConstantArrayType>(AT))
4587 PType = PVDecl->getType();
4588 } else if (PType->isFunctionType())
4589 PType = PVDecl->getType();
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004590 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004591 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4592 S, true /*Extended*/);
4593 else
4594 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004595 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004596 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004597 }
John McCall6b5a61b2011-02-07 10:33:21 +00004598
4599 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004600}
4601
Douglas Gregorf968d832011-05-27 01:19:52 +00004602bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004603 std::string& S) {
4604 // Encode result type.
4605 getObjCEncodingForType(Decl->getResultType(), S);
4606 CharUnits ParmOffset;
4607 // Compute size of all parameters.
4608 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4609 E = Decl->param_end(); PI != E; ++PI) {
4610 QualType PType = (*PI)->getType();
4611 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004612 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004613 continue;
4614
David Chisnall5389f482010-12-30 14:05:53 +00004615 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004616 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004617 ParmOffset += sz;
4618 }
4619 S += charUnitsToString(ParmOffset);
4620 ParmOffset = CharUnits::Zero();
4621
4622 // Argument types.
4623 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4624 E = Decl->param_end(); PI != E; ++PI) {
4625 ParmVarDecl *PVDecl = *PI;
4626 QualType PType = PVDecl->getOriginalType();
4627 if (const ArrayType *AT =
4628 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4629 // Use array's original type only if it has known number of
4630 // elements.
4631 if (!isa<ConstantArrayType>(AT))
4632 PType = PVDecl->getType();
4633 } else if (PType->isFunctionType())
4634 PType = PVDecl->getType();
4635 getObjCEncodingForType(PType, S);
4636 S += charUnitsToString(ParmOffset);
4637 ParmOffset += getObjCEncodingTypeSize(PType);
4638 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004639
4640 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004641}
4642
Bob Wilsondc8dab62011-11-30 01:57:58 +00004643/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4644/// method parameter or return type. If Extended, include class names and
4645/// block object types.
4646void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4647 QualType T, std::string& S,
4648 bool Extended) const {
4649 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4650 getObjCEncodingForTypeQualifier(QT, S);
4651 // Encode parameter type.
4652 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4653 true /*OutermostType*/,
4654 false /*EncodingProperty*/,
4655 false /*StructField*/,
4656 Extended /*EncodeBlockParameters*/,
4657 Extended /*EncodeClassNames*/);
4658}
4659
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004660/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004661/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004662bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004663 std::string& S,
4664 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004665 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004666 // Encode return type.
4667 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4668 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004669 // Compute size of all parameters.
4670 // Start with computing size of a pointer in number of bytes.
4671 // FIXME: There might(should) be a better way of doing this computation!
4672 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004673 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004674 // The first two arguments (self and _cmd) are pointers; account for
4675 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004676 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004677 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004678 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004679 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004680 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004681 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004682 continue;
4683
Ken Dyck199c3d62010-01-11 17:06:35 +00004684 assert (sz.isPositive() &&
4685 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004686 ParmOffset += sz;
4687 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004688 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004689 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004690 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004691
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004692 // Argument types.
4693 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004694 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004695 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004696 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004697 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004698 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004699 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4700 // Use array's original type only if it has known number of
4701 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004702 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004703 PType = PVDecl->getType();
4704 } else if (PType->isFunctionType())
4705 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004706 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4707 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004708 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004709 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004710 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004711
4712 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004713}
4714
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004715/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004716/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004717/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4718/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004719/// Property attributes are stored as a comma-delimited C string. The simple
4720/// attributes readonly and bycopy are encoded as single characters. The
4721/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4722/// encoded as single characters, followed by an identifier. Property types
4723/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004724/// these attributes are defined by the following enumeration:
4725/// @code
4726/// enum PropertyAttributes {
4727/// kPropertyReadOnly = 'R', // property is read-only.
4728/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4729/// kPropertyByref = '&', // property is a reference to the value last assigned
4730/// kPropertyDynamic = 'D', // property is dynamic
4731/// kPropertyGetter = 'G', // followed by getter selector name
4732/// kPropertySetter = 'S', // followed by setter selector name
4733/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson0d4cb852012-03-22 17:48:02 +00004734/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004735/// kPropertyWeak = 'W' // 'weak' property
4736/// kPropertyStrong = 'P' // property GC'able
4737/// kPropertyNonAtomic = 'N' // property non-atomic
4738/// };
4739/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004740void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004741 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004742 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004743 // Collect information from the property implementation decl(s).
4744 bool Dynamic = false;
4745 ObjCPropertyImplDecl *SynthesizePID = 0;
4746
4747 // FIXME: Duplicated code due to poor abstraction.
4748 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004749 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004750 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4751 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004752 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004753 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004754 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004755 if (PID->getPropertyDecl() == PD) {
4756 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4757 Dynamic = true;
4758 } else {
4759 SynthesizePID = PID;
4760 }
4761 }
4762 }
4763 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004764 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004765 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004766 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004767 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004768 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004769 if (PID->getPropertyDecl() == PD) {
4770 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4771 Dynamic = true;
4772 } else {
4773 SynthesizePID = PID;
4774 }
4775 }
Mike Stump1eb44332009-09-09 15:08:12 +00004776 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004777 }
4778 }
4779
4780 // FIXME: This is not very efficient.
4781 S = "T";
4782
4783 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004784 // GCC has some special rules regarding encoding of properties which
4785 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004786 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004787 true /* outermost type */,
4788 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004789
4790 if (PD->isReadOnly()) {
4791 S += ",R";
4792 } else {
4793 switch (PD->getSetterKind()) {
4794 case ObjCPropertyDecl::Assign: break;
4795 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004796 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004797 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004798 }
4799 }
4800
4801 // It really isn't clear at all what this means, since properties
4802 // are "dynamic by default".
4803 if (Dynamic)
4804 S += ",D";
4805
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004806 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4807 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004808
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004809 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4810 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004811 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004812 }
4813
4814 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4815 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004816 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004817 }
4818
4819 if (SynthesizePID) {
4820 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4821 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004822 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004823 }
4824
4825 // FIXME: OBJCGC: weak & strong
4826}
4827
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004828/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004829/// Another legacy compatibility encoding: 32-bit longs are encoded as
4830/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004831/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4832///
4833void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004834 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004835 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004836 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004837 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004838 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004839 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004840 PointeeTy = IntTy;
4841 }
4842 }
4843}
4844
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004845void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00004846 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004847 // We follow the behavior of gcc, expanding structures which are
4848 // directly pointed to, and expanding embedded structures. Note that
4849 // these rules are sufficient to prevent recursive encoding of the
4850 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00004851 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00004852 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004853}
4854
John McCall3624e9e2012-12-20 02:45:14 +00004855static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
4856 BuiltinType::Kind kind) {
4857 switch (kind) {
David Chisnall64fd7e82010-06-04 01:10:52 +00004858 case BuiltinType::Void: return 'v';
4859 case BuiltinType::Bool: return 'B';
4860 case BuiltinType::Char_U:
4861 case BuiltinType::UChar: return 'C';
John McCall3624e9e2012-12-20 02:45:14 +00004862 case BuiltinType::Char16:
David Chisnall64fd7e82010-06-04 01:10:52 +00004863 case BuiltinType::UShort: return 'S';
John McCall3624e9e2012-12-20 02:45:14 +00004864 case BuiltinType::Char32:
David Chisnall64fd7e82010-06-04 01:10:52 +00004865 case BuiltinType::UInt: return 'I';
4866 case BuiltinType::ULong:
John McCall3624e9e2012-12-20 02:45:14 +00004867 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004868 case BuiltinType::UInt128: return 'T';
4869 case BuiltinType::ULongLong: return 'Q';
4870 case BuiltinType::Char_S:
4871 case BuiltinType::SChar: return 'c';
4872 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00004873 case BuiltinType::WChar_S:
4874 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00004875 case BuiltinType::Int: return 'i';
4876 case BuiltinType::Long:
John McCall3624e9e2012-12-20 02:45:14 +00004877 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004878 case BuiltinType::LongLong: return 'q';
4879 case BuiltinType::Int128: return 't';
4880 case BuiltinType::Float: return 'f';
4881 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00004882 case BuiltinType::LongDouble: return 'D';
John McCall3624e9e2012-12-20 02:45:14 +00004883 case BuiltinType::NullPtr: return '*'; // like char*
4884
4885 case BuiltinType::Half:
4886 // FIXME: potentially need @encodes for these!
4887 return ' ';
4888
4889 case BuiltinType::ObjCId:
4890 case BuiltinType::ObjCClass:
4891 case BuiltinType::ObjCSel:
4892 llvm_unreachable("@encoding ObjC primitive type");
4893
4894 // OpenCL and placeholder types don't need @encodings.
4895 case BuiltinType::OCLImage1d:
4896 case BuiltinType::OCLImage1dArray:
4897 case BuiltinType::OCLImage1dBuffer:
4898 case BuiltinType::OCLImage2d:
4899 case BuiltinType::OCLImage2dArray:
4900 case BuiltinType::OCLImage3d:
Guy Benyeie6b9d802013-01-20 12:31:11 +00004901 case BuiltinType::OCLEvent:
John McCall3624e9e2012-12-20 02:45:14 +00004902 case BuiltinType::Dependent:
4903#define BUILTIN_TYPE(KIND, ID)
4904#define PLACEHOLDER_TYPE(KIND, ID) \
4905 case BuiltinType::KIND:
4906#include "clang/AST/BuiltinTypes.def"
4907 llvm_unreachable("invalid builtin type for @encode");
David Chisnall64fd7e82010-06-04 01:10:52 +00004908 }
David Blaikie719e53f2013-01-09 17:48:41 +00004909 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnall64fd7e82010-06-04 01:10:52 +00004910}
4911
Douglas Gregor5471bc82011-09-08 17:18:35 +00004912static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4913 EnumDecl *Enum = ET->getDecl();
4914
4915 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4916 if (!Enum->isFixed())
4917 return 'i';
4918
4919 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall3624e9e2012-12-20 02:45:14 +00004920 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
4921 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor5471bc82011-09-08 17:18:35 +00004922}
4923
Jay Foad4ba2a172011-01-12 09:06:06 +00004924static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00004925 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004926 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004927 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00004928 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4929 // The GNU runtime requires more information; bitfields are encoded as b,
4930 // then the offset (in bits) of the first element, then the type of the
4931 // bitfield, then the size in bits. For example, in this structure:
4932 //
4933 // struct
4934 // {
4935 // int integer;
4936 // int flags:2;
4937 // };
4938 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4939 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4940 // information is not especially sensible, but we're stuck with it for
4941 // compatibility with GCC, although providing it breaks anything that
4942 // actually uses runtime introspection and wants to work on both runtimes...
John McCall260611a2012-06-20 06:18:46 +00004943 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnall64fd7e82010-06-04 01:10:52 +00004944 const RecordDecl *RD = FD->getParent();
4945 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00004946 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00004947 if (const EnumType *ET = T->getAs<EnumType>())
4948 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall3624e9e2012-12-20 02:45:14 +00004949 else {
4950 const BuiltinType *BT = T->castAs<BuiltinType>();
4951 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
4952 }
David Chisnall64fd7e82010-06-04 01:10:52 +00004953 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004954 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004955}
4956
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004957// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004958void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4959 bool ExpandPointedToStructures,
4960 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004961 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004962 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004963 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004964 bool StructField,
4965 bool EncodeBlockParameters,
4966 bool EncodeClassNames) const {
John McCall3624e9e2012-12-20 02:45:14 +00004967 CanQualType CT = getCanonicalType(T);
4968 switch (CT->getTypeClass()) {
4969 case Type::Builtin:
4970 case Type::Enum:
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004971 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004972 return EncodeBitField(this, S, T, FD);
John McCall3624e9e2012-12-20 02:45:14 +00004973 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
4974 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
4975 else
4976 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004977 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004978
John McCall3624e9e2012-12-20 02:45:14 +00004979 case Type::Complex: {
4980 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004981 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00004982 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004983 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004984 return;
4985 }
John McCall3624e9e2012-12-20 02:45:14 +00004986
4987 case Type::Atomic: {
4988 const AtomicType *AT = T->castAs<AtomicType>();
4989 S += 'A';
4990 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
4991 false, false);
4992 return;
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004993 }
John McCall3624e9e2012-12-20 02:45:14 +00004994
4995 // encoding for pointer or reference types.
4996 case Type::Pointer:
4997 case Type::LValueReference:
4998 case Type::RValueReference: {
4999 QualType PointeeTy;
5000 if (isa<PointerType>(CT)) {
5001 const PointerType *PT = T->castAs<PointerType>();
5002 if (PT->isObjCSelType()) {
5003 S += ':';
5004 return;
5005 }
5006 PointeeTy = PT->getPointeeType();
5007 } else {
5008 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5009 }
5010
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005011 bool isReadOnly = false;
5012 // For historical/compatibility reasons, the read-only qualifier of the
5013 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5014 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00005015 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00005016 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005017 if (OutermostType && T.isConstQualified()) {
5018 isReadOnly = true;
5019 S += 'r';
5020 }
Mike Stump9fdbab32009-07-31 02:02:20 +00005021 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005022 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00005023 while (P->getAs<PointerType>())
5024 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005025 if (P.isConstQualified()) {
5026 isReadOnly = true;
5027 S += 'r';
5028 }
5029 }
5030 if (isReadOnly) {
5031 // Another legacy compatibility encoding. Some ObjC qualifier and type
5032 // combinations need to be rearranged.
5033 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00005034 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00005035 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005036 }
Mike Stump1eb44332009-09-09 15:08:12 +00005037
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005038 if (PointeeTy->isCharType()) {
5039 // char pointer types should be encoded as '*' unless it is a
5040 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00005041 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005042 S += '*';
5043 return;
5044 }
Ted Kremenek6217b802009-07-29 21:53:49 +00005045 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00005046 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5047 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5048 S += '#';
5049 return;
5050 }
5051 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5052 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5053 S += '@';
5054 return;
5055 }
5056 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005057 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005058 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005059 getLegacyIntegralTypeEncoding(PointeeTy);
5060
Mike Stump1eb44332009-09-09 15:08:12 +00005061 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005062 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005063 return;
5064 }
John McCall3624e9e2012-12-20 02:45:14 +00005065
5066 case Type::ConstantArray:
5067 case Type::IncompleteArray:
5068 case Type::VariableArray: {
5069 const ArrayType *AT = cast<ArrayType>(CT);
5070
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005071 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00005072 // Incomplete arrays are encoded as a pointer to the array element.
5073 S += '^';
5074
Mike Stump1eb44332009-09-09 15:08:12 +00005075 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005076 false, ExpandStructures, FD);
5077 } else {
5078 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00005079
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005080 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
5081 if (getTypeSize(CAT->getElementType()) == 0)
5082 S += '0';
5083 else
5084 S += llvm::utostr(CAT->getSize().getZExtValue());
5085 } else {
Anders Carlsson559a8332009-02-22 01:38:57 +00005086 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005087 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5088 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00005089 S += '0';
5090 }
Mike Stump1eb44332009-09-09 15:08:12 +00005091
5092 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005093 false, ExpandStructures, FD);
5094 S += ']';
5095 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005096 return;
5097 }
Mike Stump1eb44332009-09-09 15:08:12 +00005098
John McCall3624e9e2012-12-20 02:45:14 +00005099 case Type::FunctionNoProto:
5100 case Type::FunctionProto:
Anders Carlssonc0a87b72007-10-30 00:06:20 +00005101 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005102 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005103
John McCall3624e9e2012-12-20 02:45:14 +00005104 case Type::Record: {
5105 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005106 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005107 // Anonymous structures print as '?'
5108 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5109 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005110 if (ClassTemplateSpecializationDecl *Spec
5111 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5112 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
5113 std::string TemplateArgsStr
5114 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00005115 TemplateArgs.data(),
5116 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00005117 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005118
5119 S += TemplateArgsStr;
5120 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005121 } else {
5122 S += '?';
5123 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00005124 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005125 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005126 if (!RDecl->isUnion()) {
5127 getObjCEncodingForStructureImpl(RDecl, S, FD);
5128 } else {
5129 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5130 FieldEnd = RDecl->field_end();
5131 Field != FieldEnd; ++Field) {
5132 if (FD) {
5133 S += '"';
5134 S += Field->getNameAsString();
5135 S += '"';
5136 }
Mike Stump1eb44332009-09-09 15:08:12 +00005137
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005138 // Special case bit-fields.
5139 if (Field->isBitField()) {
5140 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie581deb32012-06-06 20:45:41 +00005141 *Field);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005142 } else {
5143 QualType qt = Field->getType();
5144 getLegacyIntegralTypeEncoding(qt);
5145 getObjCEncodingForTypeImpl(qt, S, false, true,
5146 FD, /*OutermostType*/false,
5147 /*EncodingProperty*/false,
5148 /*StructField*/true);
5149 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005150 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005151 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00005152 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005153 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005154 return;
5155 }
Mike Stump1eb44332009-09-09 15:08:12 +00005156
John McCall3624e9e2012-12-20 02:45:14 +00005157 case Type::BlockPointer: {
5158 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff21a98b12009-02-02 18:24:29 +00005159 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00005160 if (EncodeBlockParameters) {
John McCall3624e9e2012-12-20 02:45:14 +00005161 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilsondc8dab62011-11-30 01:57:58 +00005162
5163 S += '<';
5164 // Block return type
5165 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5166 ExpandPointedToStructures, ExpandStructures,
5167 FD,
5168 false /* OutermostType */,
5169 EncodingProperty,
5170 false /* StructField */,
5171 EncodeBlockParameters,
5172 EncodeClassNames);
5173 // Block self
5174 S += "@?";
5175 // Block parameters
5176 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5177 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5178 E = FPT->arg_type_end(); I && (I != E); ++I) {
5179 getObjCEncodingForTypeImpl(*I, S,
5180 ExpandPointedToStructures,
5181 ExpandStructures,
5182 FD,
5183 false /* OutermostType */,
5184 EncodingProperty,
5185 false /* StructField */,
5186 EncodeBlockParameters,
5187 EncodeClassNames);
5188 }
5189 }
5190 S += '>';
5191 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005192 return;
5193 }
Mike Stump1eb44332009-09-09 15:08:12 +00005194
John McCall3624e9e2012-12-20 02:45:14 +00005195 case Type::ObjCObject:
5196 case Type::ObjCInterface: {
5197 // Ignore protocol qualifiers when mangling at this level.
5198 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCallc12c5bb2010-05-15 11:32:37 +00005199
John McCall3624e9e2012-12-20 02:45:14 +00005200 // The assumption seems to be that this assert will succeed
5201 // because nested levels will have filtered out 'id' and 'Class'.
5202 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005203 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00005204 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005205 S += '{';
5206 const IdentifierInfo *II = OI->getIdentifier();
5207 S += II->getName();
5208 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00005209 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005210 DeepCollectObjCIvars(OI, true, Ivars);
5211 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00005212 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005213 if (Field->isBitField())
5214 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005215 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005216 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005217 }
5218 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005219 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005220 }
Mike Stump1eb44332009-09-09 15:08:12 +00005221
John McCall3624e9e2012-12-20 02:45:14 +00005222 case Type::ObjCObjectPointer: {
5223 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00005224 if (OPT->isObjCIdType()) {
5225 S += '@';
5226 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005227 }
Mike Stump1eb44332009-09-09 15:08:12 +00005228
Steve Naroff27d20a22009-10-28 22:03:49 +00005229 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5230 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5231 // Since this is a binary compatibility issue, need to consult with runtime
5232 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00005233 S += '#';
5234 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005235 }
Mike Stump1eb44332009-09-09 15:08:12 +00005236
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005237 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005238 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00005239 ExpandPointedToStructures,
5240 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00005241 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00005242 // Note that we do extended encoding of protocol qualifer list
5243 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00005244 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005245 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5246 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00005247 S += '<';
5248 S += (*I)->getNameAsString();
5249 S += '>';
5250 }
5251 S += '"';
5252 }
5253 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005254 }
Mike Stump1eb44332009-09-09 15:08:12 +00005255
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005256 QualType PointeeTy = OPT->getPointeeType();
5257 if (!EncodingProperty &&
5258 isa<TypedefType>(PointeeTy.getTypePtr())) {
5259 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00005260 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005261 // {...};
5262 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00005263 getObjCEncodingForTypeImpl(PointeeTy, S,
5264 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005265 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00005266 return;
5267 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005268
5269 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00005270 if (OPT->getInterfaceDecl() &&
5271 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005272 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00005273 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005274 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5275 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005276 S += '<';
5277 S += (*I)->getNameAsString();
5278 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00005279 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005280 S += '"';
5281 }
5282 return;
5283 }
Mike Stump1eb44332009-09-09 15:08:12 +00005284
John McCall532ec7b2010-05-17 23:56:34 +00005285 // gcc just blithely ignores member pointers.
John McCall3624e9e2012-12-20 02:45:14 +00005286 // FIXME: we shoul do better than that. 'M' is available.
5287 case Type::MemberPointer:
John McCall532ec7b2010-05-17 23:56:34 +00005288 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005289
John McCall3624e9e2012-12-20 02:45:14 +00005290 case Type::Vector:
5291 case Type::ExtVector:
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005292 // This matches gcc's encoding, even though technically it is
5293 // insufficient.
5294 // FIXME. We should do a better job than gcc.
5295 return;
John McCall3624e9e2012-12-20 02:45:14 +00005296
5297#define ABSTRACT_TYPE(KIND, BASE)
5298#define TYPE(KIND, BASE)
5299#define DEPENDENT_TYPE(KIND, BASE) \
5300 case Type::KIND:
5301#define NON_CANONICAL_TYPE(KIND, BASE) \
5302 case Type::KIND:
5303#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5304 case Type::KIND:
5305#include "clang/AST/TypeNodes.def"
5306 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005307 }
John McCall3624e9e2012-12-20 02:45:14 +00005308 llvm_unreachable("bad type kind!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005309}
5310
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005311void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5312 std::string &S,
5313 const FieldDecl *FD,
5314 bool includeVBases) const {
5315 assert(RDecl && "Expected non-null RecordDecl");
5316 assert(!RDecl->isUnion() && "Should not be called for unions");
5317 if (!RDecl->getDefinition())
5318 return;
5319
5320 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5321 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5322 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5323
5324 if (CXXRec) {
5325 for (CXXRecordDecl::base_class_iterator
5326 BI = CXXRec->bases_begin(),
5327 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5328 if (!BI->isVirtual()) {
5329 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005330 if (base->isEmpty())
5331 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005332 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005333 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5334 std::make_pair(offs, base));
5335 }
5336 }
5337 }
5338
5339 unsigned i = 0;
5340 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5341 FieldEnd = RDecl->field_end();
5342 Field != FieldEnd; ++Field, ++i) {
5343 uint64_t offs = layout.getFieldOffset(i);
5344 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie581deb32012-06-06 20:45:41 +00005345 std::make_pair(offs, *Field));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005346 }
5347
5348 if (CXXRec && includeVBases) {
5349 for (CXXRecordDecl::base_class_iterator
5350 BI = CXXRec->vbases_begin(),
5351 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5352 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005353 if (base->isEmpty())
5354 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005355 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00005356 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5357 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5358 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005359 }
5360 }
5361
5362 CharUnits size;
5363 if (CXXRec) {
5364 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5365 } else {
5366 size = layout.getSize();
5367 }
5368
5369 uint64_t CurOffs = 0;
5370 std::multimap<uint64_t, NamedDecl *>::iterator
5371 CurLayObj = FieldOrBaseOffsets.begin();
5372
Douglas Gregor58db7a52012-04-27 22:30:01 +00005373 if (CXXRec && CXXRec->isDynamicClass() &&
5374 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005375 if (FD) {
5376 S += "\"_vptr$";
5377 std::string recname = CXXRec->getNameAsString();
5378 if (recname.empty()) recname = "?";
5379 S += recname;
5380 S += '"';
5381 }
5382 S += "^^?";
5383 CurOffs += getTypeSize(VoidPtrTy);
5384 }
5385
5386 if (!RDecl->hasFlexibleArrayMember()) {
5387 // Mark the end of the structure.
5388 uint64_t offs = toBits(size);
5389 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5390 std::make_pair(offs, (NamedDecl*)0));
5391 }
5392
5393 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5394 assert(CurOffs <= CurLayObj->first);
5395
5396 if (CurOffs < CurLayObj->first) {
5397 uint64_t padding = CurLayObj->first - CurOffs;
5398 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5399 // packing/alignment of members is different that normal, in which case
5400 // the encoding will be out-of-sync with the real layout.
5401 // If the runtime switches to just consider the size of types without
5402 // taking into account alignment, we could make padding explicit in the
5403 // encoding (e.g. using arrays of chars). The encoding strings would be
5404 // longer then though.
5405 CurOffs += padding;
5406 }
5407
5408 NamedDecl *dcl = CurLayObj->second;
5409 if (dcl == 0)
5410 break; // reached end of structure.
5411
5412 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5413 // We expand the bases without their virtual bases since those are going
5414 // in the initial structure. Note that this differs from gcc which
5415 // expands virtual bases each time one is encountered in the hierarchy,
5416 // making the encoding type bigger than it really is.
5417 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005418 assert(!base->isEmpty());
5419 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005420 } else {
5421 FieldDecl *field = cast<FieldDecl>(dcl);
5422 if (FD) {
5423 S += '"';
5424 S += field->getNameAsString();
5425 S += '"';
5426 }
5427
5428 if (field->isBitField()) {
5429 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005430 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005431 } else {
5432 QualType qt = field->getType();
5433 getLegacyIntegralTypeEncoding(qt);
5434 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5435 /*OutermostType*/false,
5436 /*EncodingProperty*/false,
5437 /*StructField*/true);
5438 CurOffs += getTypeSize(field->getType());
5439 }
5440 }
5441 }
5442}
5443
Mike Stump1eb44332009-09-09 15:08:12 +00005444void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00005445 std::string& S) const {
5446 if (QT & Decl::OBJC_TQ_In)
5447 S += 'n';
5448 if (QT & Decl::OBJC_TQ_Inout)
5449 S += 'N';
5450 if (QT & Decl::OBJC_TQ_Out)
5451 S += 'o';
5452 if (QT & Decl::OBJC_TQ_Bycopy)
5453 S += 'O';
5454 if (QT & Decl::OBJC_TQ_Byref)
5455 S += 'R';
5456 if (QT & Decl::OBJC_TQ_Oneway)
5457 S += 'V';
5458}
5459
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00005460TypedefDecl *ASTContext::getObjCIdDecl() const {
5461 if (!ObjCIdDecl) {
5462 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5463 T = getObjCObjectPointerType(T);
5464 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5465 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5466 getTranslationUnitDecl(),
5467 SourceLocation(), SourceLocation(),
5468 &Idents.get("id"), IdInfo);
5469 }
5470
5471 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00005472}
5473
Douglas Gregor7a27ea52011-08-12 06:17:30 +00005474TypedefDecl *ASTContext::getObjCSelDecl() const {
5475 if (!ObjCSelDecl) {
5476 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5477 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5478 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5479 getTranslationUnitDecl(),
5480 SourceLocation(), SourceLocation(),
5481 &Idents.get("SEL"), SelInfo);
5482 }
5483 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00005484}
5485
Douglas Gregor79d67262011-08-12 05:59:41 +00005486TypedefDecl *ASTContext::getObjCClassDecl() const {
5487 if (!ObjCClassDecl) {
5488 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5489 T = getObjCObjectPointerType(T);
5490 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5491 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5492 getTranslationUnitDecl(),
5493 SourceLocation(), SourceLocation(),
5494 &Idents.get("Class"), ClassInfo);
5495 }
5496
5497 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00005498}
5499
Douglas Gregora6ea10e2012-01-17 18:09:05 +00005500ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5501 if (!ObjCProtocolClassDecl) {
5502 ObjCProtocolClassDecl
5503 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5504 SourceLocation(),
5505 &Idents.get("Protocol"),
5506 /*PrevDecl=*/0,
5507 SourceLocation(), true);
5508 }
5509
5510 return ObjCProtocolClassDecl;
5511}
5512
Meador Ingec5613b22012-06-16 03:34:49 +00005513//===----------------------------------------------------------------------===//
5514// __builtin_va_list Construction Functions
5515//===----------------------------------------------------------------------===//
5516
5517static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5518 // typedef char* __builtin_va_list;
5519 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5520 TypeSourceInfo *TInfo
5521 = Context->getTrivialTypeSourceInfo(CharPtrType);
5522
5523 TypedefDecl *VaListTypeDecl
5524 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5525 Context->getTranslationUnitDecl(),
5526 SourceLocation(), SourceLocation(),
5527 &Context->Idents.get("__builtin_va_list"),
5528 TInfo);
5529 return VaListTypeDecl;
5530}
5531
5532static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5533 // typedef void* __builtin_va_list;
5534 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5535 TypeSourceInfo *TInfo
5536 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5537
5538 TypedefDecl *VaListTypeDecl
5539 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5540 Context->getTranslationUnitDecl(),
5541 SourceLocation(), SourceLocation(),
5542 &Context->Idents.get("__builtin_va_list"),
5543 TInfo);
5544 return VaListTypeDecl;
5545}
5546
5547static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5548 // typedef struct __va_list_tag {
5549 RecordDecl *VaListTagDecl;
5550
5551 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5552 Context->getTranslationUnitDecl(),
5553 &Context->Idents.get("__va_list_tag"));
5554 VaListTagDecl->startDefinition();
5555
5556 const size_t NumFields = 5;
5557 QualType FieldTypes[NumFields];
5558 const char *FieldNames[NumFields];
5559
5560 // unsigned char gpr;
5561 FieldTypes[0] = Context->UnsignedCharTy;
5562 FieldNames[0] = "gpr";
5563
5564 // unsigned char fpr;
5565 FieldTypes[1] = Context->UnsignedCharTy;
5566 FieldNames[1] = "fpr";
5567
5568 // unsigned short reserved;
5569 FieldTypes[2] = Context->UnsignedShortTy;
5570 FieldNames[2] = "reserved";
5571
5572 // void* overflow_arg_area;
5573 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5574 FieldNames[3] = "overflow_arg_area";
5575
5576 // void* reg_save_area;
5577 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5578 FieldNames[4] = "reg_save_area";
5579
5580 // Create fields
5581 for (unsigned i = 0; i < NumFields; ++i) {
5582 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5583 SourceLocation(),
5584 SourceLocation(),
5585 &Context->Idents.get(FieldNames[i]),
5586 FieldTypes[i], /*TInfo=*/0,
5587 /*BitWidth=*/0,
5588 /*Mutable=*/false,
5589 ICIS_NoInit);
5590 Field->setAccess(AS_public);
5591 VaListTagDecl->addDecl(Field);
5592 }
5593 VaListTagDecl->completeDefinition();
5594 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005595 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005596
5597 // } __va_list_tag;
5598 TypedefDecl *VaListTagTypedefDecl
5599 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5600 Context->getTranslationUnitDecl(),
5601 SourceLocation(), SourceLocation(),
5602 &Context->Idents.get("__va_list_tag"),
5603 Context->getTrivialTypeSourceInfo(VaListTagType));
5604 QualType VaListTagTypedefType =
5605 Context->getTypedefType(VaListTagTypedefDecl);
5606
5607 // typedef __va_list_tag __builtin_va_list[1];
5608 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5609 QualType VaListTagArrayType
5610 = Context->getConstantArrayType(VaListTagTypedefType,
5611 Size, ArrayType::Normal, 0);
5612 TypeSourceInfo *TInfo
5613 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5614 TypedefDecl *VaListTypedefDecl
5615 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5616 Context->getTranslationUnitDecl(),
5617 SourceLocation(), SourceLocation(),
5618 &Context->Idents.get("__builtin_va_list"),
5619 TInfo);
5620
5621 return VaListTypedefDecl;
5622}
5623
5624static TypedefDecl *
5625CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5626 // typedef struct __va_list_tag {
5627 RecordDecl *VaListTagDecl;
5628 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5629 Context->getTranslationUnitDecl(),
5630 &Context->Idents.get("__va_list_tag"));
5631 VaListTagDecl->startDefinition();
5632
5633 const size_t NumFields = 4;
5634 QualType FieldTypes[NumFields];
5635 const char *FieldNames[NumFields];
5636
5637 // unsigned gp_offset;
5638 FieldTypes[0] = Context->UnsignedIntTy;
5639 FieldNames[0] = "gp_offset";
5640
5641 // unsigned fp_offset;
5642 FieldTypes[1] = Context->UnsignedIntTy;
5643 FieldNames[1] = "fp_offset";
5644
5645 // void* overflow_arg_area;
5646 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5647 FieldNames[2] = "overflow_arg_area";
5648
5649 // void* reg_save_area;
5650 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5651 FieldNames[3] = "reg_save_area";
5652
5653 // Create fields
5654 for (unsigned i = 0; i < NumFields; ++i) {
5655 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5656 VaListTagDecl,
5657 SourceLocation(),
5658 SourceLocation(),
5659 &Context->Idents.get(FieldNames[i]),
5660 FieldTypes[i], /*TInfo=*/0,
5661 /*BitWidth=*/0,
5662 /*Mutable=*/false,
5663 ICIS_NoInit);
5664 Field->setAccess(AS_public);
5665 VaListTagDecl->addDecl(Field);
5666 }
5667 VaListTagDecl->completeDefinition();
5668 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005669 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005670
5671 // } __va_list_tag;
5672 TypedefDecl *VaListTagTypedefDecl
5673 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5674 Context->getTranslationUnitDecl(),
5675 SourceLocation(), SourceLocation(),
5676 &Context->Idents.get("__va_list_tag"),
5677 Context->getTrivialTypeSourceInfo(VaListTagType));
5678 QualType VaListTagTypedefType =
5679 Context->getTypedefType(VaListTagTypedefDecl);
5680
5681 // typedef __va_list_tag __builtin_va_list[1];
5682 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5683 QualType VaListTagArrayType
5684 = Context->getConstantArrayType(VaListTagTypedefType,
5685 Size, ArrayType::Normal,0);
5686 TypeSourceInfo *TInfo
5687 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5688 TypedefDecl *VaListTypedefDecl
5689 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5690 Context->getTranslationUnitDecl(),
5691 SourceLocation(), SourceLocation(),
5692 &Context->Idents.get("__builtin_va_list"),
5693 TInfo);
5694
5695 return VaListTypedefDecl;
5696}
5697
5698static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5699 // typedef int __builtin_va_list[4];
5700 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5701 QualType IntArrayType
5702 = Context->getConstantArrayType(Context->IntTy,
5703 Size, ArrayType::Normal, 0);
5704 TypedefDecl *VaListTypedefDecl
5705 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5706 Context->getTranslationUnitDecl(),
5707 SourceLocation(), SourceLocation(),
5708 &Context->Idents.get("__builtin_va_list"),
5709 Context->getTrivialTypeSourceInfo(IntArrayType));
5710
5711 return VaListTypedefDecl;
5712}
5713
Logan Chieneae5a8202012-10-10 06:56:20 +00005714static TypedefDecl *
5715CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5716 RecordDecl *VaListDecl;
5717 if (Context->getLangOpts().CPlusPlus) {
5718 // namespace std { struct __va_list {
5719 NamespaceDecl *NS;
5720 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5721 Context->getTranslationUnitDecl(),
5722 /*Inline*/false, SourceLocation(),
5723 SourceLocation(), &Context->Idents.get("std"),
5724 /*PrevDecl*/0);
5725
5726 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5727 Context->getTranslationUnitDecl(),
5728 SourceLocation(), SourceLocation(),
5729 &Context->Idents.get("__va_list"));
5730
5731 VaListDecl->setDeclContext(NS);
5732
5733 } else {
5734 // struct __va_list {
5735 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
5736 Context->getTranslationUnitDecl(),
5737 &Context->Idents.get("__va_list"));
5738 }
5739
5740 VaListDecl->startDefinition();
5741
5742 // void * __ap;
5743 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5744 VaListDecl,
5745 SourceLocation(),
5746 SourceLocation(),
5747 &Context->Idents.get("__ap"),
5748 Context->getPointerType(Context->VoidTy),
5749 /*TInfo=*/0,
5750 /*BitWidth=*/0,
5751 /*Mutable=*/false,
5752 ICIS_NoInit);
5753 Field->setAccess(AS_public);
5754 VaListDecl->addDecl(Field);
5755
5756 // };
5757 VaListDecl->completeDefinition();
5758
5759 // typedef struct __va_list __builtin_va_list;
5760 TypeSourceInfo *TInfo
5761 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
5762
5763 TypedefDecl *VaListTypeDecl
5764 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5765 Context->getTranslationUnitDecl(),
5766 SourceLocation(), SourceLocation(),
5767 &Context->Idents.get("__builtin_va_list"),
5768 TInfo);
5769
5770 return VaListTypeDecl;
5771}
5772
Meador Ingec5613b22012-06-16 03:34:49 +00005773static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5774 TargetInfo::BuiltinVaListKind Kind) {
5775 switch (Kind) {
5776 case TargetInfo::CharPtrBuiltinVaList:
5777 return CreateCharPtrBuiltinVaListDecl(Context);
5778 case TargetInfo::VoidPtrBuiltinVaList:
5779 return CreateVoidPtrBuiltinVaListDecl(Context);
5780 case TargetInfo::PowerABIBuiltinVaList:
5781 return CreatePowerABIBuiltinVaListDecl(Context);
5782 case TargetInfo::X86_64ABIBuiltinVaList:
5783 return CreateX86_64ABIBuiltinVaListDecl(Context);
5784 case TargetInfo::PNaClABIBuiltinVaList:
5785 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chieneae5a8202012-10-10 06:56:20 +00005786 case TargetInfo::AAPCSABIBuiltinVaList:
5787 return CreateAAPCSABIBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00005788 }
5789
5790 llvm_unreachable("Unhandled __builtin_va_list type kind");
5791}
5792
5793TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5794 if (!BuiltinVaListDecl)
5795 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5796
5797 return BuiltinVaListDecl;
5798}
5799
Meador Ingefb40e3f2012-07-01 15:57:25 +00005800QualType ASTContext::getVaListTagType() const {
5801 // Force the creation of VaListTagTy by building the __builtin_va_list
5802 // declaration.
5803 if (VaListTagTy.isNull())
5804 (void) getBuiltinVaListDecl();
5805
5806 return VaListTagTy;
5807}
5808
Ted Kremeneka526c5c2008-01-07 19:49:32 +00005809void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00005810 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00005811 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00005812
Ted Kremeneka526c5c2008-01-07 19:49:32 +00005813 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00005814}
5815
John McCall0bd6feb2009-12-02 08:04:21 +00005816/// \brief Retrieve the template name that corresponds to a non-empty
5817/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00005818TemplateName
5819ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5820 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00005821 unsigned size = End - Begin;
5822 assert(size > 1 && "set is not overloaded!");
5823
5824 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5825 size * sizeof(FunctionTemplateDecl*));
5826 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5827
5828 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00005829 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00005830 NamedDecl *D = *I;
5831 assert(isa<FunctionTemplateDecl>(D) ||
5832 (isa<UsingShadowDecl>(D) &&
5833 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5834 *Storage++ = D;
5835 }
5836
5837 return TemplateName(OT);
5838}
5839
Douglas Gregor7532dc62009-03-30 22:58:21 +00005840/// \brief Retrieve the template name that represents a qualified
5841/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00005842TemplateName
5843ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5844 bool TemplateKeyword,
5845 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00005846 assert(NNS && "Missing nested-name-specifier in qualified template name");
5847
Douglas Gregor789b1f62010-02-04 18:10:26 +00005848 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00005849 llvm::FoldingSetNodeID ID;
5850 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5851
5852 void *InsertPos = 0;
5853 QualifiedTemplateName *QTN =
5854 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5855 if (!QTN) {
Richard Smith2f47cab2012-08-16 01:19:31 +00005856 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
5857 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregor7532dc62009-03-30 22:58:21 +00005858 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5859 }
5860
5861 return TemplateName(QTN);
5862}
5863
5864/// \brief Retrieve the template name that represents a dependent
5865/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00005866TemplateName
5867ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5868 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00005869 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00005870 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00005871
5872 llvm::FoldingSetNodeID ID;
5873 DependentTemplateName::Profile(ID, NNS, Name);
5874
5875 void *InsertPos = 0;
5876 DependentTemplateName *QTN =
5877 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5878
5879 if (QTN)
5880 return TemplateName(QTN);
5881
5882 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5883 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00005884 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5885 DependentTemplateName(NNS, Name);
Douglas Gregor7532dc62009-03-30 22:58:21 +00005886 } else {
5887 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smith2f47cab2012-08-16 01:19:31 +00005888 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5889 DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005890 DependentTemplateName *CheckQTN =
5891 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5892 assert(!CheckQTN && "Dependent type name canonicalization broken");
5893 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00005894 }
5895
5896 DependentTemplateNames.InsertNode(QTN, InsertPos);
5897 return TemplateName(QTN);
5898}
5899
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005900/// \brief Retrieve the template name that represents a dependent
5901/// template name such as \c MetaFun::template operator+.
5902TemplateName
5903ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00005904 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005905 assert((!NNS || NNS->isDependent()) &&
5906 "Nested name specifier must be dependent");
5907
5908 llvm::FoldingSetNodeID ID;
5909 DependentTemplateName::Profile(ID, NNS, Operator);
5910
5911 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00005912 DependentTemplateName *QTN
5913 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005914
5915 if (QTN)
5916 return TemplateName(QTN);
5917
5918 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5919 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00005920 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5921 DependentTemplateName(NNS, Operator);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005922 } else {
5923 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smith2f47cab2012-08-16 01:19:31 +00005924 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5925 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005926
5927 DependentTemplateName *CheckQTN
5928 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5929 assert(!CheckQTN && "Dependent template name canonicalization broken");
5930 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005931 }
5932
5933 DependentTemplateNames.InsertNode(QTN, InsertPos);
5934 return TemplateName(QTN);
5935}
5936
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005937TemplateName
John McCall14606042011-06-30 08:33:18 +00005938ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5939 TemplateName replacement) const {
5940 llvm::FoldingSetNodeID ID;
5941 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5942
5943 void *insertPos = 0;
5944 SubstTemplateTemplateParmStorage *subst
5945 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5946
5947 if (!subst) {
5948 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5949 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5950 }
5951
5952 return TemplateName(subst);
5953}
5954
5955TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005956ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5957 const TemplateArgument &ArgPack) const {
5958 ASTContext &Self = const_cast<ASTContext &>(*this);
5959 llvm::FoldingSetNodeID ID;
5960 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5961
5962 void *InsertPos = 0;
5963 SubstTemplateTemplateParmPackStorage *Subst
5964 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5965
5966 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00005967 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005968 ArgPack.pack_size(),
5969 ArgPack.pack_begin());
5970 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5971 }
5972
5973 return TemplateName(Subst);
5974}
5975
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005976/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00005977/// TargetInfo, produce the corresponding type. The unsigned @p Type
5978/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00005979CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005980 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00005981 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005982 case TargetInfo::SignedShort: return ShortTy;
5983 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5984 case TargetInfo::SignedInt: return IntTy;
5985 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5986 case TargetInfo::SignedLong: return LongTy;
5987 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5988 case TargetInfo::SignedLongLong: return LongLongTy;
5989 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5990 }
5991
David Blaikieb219cfc2011-09-23 05:06:16 +00005992 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005993}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00005994
5995//===----------------------------------------------------------------------===//
5996// Type Predicates.
5997//===----------------------------------------------------------------------===//
5998
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005999/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6000/// garbage collection attribute.
6001///
John McCallae278a32011-01-12 00:34:59 +00006002Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006003 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00006004 return Qualifiers::GCNone;
6005
David Blaikie4e4d0842012-03-11 07:00:24 +00006006 assert(getLangOpts().ObjC1);
John McCallae278a32011-01-12 00:34:59 +00006007 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6008
6009 // Default behaviour under objective-C's gc is for ObjC pointers
6010 // (or pointers to them) be treated as though they were declared
6011 // as __strong.
6012 if (GCAttrs == Qualifiers::GCNone) {
6013 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6014 return Qualifiers::Strong;
6015 else if (Ty->isPointerType())
6016 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6017 } else {
6018 // It's not valid to set GC attributes on anything that isn't a
6019 // pointer.
6020#ifndef NDEBUG
6021 QualType CT = Ty->getCanonicalTypeInternal();
6022 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6023 CT = AT->getElementType();
6024 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6025#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006026 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00006027 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006028}
6029
Chris Lattner6ac46a42008-04-07 06:51:04 +00006030//===----------------------------------------------------------------------===//
6031// Type Compatibility Testing
6032//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00006033
Mike Stump1eb44332009-09-09 15:08:12 +00006034/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006035/// compatible.
6036static bool areCompatVectorTypes(const VectorType *LHS,
6037 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00006038 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00006039 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00006040 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00006041}
6042
Douglas Gregor255210e2010-08-06 10:14:59 +00006043bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6044 QualType SecondVec) {
6045 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6046 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6047
6048 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6049 return true;
6050
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006051 // Treat Neon vector types and most AltiVec vector types as if they are the
6052 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00006053 const VectorType *First = FirstVec->getAs<VectorType>();
6054 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006055 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00006056 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006057 First->getVectorKind() != VectorType::AltiVecPixel &&
6058 First->getVectorKind() != VectorType::AltiVecBool &&
6059 Second->getVectorKind() != VectorType::AltiVecPixel &&
6060 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00006061 return true;
6062
6063 return false;
6064}
6065
Steve Naroff4084c302009-07-23 01:01:38 +00006066//===----------------------------------------------------------------------===//
6067// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6068//===----------------------------------------------------------------------===//
6069
6070/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6071/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00006072bool
6073ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6074 ObjCProtocolDecl *rProto) const {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00006075 if (declaresSameEntity(lProto, rProto))
Steve Naroff4084c302009-07-23 01:01:38 +00006076 return true;
6077 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6078 E = rProto->protocol_end(); PI != E; ++PI)
6079 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6080 return true;
6081 return false;
6082}
6083
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00006084/// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
Steve Naroff4084c302009-07-23 01:01:38 +00006085/// return true if lhs's protocols conform to rhs's protocol; false
6086/// otherwise.
6087bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
6088 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
6089 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
6090 return false;
6091}
6092
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00006093/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6094/// Class<pr1, ...>.
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006095bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6096 QualType rhs) {
6097 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6098 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6099 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6100
6101 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6102 E = lhsQID->qual_end(); I != E; ++I) {
6103 bool match = false;
6104 ObjCProtocolDecl *lhsProto = *I;
6105 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6106 E = rhsOPT->qual_end(); J != E; ++J) {
6107 ObjCProtocolDecl *rhsProto = *J;
6108 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6109 match = true;
6110 break;
6111 }
6112 }
6113 if (!match)
6114 return false;
6115 }
6116 return true;
6117}
6118
Steve Naroff4084c302009-07-23 01:01:38 +00006119/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6120/// ObjCQualifiedIDType.
6121bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6122 bool compare) {
6123 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00006124 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006125 lhs->isObjCIdType() || lhs->isObjCClassType())
6126 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006127 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006128 rhs->isObjCIdType() || rhs->isObjCClassType())
6129 return true;
6130
6131 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00006132 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006133
Steve Naroff4084c302009-07-23 01:01:38 +00006134 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006135
Steve Naroff4084c302009-07-23 01:01:38 +00006136 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006137 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00006138 // make sure we check the class hierarchy.
6139 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6140 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6141 E = lhsQID->qual_end(); I != E; ++I) {
6142 // when comparing an id<P> on lhs with a static type on rhs,
6143 // see if static class implements all of id's protocols, directly or
6144 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006145 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00006146 return false;
6147 }
6148 }
6149 // If there are no qualifiers and no interface, we have an 'id'.
6150 return true;
6151 }
Mike Stump1eb44332009-09-09 15:08:12 +00006152 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006153 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6154 E = lhsQID->qual_end(); I != E; ++I) {
6155 ObjCProtocolDecl *lhsProto = *I;
6156 bool match = false;
6157
6158 // when comparing an id<P> on lhs with a static type on rhs,
6159 // see if static class implements all of id's protocols, directly or
6160 // through its super class and categories.
6161 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6162 E = rhsOPT->qual_end(); J != E; ++J) {
6163 ObjCProtocolDecl *rhsProto = *J;
6164 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6165 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6166 match = true;
6167 break;
6168 }
6169 }
Mike Stump1eb44332009-09-09 15:08:12 +00006170 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00006171 // make sure we check the class hierarchy.
6172 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6173 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6174 E = lhsQID->qual_end(); I != E; ++I) {
6175 // when comparing an id<P> on lhs with a static type on rhs,
6176 // see if static class implements all of id's protocols, directly or
6177 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006178 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00006179 match = true;
6180 break;
6181 }
6182 }
6183 }
6184 if (!match)
6185 return false;
6186 }
Mike Stump1eb44332009-09-09 15:08:12 +00006187
Steve Naroff4084c302009-07-23 01:01:38 +00006188 return true;
6189 }
Mike Stump1eb44332009-09-09 15:08:12 +00006190
Steve Naroff4084c302009-07-23 01:01:38 +00006191 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6192 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6193
Mike Stump1eb44332009-09-09 15:08:12 +00006194 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00006195 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006196 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006197 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6198 E = lhsOPT->qual_end(); I != E; ++I) {
6199 ObjCProtocolDecl *lhsProto = *I;
6200 bool match = false;
6201
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006202 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00006203 // see if static class implements all of id's protocols, directly or
6204 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006205 // First, lhs protocols in the qualifier list must be found, direct
6206 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00006207 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6208 E = rhsQID->qual_end(); J != E; ++J) {
6209 ObjCProtocolDecl *rhsProto = *J;
6210 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6211 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6212 match = true;
6213 break;
6214 }
6215 }
6216 if (!match)
6217 return false;
6218 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006219
6220 // Static class's protocols, or its super class or category protocols
6221 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6222 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6223 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6224 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6225 // This is rather dubious but matches gcc's behavior. If lhs has
6226 // no type qualifier and its class has no static protocol(s)
6227 // assume that it is mismatch.
6228 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6229 return false;
6230 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6231 LHSInheritedProtocols.begin(),
6232 E = LHSInheritedProtocols.end(); I != E; ++I) {
6233 bool match = false;
6234 ObjCProtocolDecl *lhsProto = (*I);
6235 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6236 E = rhsQID->qual_end(); J != E; ++J) {
6237 ObjCProtocolDecl *rhsProto = *J;
6238 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6239 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6240 match = true;
6241 break;
6242 }
6243 }
6244 if (!match)
6245 return false;
6246 }
6247 }
Steve Naroff4084c302009-07-23 01:01:38 +00006248 return true;
6249 }
6250 return false;
6251}
6252
Eli Friedman3d815e72008-08-22 00:56:42 +00006253/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006254/// compatible for assignment from RHS to LHS. This handles validation of any
6255/// protocol qualifiers on the LHS or RHS.
6256///
Steve Naroff14108da2009-07-10 23:34:53 +00006257bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6258 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00006259 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6260 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6261
Steve Naroffde2e22d2009-07-15 18:40:39 +00006262 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00006263 if (LHS->isObjCUnqualifiedIdOrClass() ||
6264 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00006265 return true;
6266
John McCallc12c5bb2010-05-15 11:32:37 +00006267 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00006268 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6269 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00006270 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006271
6272 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6273 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6274 QualType(RHSOPT,0));
6275
John McCallc12c5bb2010-05-15 11:32:37 +00006276 // If we have 2 user-defined types, fall into that path.
6277 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00006278 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006279
Steve Naroff4084c302009-07-23 01:01:38 +00006280 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006281}
6282
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006283/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00006284/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006285/// arguments in block literals. When passed as arguments, passing 'A*' where
6286/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6287/// not OK. For the return type, the opposite is not OK.
6288bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6289 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006290 const ObjCObjectPointerType *RHSOPT,
6291 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006292 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006293 return true;
6294
6295 if (LHSOPT->isObjCBuiltinType()) {
6296 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6297 }
6298
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006299 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006300 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6301 QualType(RHSOPT,0),
6302 false);
6303
6304 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6305 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6306 if (LHS && RHS) { // We have 2 user-defined types.
6307 if (LHS != RHS) {
6308 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006309 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006310 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006311 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006312 }
6313 else
6314 return true;
6315 }
6316 return false;
6317}
6318
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006319/// getIntersectionOfProtocols - This routine finds the intersection of set
6320/// of protocols inherited from two distinct objective-c pointer objects.
6321/// It is used to build composite qualifier list of the composite type of
6322/// the conditional expression involving two objective-c pointer objects.
6323static
6324void getIntersectionOfProtocols(ASTContext &Context,
6325 const ObjCObjectPointerType *LHSOPT,
6326 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006327 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006328
John McCallc12c5bb2010-05-15 11:32:37 +00006329 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6330 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6331 assert(LHS->getInterface() && "LHS must have an interface base");
6332 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006333
6334 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6335 unsigned LHSNumProtocols = LHS->getNumProtocols();
6336 if (LHSNumProtocols > 0)
6337 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6338 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006339 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006340 Context.CollectInheritedProtocols(LHS->getInterface(),
6341 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006342 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6343 LHSInheritedProtocols.end());
6344 }
6345
6346 unsigned RHSNumProtocols = RHS->getNumProtocols();
6347 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00006348 ObjCProtocolDecl **RHSProtocols =
6349 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006350 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6351 if (InheritedProtocolSet.count(RHSProtocols[i]))
6352 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00006353 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006354 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006355 Context.CollectInheritedProtocols(RHS->getInterface(),
6356 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006357 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6358 RHSInheritedProtocols.begin(),
6359 E = RHSInheritedProtocols.end(); I != E; ++I)
6360 if (InheritedProtocolSet.count((*I)))
6361 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006362 }
6363}
6364
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006365/// areCommonBaseCompatible - Returns common base class of the two classes if
6366/// one found. Note that this is O'2 algorithm. But it will be called as the
6367/// last type comparison in a ?-exp of ObjC pointer types before a
6368/// warning is issued. So, its invokation is extremely rare.
6369QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00006370 const ObjCObjectPointerType *Lptr,
6371 const ObjCObjectPointerType *Rptr) {
6372 const ObjCObjectType *LHS = Lptr->getObjectType();
6373 const ObjCObjectType *RHS = Rptr->getObjectType();
6374 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6375 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor60ef3082011-12-15 00:29:59 +00006376 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006377 return QualType();
6378
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006379 do {
John McCallc12c5bb2010-05-15 11:32:37 +00006380 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006381 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006382 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006383 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6384
6385 QualType Result = QualType(LHS, 0);
6386 if (!Protocols.empty())
6387 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6388 Result = getObjCObjectPointerType(Result);
6389 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006390 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006391 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006392
6393 return QualType();
6394}
6395
John McCallc12c5bb2010-05-15 11:32:37 +00006396bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6397 const ObjCObjectType *RHS) {
6398 assert(LHS->getInterface() && "LHS is not an interface type");
6399 assert(RHS->getInterface() && "RHS is not an interface type");
6400
Chris Lattner6ac46a42008-04-07 06:51:04 +00006401 // Verify that the base decls are compatible: the RHS must be a subclass of
6402 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00006403 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00006404 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006405
Chris Lattner6ac46a42008-04-07 06:51:04 +00006406 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6407 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00006408 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00006409 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006410
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006411 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6412 // more detailed analysis is required.
6413 if (RHS->getNumProtocols() == 0) {
6414 // OK, if LHS is a superclass of RHS *and*
6415 // this superclass is assignment compatible with LHS.
6416 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006417 bool IsSuperClass =
6418 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6419 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006420 // OK if conversion of LHS to SuperClass results in narrowing of types
6421 // ; i.e., SuperClass may implement at least one of the protocols
6422 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6423 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6424 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006425 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006426 // If super class has no protocols, it is not a match.
6427 if (SuperClassInheritedProtocols.empty())
6428 return false;
6429
6430 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6431 LHSPE = LHS->qual_end();
6432 LHSPI != LHSPE; LHSPI++) {
6433 bool SuperImplementsProtocol = false;
6434 ObjCProtocolDecl *LHSProto = (*LHSPI);
6435
6436 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6437 SuperClassInheritedProtocols.begin(),
6438 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6439 ObjCProtocolDecl *SuperClassProto = (*I);
6440 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6441 SuperImplementsProtocol = true;
6442 break;
6443 }
6444 }
6445 if (!SuperImplementsProtocol)
6446 return false;
6447 }
6448 return true;
6449 }
6450 return false;
6451 }
Mike Stump1eb44332009-09-09 15:08:12 +00006452
John McCallc12c5bb2010-05-15 11:32:37 +00006453 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6454 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006455 LHSPI != LHSPE; LHSPI++) {
6456 bool RHSImplementsProtocol = false;
6457
6458 // If the RHS doesn't implement the protocol on the left, the types
6459 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00006460 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6461 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00006462 RHSPI != RHSPE; RHSPI++) {
6463 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006464 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00006465 break;
6466 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006467 }
6468 // FIXME: For better diagnostics, consider passing back the protocol name.
6469 if (!RHSImplementsProtocol)
6470 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006471 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006472 // The RHS implements all protocols listed on the LHS.
6473 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006474}
6475
Steve Naroff389bf462009-02-12 17:52:19 +00006476bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6477 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00006478 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6479 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006480
Steve Naroff14108da2009-07-10 23:34:53 +00006481 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00006482 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006483
6484 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6485 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00006486}
6487
Douglas Gregor569c3162010-08-07 11:51:51 +00006488bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6489 return canAssignObjCInterfaces(
6490 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6491 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6492}
6493
Mike Stump1eb44332009-09-09 15:08:12 +00006494/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00006495/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00006496/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00006497/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00006498bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6499 bool CompareUnqualified) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006500 if (getLangOpts().CPlusPlus)
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006501 return hasSameType(LHS, RHS);
6502
Douglas Gregor447234d2010-07-29 15:18:02 +00006503 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00006504}
6505
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006506bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00006507 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006508}
6509
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006510bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6511 return !mergeTypes(LHS, RHS, true).isNull();
6512}
6513
Peter Collingbourne48466752010-10-24 18:30:18 +00006514/// mergeTransparentUnionType - if T is a transparent union type and a member
6515/// of T is compatible with SubType, return the merged type, else return
6516/// QualType()
6517QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6518 bool OfBlockPointer,
6519 bool Unqualified) {
6520 if (const RecordType *UT = T->getAsUnionType()) {
6521 RecordDecl *UD = UT->getDecl();
6522 if (UD->hasAttr<TransparentUnionAttr>()) {
6523 for (RecordDecl::field_iterator it = UD->field_begin(),
6524 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00006525 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006526 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6527 if (!MT.isNull())
6528 return MT;
6529 }
6530 }
6531 }
6532
6533 return QualType();
6534}
6535
6536/// mergeFunctionArgumentTypes - merge two types which appear as function
6537/// argument types
6538QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6539 bool OfBlockPointer,
6540 bool Unqualified) {
6541 // GNU extension: two types are compatible if they appear as a function
6542 // argument, one of the types is a transparent union type and the other
6543 // type is compatible with a union member
6544 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6545 Unqualified);
6546 if (!lmerge.isNull())
6547 return lmerge;
6548
6549 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6550 Unqualified);
6551 if (!rmerge.isNull())
6552 return rmerge;
6553
6554 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6555}
6556
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006557QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00006558 bool OfBlockPointer,
6559 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00006560 const FunctionType *lbase = lhs->getAs<FunctionType>();
6561 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00006562 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6563 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00006564 bool allLTypes = true;
6565 bool allRTypes = true;
6566
6567 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006568 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006569 if (OfBlockPointer) {
6570 QualType RHS = rbase->getResultType();
6571 QualType LHS = lbase->getResultType();
6572 bool UnqualifiedResult = Unqualified;
6573 if (!UnqualifiedResult)
6574 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006575 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006576 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006577 else
John McCall8cc246c2010-12-15 01:06:38 +00006578 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6579 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006580 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006581
6582 if (Unqualified)
6583 retType = retType.getUnqualifiedType();
6584
6585 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6586 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6587 if (Unqualified) {
6588 LRetType = LRetType.getUnqualifiedType();
6589 RRetType = RRetType.getUnqualifiedType();
6590 }
6591
6592 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006593 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00006594 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006595 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00006596
Daniel Dunbar6a15c852010-04-28 16:20:58 +00006597 // FIXME: double check this
6598 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6599 // rbase->getRegParmAttr() != 0 &&
6600 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00006601 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6602 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00006603
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006604 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00006605 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006606 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006607
John McCall8cc246c2010-12-15 01:06:38 +00006608 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00006609 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6610 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00006611 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6612 return QualType();
6613
John McCallf85e1932011-06-15 23:02:42 +00006614 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6615 return QualType();
6616
John McCall8cc246c2010-12-15 01:06:38 +00006617 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6618 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00006619
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00006620 if (lbaseInfo.getNoReturn() != NoReturn)
6621 allLTypes = false;
6622 if (rbaseInfo.getNoReturn() != NoReturn)
6623 allRTypes = false;
6624
John McCallf85e1932011-06-15 23:02:42 +00006625 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00006626
Eli Friedman3d815e72008-08-22 00:56:42 +00006627 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00006628 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6629 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006630 unsigned lproto_nargs = lproto->getNumArgs();
6631 unsigned rproto_nargs = rproto->getNumArgs();
6632
6633 // Compatible functions must have the same number of arguments
6634 if (lproto_nargs != rproto_nargs)
6635 return QualType();
6636
6637 // Variadic and non-variadic functions aren't compatible
6638 if (lproto->isVariadic() != rproto->isVariadic())
6639 return QualType();
6640
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00006641 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6642 return QualType();
6643
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006644 if (LangOpts.ObjCAutoRefCount &&
6645 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6646 return QualType();
6647
Eli Friedman3d815e72008-08-22 00:56:42 +00006648 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00006649 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00006650 for (unsigned i = 0; i < lproto_nargs; i++) {
6651 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6652 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006653 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6654 OfBlockPointer,
6655 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006656 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006657
6658 if (Unqualified)
6659 argtype = argtype.getUnqualifiedType();
6660
Eli Friedman3d815e72008-08-22 00:56:42 +00006661 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00006662 if (Unqualified) {
6663 largtype = largtype.getUnqualifiedType();
6664 rargtype = rargtype.getUnqualifiedType();
6665 }
6666
Chris Lattner61710852008-10-05 17:34:18 +00006667 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6668 allLTypes = false;
6669 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6670 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00006671 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006672
Eli Friedman3d815e72008-08-22 00:56:42 +00006673 if (allLTypes) return lhs;
6674 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00006675
6676 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6677 EPI.ExtInfo = einfo;
6678 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00006679 }
6680
6681 if (lproto) allRTypes = false;
6682 if (rproto) allLTypes = false;
6683
Douglas Gregor72564e72009-02-26 23:50:07 +00006684 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00006685 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00006686 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006687 if (proto->isVariadic()) return QualType();
6688 // Check that the types are compatible with the types that
6689 // would result from default argument promotions (C99 6.7.5.3p15).
6690 // The only types actually affected are promotable integer
6691 // types and floats, which would be passed as a different
6692 // type depending on whether the prototype is visible.
6693 unsigned proto_nargs = proto->getNumArgs();
6694 for (unsigned i = 0; i < proto_nargs; ++i) {
6695 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00006696
Eli Friedmanc586d5d2012-08-30 00:44:15 +00006697 // Look at the converted type of enum types, since that is the type used
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00006698 // to pass enum values.
Eli Friedmanc586d5d2012-08-30 00:44:15 +00006699 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
6700 argTy = Enum->getDecl()->getIntegerType();
6701 if (argTy.isNull())
6702 return QualType();
6703 }
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00006704
Eli Friedman3d815e72008-08-22 00:56:42 +00006705 if (argTy->isPromotableIntegerType() ||
6706 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6707 return QualType();
6708 }
6709
6710 if (allLTypes) return lhs;
6711 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00006712
6713 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6714 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00006715 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00006716 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00006717 }
6718
6719 if (allLTypes) return lhs;
6720 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00006721 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00006722}
6723
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006724QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00006725 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006726 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00006727 // C++ [expr]: If an expression initially has the type "reference to T", the
6728 // type is adjusted to "T" prior to any further analysis, the expression
6729 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00006730 // expression is an lvalue unless the reference is an rvalue reference and
6731 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006732 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6733 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00006734
6735 if (Unqualified) {
6736 LHS = LHS.getUnqualifiedType();
6737 RHS = RHS.getUnqualifiedType();
6738 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006739
Eli Friedman3d815e72008-08-22 00:56:42 +00006740 QualType LHSCan = getCanonicalType(LHS),
6741 RHSCan = getCanonicalType(RHS);
6742
6743 // If two types are identical, they are compatible.
6744 if (LHSCan == RHSCan)
6745 return LHS;
6746
John McCall0953e762009-09-24 19:53:00 +00006747 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006748 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6749 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00006750 if (LQuals != RQuals) {
6751 // If any of these qualifiers are different, we have a type
6752 // mismatch.
6753 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00006754 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6755 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00006756 return QualType();
6757
6758 // Exactly one GC qualifier difference is allowed: __strong is
6759 // okay if the other type has no GC qualifier but is an Objective
6760 // C object pointer (i.e. implicitly strong by default). We fix
6761 // this by pretending that the unqualified type was actually
6762 // qualified __strong.
6763 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6764 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6765 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6766
6767 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6768 return QualType();
6769
6770 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6771 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6772 }
6773 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6774 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6775 }
Eli Friedman3d815e72008-08-22 00:56:42 +00006776 return QualType();
John McCall0953e762009-09-24 19:53:00 +00006777 }
6778
6779 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00006780
Eli Friedman852d63b2009-06-01 01:22:52 +00006781 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6782 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00006783
Chris Lattner1adb8832008-01-14 05:45:46 +00006784 // We want to consider the two function types to be the same for these
6785 // comparisons, just force one to the other.
6786 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6787 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00006788
6789 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00006790 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6791 LHSClass = Type::ConstantArray;
6792 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6793 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00006794
John McCallc12c5bb2010-05-15 11:32:37 +00006795 // ObjCInterfaces are just specialized ObjCObjects.
6796 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6797 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6798
Nate Begeman213541a2008-04-18 23:10:10 +00006799 // Canonicalize ExtVector -> Vector.
6800 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6801 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00006802
Chris Lattnera36a61f2008-04-07 05:43:21 +00006803 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00006804 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00006805 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00006806 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00006807 // Compatibility is based on the underlying type, not the promotion
6808 // type.
John McCall183700f2009-09-21 23:43:11 +00006809 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianb918d6b2012-02-06 19:06:20 +00006810 QualType TINT = ETy->getDecl()->getIntegerType();
6811 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006812 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00006813 }
John McCall183700f2009-09-21 23:43:11 +00006814 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianb918d6b2012-02-06 19:06:20 +00006815 QualType TINT = ETy->getDecl()->getIntegerType();
6816 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006817 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00006818 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00006819 // allow block pointer type to match an 'id' type.
Fariborz Jahanian41963632012-01-26 17:08:50 +00006820 if (OfBlockPointer && !BlockReturnType) {
6821 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6822 return LHS;
6823 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6824 return RHS;
6825 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00006826
Eli Friedman3d815e72008-08-22 00:56:42 +00006827 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00006828 }
Eli Friedman3d815e72008-08-22 00:56:42 +00006829
Steve Naroff4a746782008-01-09 22:43:08 +00006830 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00006831 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00006832#define TYPE(Class, Base)
6833#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00006834#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00006835#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6836#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6837#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00006838 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00006839
Sebastian Redl7c80bd62009-03-16 23:22:08 +00006840 case Type::LValueReference:
6841 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00006842 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00006843 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00006844
John McCallc12c5bb2010-05-15 11:32:37 +00006845 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00006846 case Type::IncompleteArray:
6847 case Type::VariableArray:
6848 case Type::FunctionProto:
6849 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00006850 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00006851
Chris Lattner1adb8832008-01-14 05:45:46 +00006852 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00006853 {
6854 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00006855 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6856 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006857 if (Unqualified) {
6858 LHSPointee = LHSPointee.getUnqualifiedType();
6859 RHSPointee = RHSPointee.getUnqualifiedType();
6860 }
6861 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6862 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006863 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00006864 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00006865 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00006866 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00006867 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00006868 return getPointerType(ResultType);
6869 }
Steve Naroffc0febd52008-12-10 17:49:55 +00006870 case Type::BlockPointer:
6871 {
6872 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00006873 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6874 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006875 if (Unqualified) {
6876 LHSPointee = LHSPointee.getUnqualifiedType();
6877 RHSPointee = RHSPointee.getUnqualifiedType();
6878 }
6879 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6880 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00006881 if (ResultType.isNull()) return QualType();
6882 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6883 return LHS;
6884 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6885 return RHS;
6886 return getBlockPointerType(ResultType);
6887 }
Eli Friedmanb001de72011-10-06 23:00:33 +00006888 case Type::Atomic:
6889 {
6890 // Merge two pointer types, while trying to preserve typedef info
6891 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6892 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6893 if (Unqualified) {
6894 LHSValue = LHSValue.getUnqualifiedType();
6895 RHSValue = RHSValue.getUnqualifiedType();
6896 }
6897 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6898 Unqualified);
6899 if (ResultType.isNull()) return QualType();
6900 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6901 return LHS;
6902 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6903 return RHS;
6904 return getAtomicType(ResultType);
6905 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006906 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00006907 {
6908 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6909 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6910 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6911 return QualType();
6912
6913 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6914 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006915 if (Unqualified) {
6916 LHSElem = LHSElem.getUnqualifiedType();
6917 RHSElem = RHSElem.getUnqualifiedType();
6918 }
6919
6920 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006921 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00006922 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6923 return LHS;
6924 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6925 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00006926 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6927 ArrayType::ArraySizeModifier(), 0);
6928 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6929 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006930 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6931 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00006932 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6933 return LHS;
6934 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6935 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00006936 if (LVAT) {
6937 // FIXME: This isn't correct! But tricky to implement because
6938 // the array's size has to be the size of LHS, but the type
6939 // has to be different.
6940 return LHS;
6941 }
6942 if (RVAT) {
6943 // FIXME: This isn't correct! But tricky to implement because
6944 // the array's size has to be the size of RHS, but the type
6945 // has to be different.
6946 return RHS;
6947 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00006948 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6949 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00006950 return getIncompleteArrayType(ResultType,
6951 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006952 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006953 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00006954 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00006955 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00006956 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00006957 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00006958 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006959 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00006960 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00006961 case Type::Complex:
6962 // Distinct complex types are incompatible.
6963 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006964 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006965 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00006966 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6967 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006968 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00006969 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00006970 case Type::ObjCObject: {
6971 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006972 // FIXME: This should be type compatibility, e.g. whether
6973 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00006974 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6975 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6976 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00006977 return LHS;
6978
Eli Friedman3d815e72008-08-22 00:56:42 +00006979 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00006980 }
Steve Naroff14108da2009-07-10 23:34:53 +00006981 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006982 if (OfBlockPointer) {
6983 if (canAssignObjCInterfacesInBlockPointer(
6984 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006985 RHS->getAs<ObjCObjectPointerType>(),
6986 BlockReturnType))
David Blaikie7530c032012-01-17 06:56:22 +00006987 return LHS;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006988 return QualType();
6989 }
John McCall183700f2009-09-21 23:43:11 +00006990 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6991 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00006992 return LHS;
6993
Steve Naroffbc76dd02008-12-10 22:14:21 +00006994 return QualType();
David Blaikie7530c032012-01-17 06:56:22 +00006995 }
Steve Naroffec0550f2007-10-15 20:41:53 +00006996 }
Douglas Gregor72564e72009-02-26 23:50:07 +00006997
David Blaikie7530c032012-01-17 06:56:22 +00006998 llvm_unreachable("Invalid Type::Class!");
Steve Naroffec0550f2007-10-15 20:41:53 +00006999}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00007000
Fariborz Jahanian78213e42011-09-28 21:52:05 +00007001bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7002 const FunctionProtoType *FromFunctionType,
7003 const FunctionProtoType *ToFunctionType) {
7004 if (FromFunctionType->hasAnyConsumedArgs() !=
7005 ToFunctionType->hasAnyConsumedArgs())
7006 return false;
7007 FunctionProtoType::ExtProtoInfo FromEPI =
7008 FromFunctionType->getExtProtoInfo();
7009 FunctionProtoType::ExtProtoInfo ToEPI =
7010 ToFunctionType->getExtProtoInfo();
7011 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
7012 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
7013 ArgIdx != NumArgs; ++ArgIdx) {
7014 if (FromEPI.ConsumedArguments[ArgIdx] !=
7015 ToEPI.ConsumedArguments[ArgIdx])
7016 return false;
7017 }
7018 return true;
7019}
7020
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007021/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7022/// 'RHS' attributes and returns the merged version; including for function
7023/// return types.
7024QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7025 QualType LHSCan = getCanonicalType(LHS),
7026 RHSCan = getCanonicalType(RHS);
7027 // If two types are identical, they are compatible.
7028 if (LHSCan == RHSCan)
7029 return LHS;
7030 if (RHSCan->isFunctionType()) {
7031 if (!LHSCan->isFunctionType())
7032 return QualType();
7033 QualType OldReturnType =
7034 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7035 QualType NewReturnType =
7036 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7037 QualType ResReturnType =
7038 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7039 if (ResReturnType.isNull())
7040 return QualType();
7041 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7042 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7043 // In either case, use OldReturnType to build the new function type.
7044 const FunctionType *F = LHS->getAs<FunctionType>();
7045 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00007046 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7047 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007048 QualType ResultType
7049 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00007050 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007051 return ResultType;
7052 }
7053 }
7054 return QualType();
7055 }
7056
7057 // If the qualifiers are different, the types can still be merged.
7058 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7059 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7060 if (LQuals != RQuals) {
7061 // If any of these qualifiers are different, we have a type mismatch.
7062 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7063 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7064 return QualType();
7065
7066 // Exactly one GC qualifier difference is allowed: __strong is
7067 // okay if the other type has no GC qualifier but is an Objective
7068 // C object pointer (i.e. implicitly strong by default). We fix
7069 // this by pretending that the unqualified type was actually
7070 // qualified __strong.
7071 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7072 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7073 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7074
7075 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7076 return QualType();
7077
7078 if (GC_L == Qualifiers::Strong)
7079 return LHS;
7080 if (GC_R == Qualifiers::Strong)
7081 return RHS;
7082 return QualType();
7083 }
7084
7085 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7086 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7087 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7088 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7089 if (ResQT == LHSBaseQT)
7090 return LHS;
7091 if (ResQT == RHSBaseQT)
7092 return RHS;
7093 }
7094 return QualType();
7095}
7096
Chris Lattner5426bf62008-04-07 07:01:58 +00007097//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00007098// Integer Predicates
7099//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00007100
Jay Foad4ba2a172011-01-12 09:06:06 +00007101unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00007102 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00007103 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007104 if (T->isBooleanType())
7105 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00007106 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00007107 return (unsigned)getTypeSize(T);
7108}
7109
Abramo Bagnara762f1592012-09-09 10:21:24 +00007110QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregorf6094622010-07-23 15:58:24 +00007111 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00007112
7113 // Turn <4 x signed int> -> <4 x unsigned int>
7114 if (const VectorType *VTy = T->getAs<VectorType>())
7115 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00007116 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00007117
7118 // For enums, we return the unsigned version of the base type.
7119 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00007120 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00007121
7122 const BuiltinType *BTy = T->getAs<BuiltinType>();
7123 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007124 switch (BTy->getKind()) {
7125 case BuiltinType::Char_S:
7126 case BuiltinType::SChar:
7127 return UnsignedCharTy;
7128 case BuiltinType::Short:
7129 return UnsignedShortTy;
7130 case BuiltinType::Int:
7131 return UnsignedIntTy;
7132 case BuiltinType::Long:
7133 return UnsignedLongTy;
7134 case BuiltinType::LongLong:
7135 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00007136 case BuiltinType::Int128:
7137 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00007138 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00007139 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007140 }
7141}
7142
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00007143ASTMutationListener::~ASTMutationListener() { }
7144
Chris Lattner86df27b2009-06-14 00:45:47 +00007145
7146//===----------------------------------------------------------------------===//
7147// Builtin Type Computation
7148//===----------------------------------------------------------------------===//
7149
7150/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00007151/// pointer over the consumed characters. This returns the resultant type. If
7152/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7153/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7154/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00007155///
7156/// RequiresICE is filled in on return to indicate whether the value is required
7157/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00007158static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00007159 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00007160 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00007161 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00007162 // Modifiers.
7163 int HowLong = 0;
7164 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00007165 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007166
Chris Lattner33daae62010-10-01 22:42:38 +00007167 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00007168 bool Done = false;
7169 while (!Done) {
7170 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00007171 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007172 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00007173 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007174 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007175 case 'S':
7176 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7177 assert(!Signed && "Can't use 'S' modifier multiple times!");
7178 Signed = true;
7179 break;
7180 case 'U':
7181 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7182 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7183 Unsigned = true;
7184 break;
7185 case 'L':
7186 assert(HowLong <= 2 && "Can't have LLLL modifier");
7187 ++HowLong;
7188 break;
7189 }
7190 }
7191
7192 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00007193
Chris Lattner86df27b2009-06-14 00:45:47 +00007194 // Read the base type.
7195 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00007196 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00007197 case 'v':
7198 assert(HowLong == 0 && !Signed && !Unsigned &&
7199 "Bad modifiers used with 'v'!");
7200 Type = Context.VoidTy;
7201 break;
7202 case 'f':
7203 assert(HowLong == 0 && !Signed && !Unsigned &&
7204 "Bad modifiers used with 'f'!");
7205 Type = Context.FloatTy;
7206 break;
7207 case 'd':
7208 assert(HowLong < 2 && !Signed && !Unsigned &&
7209 "Bad modifiers used with 'd'!");
7210 if (HowLong)
7211 Type = Context.LongDoubleTy;
7212 else
7213 Type = Context.DoubleTy;
7214 break;
7215 case 's':
7216 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7217 if (Unsigned)
7218 Type = Context.UnsignedShortTy;
7219 else
7220 Type = Context.ShortTy;
7221 break;
7222 case 'i':
7223 if (HowLong == 3)
7224 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7225 else if (HowLong == 2)
7226 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7227 else if (HowLong == 1)
7228 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7229 else
7230 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7231 break;
7232 case 'c':
7233 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7234 if (Signed)
7235 Type = Context.SignedCharTy;
7236 else if (Unsigned)
7237 Type = Context.UnsignedCharTy;
7238 else
7239 Type = Context.CharTy;
7240 break;
7241 case 'b': // boolean
7242 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7243 Type = Context.BoolTy;
7244 break;
7245 case 'z': // size_t.
7246 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7247 Type = Context.getSizeType();
7248 break;
7249 case 'F':
7250 Type = Context.getCFConstantStringType();
7251 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00007252 case 'G':
7253 Type = Context.getObjCIdType();
7254 break;
7255 case 'H':
7256 Type = Context.getObjCSelType();
7257 break;
Fariborz Jahanianf7992132013-01-04 18:45:40 +00007258 case 'M':
7259 Type = Context.getObjCSuperType();
7260 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007261 case 'a':
7262 Type = Context.getBuiltinVaListType();
7263 assert(!Type.isNull() && "builtin va list type not initialized!");
7264 break;
7265 case 'A':
7266 // This is a "reference" to a va_list; however, what exactly
7267 // this means depends on how va_list is defined. There are two
7268 // different kinds of va_list: ones passed by value, and ones
7269 // passed by reference. An example of a by-value va_list is
7270 // x86, where va_list is a char*. An example of by-ref va_list
7271 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7272 // we want this argument to be a char*&; for x86-64, we want
7273 // it to be a __va_list_tag*.
7274 Type = Context.getBuiltinVaListType();
7275 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00007276 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00007277 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00007278 else
Chris Lattner86df27b2009-06-14 00:45:47 +00007279 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00007280 break;
7281 case 'V': {
7282 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00007283 unsigned NumElements = strtoul(Str, &End, 10);
7284 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00007285 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00007286
Chris Lattner14e0e742010-10-01 22:53:11 +00007287 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7288 RequiresICE, false);
7289 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00007290
7291 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00007292 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00007293 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00007294 break;
7295 }
Douglas Gregorb4bc99b2012-06-07 18:08:25 +00007296 case 'E': {
7297 char *End;
7298
7299 unsigned NumElements = strtoul(Str, &End, 10);
7300 assert(End != Str && "Missing vector size");
7301
7302 Str = End;
7303
7304 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7305 false);
7306 Type = Context.getExtVectorType(ElementType, NumElements);
7307 break;
7308 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00007309 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00007310 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7311 false);
7312 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00007313 Type = Context.getComplexType(ElementType);
7314 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00007315 }
7316 case 'Y' : {
7317 Type = Context.getPointerDiffType();
7318 break;
7319 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007320 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00007321 Type = Context.getFILEType();
7322 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007323 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00007324 return QualType();
7325 }
Mike Stumpfd612db2009-07-28 23:47:15 +00007326 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007327 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00007328 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00007329 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00007330 else
7331 Type = Context.getjmp_bufType();
7332
Mike Stumpfd612db2009-07-28 23:47:15 +00007333 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007334 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00007335 return QualType();
7336 }
7337 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00007338 case 'K':
7339 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7340 Type = Context.getucontext_tType();
7341
7342 if (Type.isNull()) {
7343 Error = ASTContext::GE_Missing_ucontext;
7344 return QualType();
7345 }
7346 break;
Eli Friedman6902e412012-11-27 02:58:24 +00007347 case 'p':
7348 Type = Context.getProcessIDType();
7349 break;
Mike Stump782fa302009-07-28 02:25:19 +00007350 }
Mike Stump1eb44332009-09-09 15:08:12 +00007351
Chris Lattner33daae62010-10-01 22:42:38 +00007352 // If there are modifiers and if we're allowed to parse them, go for it.
7353 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00007354 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00007355 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00007356 default: Done = true; --Str; break;
7357 case '*':
7358 case '&': {
7359 // Both pointers and references can have their pointee types
7360 // qualified with an address space.
7361 char *End;
7362 unsigned AddrSpace = strtoul(Str, &End, 10);
7363 if (End != Str && AddrSpace != 0) {
7364 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7365 Str = End;
7366 }
7367 if (c == '*')
7368 Type = Context.getPointerType(Type);
7369 else
7370 Type = Context.getLValueReferenceType(Type);
7371 break;
7372 }
7373 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7374 case 'C':
7375 Type = Type.withConst();
7376 break;
7377 case 'D':
7378 Type = Context.getVolatileType(Type);
7379 break;
Ted Kremenek18932a02012-01-20 21:40:12 +00007380 case 'R':
7381 Type = Type.withRestrict();
7382 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007383 }
7384 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00007385
Chris Lattner14e0e742010-10-01 22:53:11 +00007386 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00007387 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00007388
Chris Lattner86df27b2009-06-14 00:45:47 +00007389 return Type;
7390}
7391
7392/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00007393QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00007394 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00007395 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00007396 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00007397
Chris Lattner5f9e2722011-07-23 10:55:15 +00007398 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00007399
Chris Lattner14e0e742010-10-01 22:53:11 +00007400 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00007401 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00007402 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7403 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007404 if (Error != GE_None)
7405 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00007406
7407 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7408
Chris Lattner86df27b2009-06-14 00:45:47 +00007409 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00007410 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007411 if (Error != GE_None)
7412 return QualType();
7413
Chris Lattner14e0e742010-10-01 22:53:11 +00007414 // If this argument is required to be an IntegerConstantExpression and the
7415 // caller cares, fill in the bitmask we return.
7416 if (RequiresICE && IntegerConstantArgs)
7417 *IntegerConstantArgs |= 1 << ArgTypes.size();
7418
Chris Lattner86df27b2009-06-14 00:45:47 +00007419 // Do array -> pointer decay. The builtin should use the decayed type.
7420 if (Ty->isArrayType())
7421 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00007422
Chris Lattner86df27b2009-06-14 00:45:47 +00007423 ArgTypes.push_back(Ty);
7424 }
7425
7426 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7427 "'.' should only occur at end of builtin type list!");
7428
John McCall00ccbef2010-12-21 00:44:39 +00007429 FunctionType::ExtInfo EI;
7430 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7431
7432 bool Variadic = (TypeStr[0] == '.');
7433
7434 // We really shouldn't be making a no-proto type here, especially in C++.
7435 if (ArgTypes.empty() && Variadic)
7436 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00007437
John McCalle23cf432010-12-14 08:05:40 +00007438 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00007439 EPI.ExtInfo = EI;
7440 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00007441
7442 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00007443}
Eli Friedmana95d7572009-08-19 07:44:53 +00007444
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007445GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
7446 GVALinkage External = GVA_StrongExternal;
7447
7448 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007449 switch (L) {
7450 case NoLinkage:
7451 case InternalLinkage:
7452 case UniqueExternalLinkage:
7453 return GVA_Internal;
7454
7455 case ExternalLinkage:
7456 switch (FD->getTemplateSpecializationKind()) {
7457 case TSK_Undeclared:
7458 case TSK_ExplicitSpecialization:
7459 External = GVA_StrongExternal;
7460 break;
7461
7462 case TSK_ExplicitInstantiationDefinition:
7463 return GVA_ExplicitTemplateInstantiation;
7464
7465 case TSK_ExplicitInstantiationDeclaration:
7466 case TSK_ImplicitInstantiation:
7467 External = GVA_TemplateInstantiation;
7468 break;
7469 }
7470 }
7471
7472 if (!FD->isInlined())
7473 return External;
7474
David Blaikie4e4d0842012-03-11 07:00:24 +00007475 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007476 // GNU or C99 inline semantics. Determine whether this symbol should be
7477 // externally visible.
7478 if (FD->isInlineDefinitionExternallyVisible())
7479 return External;
7480
7481 // C99 inline semantics, where the symbol is not externally visible.
7482 return GVA_C99Inline;
7483 }
7484
7485 // C++0x [temp.explicit]p9:
7486 // [ Note: The intent is that an inline function that is the subject of
7487 // an explicit instantiation declaration will still be implicitly
7488 // instantiated when used so that the body can be considered for
7489 // inlining, but that no out-of-line copy of the inline function would be
7490 // generated in the translation unit. -- end note ]
7491 if (FD->getTemplateSpecializationKind()
7492 == TSK_ExplicitInstantiationDeclaration)
7493 return GVA_C99Inline;
7494
7495 return GVA_CXXInline;
7496}
7497
7498GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7499 // If this is a static data member, compute the kind of template
7500 // specialization. Otherwise, this variable is not part of a
7501 // template.
7502 TemplateSpecializationKind TSK = TSK_Undeclared;
7503 if (VD->isStaticDataMember())
7504 TSK = VD->getTemplateSpecializationKind();
7505
7506 Linkage L = VD->getLinkage();
Rafael Espindola62a833e2013-01-02 04:19:07 +00007507 assert (!(L == ExternalLinkage && getLangOpts().CPlusPlus &&
7508 VD->getType()->getLinkage() == UniqueExternalLinkage));
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007509
7510 switch (L) {
7511 case NoLinkage:
7512 case InternalLinkage:
7513 case UniqueExternalLinkage:
7514 return GVA_Internal;
7515
7516 case ExternalLinkage:
7517 switch (TSK) {
7518 case TSK_Undeclared:
7519 case TSK_ExplicitSpecialization:
7520 return GVA_StrongExternal;
7521
7522 case TSK_ExplicitInstantiationDeclaration:
7523 llvm_unreachable("Variable should not be instantiated");
7524 // Fall through to treat this like any other instantiation.
7525
7526 case TSK_ExplicitInstantiationDefinition:
7527 return GVA_ExplicitTemplateInstantiation;
7528
7529 case TSK_ImplicitInstantiation:
7530 return GVA_TemplateInstantiation;
7531 }
7532 }
7533
David Blaikie7530c032012-01-17 06:56:22 +00007534 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007535}
7536
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00007537bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007538 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7539 if (!VD->isFileVarDecl())
7540 return false;
Argyrios Kyrtzidis144b38a2011-09-13 21:35:00 +00007541 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007542 return false;
7543
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007544 // Weak references don't produce any output by themselves.
7545 if (D->hasAttr<WeakRefAttr>())
7546 return false;
7547
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007548 // Aliases and used decls are required.
7549 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7550 return true;
7551
7552 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7553 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00007554 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00007555 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007556
7557 // Constructors and destructors are required.
7558 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7559 return true;
7560
7561 // The key function for a class is required.
7562 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7563 const CXXRecordDecl *RD = MD->getParent();
7564 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7565 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
7566 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7567 return true;
7568 }
7569 }
7570
7571 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7572
7573 // static, static inline, always_inline, and extern inline functions can
7574 // always be deferred. Normal inline functions can be deferred in C99/C++.
7575 // Implicit template instantiations can also be deferred in C++.
7576 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev3a5aca82012-02-02 06:06:34 +00007577 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007578 return false;
7579 return true;
7580 }
Douglas Gregor94da1582011-09-10 00:22:34 +00007581
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007582 const VarDecl *VD = cast<VarDecl>(D);
7583 assert(VD->isFileVarDecl() && "Expected file scoped var");
7584
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007585 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7586 return false;
7587
Richard Smith5f9a7e32012-11-12 21:38:00 +00007588 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007589 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smith5f9a7e32012-11-12 21:38:00 +00007590 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7591 return true;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007592
Richard Smith5f9a7e32012-11-12 21:38:00 +00007593 // Variables that have destruction with side-effects are required.
7594 if (VD->getType().isDestructedType())
7595 return true;
7596
7597 // Variables that have initialization with side-effects are required.
7598 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7599 return true;
7600
7601 return false;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007602}
Charles Davis071cc7d2010-08-16 03:33:14 +00007603
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007604CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davisee743f92010-11-09 18:04:24 +00007605 // Pass through to the C++ ABI object
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007606 return ABI->getDefaultMethodCallConv(isVariadic);
7607}
7608
7609CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
7610 if (CC == CC_C && !LangOpts.MRTD && getTargetInfo().getCXXABI() != CXXABI_Microsoft)
7611 return CC_Default;
7612 return CC;
Charles Davisee743f92010-11-09 18:04:24 +00007613}
7614
Jay Foad4ba2a172011-01-12 09:06:06 +00007615bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00007616 // Pass through to the C++ ABI object
7617 return ABI->isNearlyEmpty(RD);
7618}
7619
Peter Collingbourne14110472011-01-13 18:57:25 +00007620MangleContext *ASTContext::createMangleContext() {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00007621 switch (Target->getCXXABI()) {
Peter Collingbourne14110472011-01-13 18:57:25 +00007622 case CXXABI_ARM:
7623 case CXXABI_Itanium:
7624 return createItaniumMangleContext(*this, getDiagnostics());
7625 case CXXABI_Microsoft:
7626 return createMicrosoftMangleContext(*this, getDiagnostics());
7627 }
David Blaikieb219cfc2011-09-23 05:06:16 +00007628 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00007629}
7630
Charles Davis071cc7d2010-08-16 03:33:14 +00007631CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00007632
7633size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00007634 return ASTRecordLayouts.getMemorySize()
7635 + llvm::capacity_in_bytes(ObjCLayouts)
7636 + llvm::capacity_in_bytes(KeyFunctions)
7637 + llvm::capacity_in_bytes(ObjCImpls)
7638 + llvm::capacity_in_bytes(BlockVarCopyInits)
7639 + llvm::capacity_in_bytes(DeclAttrs)
7640 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7641 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7642 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7643 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7644 + llvm::capacity_in_bytes(OverriddenMethods)
7645 + llvm::capacity_in_bytes(Types)
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007646 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet0d95f0d2011-08-14 14:28:49 +00007647 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00007648}
Ted Kremenekd211cb72011-10-06 05:00:56 +00007649
David Blaikie66cff722012-11-14 01:52:05 +00007650void ASTContext::addUnnamedTag(const TagDecl *Tag) {
7651 // FIXME: This mangling should be applied to function local classes too
7652 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl() ||
7653 !isa<CXXRecordDecl>(Tag->getParent()) || Tag->getLinkage() != ExternalLinkage)
7654 return;
7655
7656 std::pair<llvm::DenseMap<const DeclContext *, unsigned>::iterator, bool> P =
7657 UnnamedMangleContexts.insert(std::make_pair(Tag->getParent(), 0));
7658 UnnamedMangleNumbers.insert(std::make_pair(Tag, P.first->second++));
7659}
7660
7661int ASTContext::getUnnamedTagManglingNumber(const TagDecl *Tag) const {
7662 llvm::DenseMap<const TagDecl *, unsigned>::const_iterator I =
7663 UnnamedMangleNumbers.find(Tag);
7664 return I != UnnamedMangleNumbers.end() ? I->second : -1;
7665}
7666
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00007667unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7668 CXXRecordDecl *Lambda = CallOperator->getParent();
7669 return LambdaMangleContexts[Lambda->getDeclContext()]
7670 .getManglingNumber(CallOperator);
7671}
7672
7673
Ted Kremenekd211cb72011-10-06 05:00:56 +00007674void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7675 ParamIndices[D] = index;
7676}
7677
7678unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7679 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7680 assert(I != ParamIndices.end() &&
7681 "ParmIndices lacks entry set by ParmVarDecl");
7682 return I->second;
7683}