blob: c1f31529b3de3c77bc05015fe7a0de42f697ab08 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000015#include "CXXABI.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000016#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000018#include "clang/AST/CharUnits.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000019#include "clang/AST/Comment.h"
Dmitri Gribenkoaa580812012-08-09 00:03:17 +000020#include "clang/AST/CommentCommandTraits.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000021#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000022#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000023#include "clang/AST/DeclTemplate.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000024#include "clang/AST/Expr.h"
John McCallea1471e2010-05-20 01:18:31 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000026#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000027#include "clang/AST/Mangle.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000028#include "clang/AST/RecordLayout.h"
29#include "clang/AST/TypeLoc.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000030#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000031#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000032#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000033#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000034#include "llvm/ADT/StringExtras.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000035#include "llvm/Support/Capacity.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000036#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000037#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +000038#include <map>
Anders Carlsson29445a02009-07-18 21:19:52 +000039
Reid Spencer5f016e22007-07-11 17:01:13 +000040using namespace clang;
41
Douglas Gregor18274032010-07-03 00:47:00 +000042unsigned ASTContext::NumImplicitDefaultConstructors;
43unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000044unsigned ASTContext::NumImplicitCopyConstructors;
45unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000046unsigned ASTContext::NumImplicitMoveConstructors;
47unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000048unsigned ASTContext::NumImplicitCopyAssignmentOperators;
49unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000050unsigned ASTContext::NumImplicitMoveAssignmentOperators;
51unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000052unsigned ASTContext::NumImplicitDestructors;
53unsigned ASTContext::NumImplicitDestructorsDeclared;
54
Reid Spencer5f016e22007-07-11 17:01:13 +000055enum FloatingRank {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +000056 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Reid Spencer5f016e22007-07-11 17:01:13 +000057};
58
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000059RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +000060 if (!CommentsLoaded && ExternalSource) {
61 ExternalSource->ReadComments();
62 CommentsLoaded = true;
63 }
64
65 assert(D);
66
Dmitri Gribenkoc3fee352012-06-28 16:19:39 +000067 // User can not attach documentation to implicit declarations.
68 if (D->isImplicit())
69 return NULL;
70
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +000071 // User can not attach documentation to implicit instantiations.
72 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
73 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
74 return NULL;
75 }
76
Dmitri Gribenkodce750b2012-08-20 22:36:31 +000077 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
78 if (VD->isStaticDataMember() &&
79 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
80 return NULL;
81 }
82
83 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
84 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
85 return NULL;
86 }
87
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +000088 if (const ClassTemplateSpecializationDecl *CTSD =
89 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
90 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
91 if (TSK == TSK_ImplicitInstantiation ||
92 TSK == TSK_Undeclared)
93 return NULL;
94 }
95
Dmitri Gribenkodce750b2012-08-20 22:36:31 +000096 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
97 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
98 return NULL;
99 }
Fariborz Jahanian099ecfb2013-04-17 21:05:20 +0000100 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
101 // When tag declaration (but not definition!) is part of the
102 // decl-specifier-seq of some other declaration, it doesn't get comment
103 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
104 return NULL;
105 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000106 // TODO: handle comments for function parameters properly.
107 if (isa<ParmVarDecl>(D))
108 return NULL;
109
Dmitri Gribenko96b09862012-07-31 22:37:06 +0000110 // TODO: we could look up template parameter documentation in the template
111 // documentation.
112 if (isa<TemplateTypeParmDecl>(D) ||
113 isa<NonTypeTemplateParmDecl>(D) ||
114 isa<TemplateTemplateParmDecl>(D))
115 return NULL;
116
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000117 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000118
119 // If there are no comments anywhere, we won't find anything.
120 if (RawComments.empty())
121 return NULL;
122
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000123 // Find declaration location.
124 // For Objective-C declarations we generally don't expect to have multiple
125 // declarators, thus use declaration starting location as the "declaration
126 // location".
127 // For all other declarations multiple declarators are used quite frequently,
128 // so we use the location of the identifier as the "declaration location".
129 SourceLocation DeclLoc;
130 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko96b09862012-07-31 22:37:06 +0000131 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +0000132 isa<RedeclarableTemplateDecl>(D) ||
133 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000134 DeclLoc = D->getLocStart();
135 else
136 DeclLoc = D->getLocation();
137
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000138 // If the declaration doesn't map directly to a location in a file, we
139 // can't find the comment.
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000140 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
141 return NULL;
142
143 // Find the comment that occurs just after this declaration.
Dmitri Gribenkoa444f182012-07-17 22:01:09 +0000144 ArrayRef<RawComment *>::iterator Comment;
145 {
146 // When searching for comments during parsing, the comment we are looking
147 // for is usually among the last two comments we parsed -- check them
148 // first.
Dmitri Gribenko6fd7d302013-04-10 15:35:17 +0000149 RawComment CommentAtDeclLoc(
150 SourceMgr, SourceRange(DeclLoc), false,
151 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoa444f182012-07-17 22:01:09 +0000152 BeforeThanCompare<RawComment> Compare(SourceMgr);
153 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
154 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
155 if (!Found && RawComments.size() >= 2) {
156 MaybeBeforeDecl--;
157 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
158 }
159
160 if (Found) {
161 Comment = MaybeBeforeDecl + 1;
162 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
163 &CommentAtDeclLoc, Compare));
164 } else {
165 // Slow path.
166 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
167 &CommentAtDeclLoc, Compare);
168 }
169 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000170
171 // Decompose the location for the declaration and find the beginning of the
172 // file buffer.
173 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
174
175 // First check whether we have a trailing comment.
176 if (Comment != RawComments.end() &&
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000177 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Dmitri Gribenko9c006762012-07-06 23:27:33 +0000178 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000179 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000180 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000181 // Check that Doxygen trailing comment comes after the declaration, starts
182 // on the same line and in the same file as the declaration.
183 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
184 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
185 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
186 CommentBeginDecomp.second)) {
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000187 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000188 }
189 }
190
191 // The comment just after the declaration was not a trailing comment.
192 // Let's look at the previous comment.
193 if (Comment == RawComments.begin())
194 return NULL;
195 --Comment;
196
197 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000198 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000199 return NULL;
200
201 // Decompose the end of the comment.
202 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000203 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000204
205 // If the comment and the declaration aren't in the same file, then they
206 // aren't related.
207 if (DeclLocDecomp.first != CommentEndDecomp.first)
208 return NULL;
209
210 // Get the corresponding buffer.
211 bool Invalid = false;
212 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
213 &Invalid).data();
214 if (Invalid)
215 return NULL;
216
217 // Extract text between the comment and declaration.
218 StringRef Text(Buffer + CommentEndDecomp.second,
219 DeclLocDecomp.second - CommentEndDecomp.second);
220
Dmitri Gribenko8bdb58a2012-06-27 23:43:37 +0000221 // There should be no other declarations or preprocessor directives between
222 // comment and declaration.
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000223 if (Text.find_first_of(",;{}#@") != StringRef::npos)
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000224 return NULL;
225
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000226 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000227}
228
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000229namespace {
230/// If we have a 'templated' declaration for a template, adjust 'D' to
231/// refer to the actual template.
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000232/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000233const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregorcd81df22012-08-13 16:37:30 +0000234 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000235 // Is this function declaration part of a function template?
Douglas Gregorcd81df22012-08-13 16:37:30 +0000236 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000237 return FTD;
238
239 // Nothing to do if function is not an implicit instantiation.
240 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
241 return D;
242
243 // Function is an implicit instantiation of a function template?
244 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
245 return FTD;
246
247 // Function is instantiated from a member definition of a class template?
248 if (const FunctionDecl *MemberDecl =
249 FD->getInstantiatedFromMemberFunction())
250 return MemberDecl;
251
252 return D;
Douglas Gregorcd81df22012-08-13 16:37:30 +0000253 }
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000254 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
255 // Static data member is instantiated from a member definition of a class
256 // template?
257 if (VD->isStaticDataMember())
258 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
259 return MemberDecl;
260
261 return D;
262 }
263 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
264 // Is this class declaration part of a class template?
265 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
266 return CTD;
267
268 // Class is an implicit instantiation of a class template or partial
269 // specialization?
270 if (const ClassTemplateSpecializationDecl *CTSD =
271 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
272 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
273 return D;
274 llvm::PointerUnion<ClassTemplateDecl *,
275 ClassTemplatePartialSpecializationDecl *>
276 PU = CTSD->getSpecializedTemplateOrPartial();
277 return PU.is<ClassTemplateDecl*>() ?
278 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
279 static_cast<const Decl*>(
280 PU.get<ClassTemplatePartialSpecializationDecl *>());
281 }
282
283 // Class is instantiated from a member definition of a class template?
284 if (const MemberSpecializationInfo *Info =
285 CRD->getMemberSpecializationInfo())
286 return Info->getInstantiatedFrom();
287
288 return D;
289 }
290 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
291 // Enum is instantiated from a member definition of a class template?
292 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
293 return MemberDecl;
294
295 return D;
296 }
297 // FIXME: Adjust alias templates?
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000298 return D;
299}
300} // unnamed namespace
301
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000302const RawComment *ASTContext::getRawCommentForAnyRedecl(
303 const Decl *D,
304 const Decl **OriginalDecl) const {
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000305 D = adjustDeclToTemplate(D);
Douglas Gregorcd81df22012-08-13 16:37:30 +0000306
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000307 // Check whether we have cached a comment for this declaration already.
308 {
309 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
310 RedeclComments.find(D);
311 if (Pos != RedeclComments.end()) {
312 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000313 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
314 if (OriginalDecl)
315 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000316 return Raw.getRaw();
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000317 }
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000318 }
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000319 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000320
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000321 // Search for comments attached to declarations in the redeclaration chain.
322 const RawComment *RC = NULL;
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000323 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000324 for (Decl::redecl_iterator I = D->redecls_begin(),
325 E = D->redecls_end();
326 I != E; ++I) {
327 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
328 RedeclComments.find(*I);
329 if (Pos != RedeclComments.end()) {
330 const RawCommentAndCacheFlags &Raw = Pos->second;
331 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
332 RC = Raw.getRaw();
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000333 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000334 break;
335 }
336 } else {
337 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000338 OriginalDeclForRC = *I;
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000339 RawCommentAndCacheFlags Raw;
340 if (RC) {
341 Raw.setRaw(RC);
342 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
343 } else
344 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000345 Raw.setOriginalDecl(*I);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000346 RedeclComments[*I] = Raw;
347 if (RC)
348 break;
349 }
350 }
351
Dmitri Gribenko8376f592012-06-28 16:25:36 +0000352 // If we found a comment, it should be a documentation comment.
353 assert(!RC || RC->isDocumentation());
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000354
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000355 if (OriginalDecl)
356 *OriginalDecl = OriginalDeclForRC;
357
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000358 // Update cache for every declaration in the redeclaration chain.
359 RawCommentAndCacheFlags Raw;
360 Raw.setRaw(RC);
361 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000362 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000363
364 for (Decl::redecl_iterator I = D->redecls_begin(),
365 E = D->redecls_end();
366 I != E; ++I) {
367 RawCommentAndCacheFlags &R = RedeclComments[*I];
368 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
369 R = Raw;
370 }
371
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000372 return RC;
373}
374
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000375static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
376 SmallVectorImpl<const NamedDecl *> &Redeclared) {
377 const DeclContext *DC = ObjCMethod->getDeclContext();
378 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
379 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
380 if (!ID)
381 return;
382 // Add redeclared method here.
Douglas Gregord3297242013-01-16 23:00:23 +0000383 for (ObjCInterfaceDecl::known_extensions_iterator
384 Ext = ID->known_extensions_begin(),
385 ExtEnd = ID->known_extensions_end();
386 Ext != ExtEnd; ++Ext) {
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000387 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregord3297242013-01-16 23:00:23 +0000388 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000389 ObjCMethod->isInstanceMethod()))
390 Redeclared.push_back(RedeclaredMethod);
391 }
392 }
393}
394
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000395comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
396 const Decl *D) const {
397 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
398 ThisDeclInfo->CommentDecl = D;
399 ThisDeclInfo->IsFilled = false;
400 ThisDeclInfo->fill();
401 ThisDeclInfo->CommentDecl = FC->getDecl();
402 comments::FullComment *CFC =
403 new (*this) comments::FullComment(FC->getBlocks(),
404 ThisDeclInfo);
405 return CFC;
406
407}
408
Richard Smith0a74a4c2013-05-21 05:24:00 +0000409comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
410 const RawComment *RC = getRawCommentForDeclNoCache(D);
411 return RC ? RC->parse(*this, 0, D) : 0;
412}
413
Dmitri Gribenko19523542012-09-29 11:40:46 +0000414comments::FullComment *ASTContext::getCommentForDecl(
415 const Decl *D,
416 const Preprocessor *PP) const {
Fariborz Jahanianfbff0c42013-05-13 17:27:00 +0000417 if (D->isInvalidDecl())
418 return NULL;
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000419 D = adjustDeclToTemplate(D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000420
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000421 const Decl *Canonical = D->getCanonicalDecl();
422 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
423 ParsedComments.find(Canonical);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000424
425 if (Pos != ParsedComments.end()) {
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000426 if (Canonical != D) {
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000427 comments::FullComment *FC = Pos->second;
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000428 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000429 return CFC;
430 }
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000431 return Pos->second;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000432 }
433
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000434 const Decl *OriginalDecl;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000435
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000436 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000437 if (!RC) {
438 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko1e905da2012-11-03 14:24:57 +0000439 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanianc328d9c2013-01-12 00:28:34 +0000440 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000441 if (OMD && OMD->isPropertyAccessor())
442 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
443 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
444 return cloneFullComment(FC, D);
Fariborz Jahanianc328d9c2013-01-12 00:28:34 +0000445 if (OMD)
Dmitri Gribenko1e905da2012-11-03 14:24:57 +0000446 addRedeclaredMethods(OMD, Overridden);
447 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000448 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
449 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
450 return cloneFullComment(FC, D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000451 }
Fariborz Jahanian4857fdc2013-05-02 15:44:16 +0000452 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +0000453 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000454 // does not have one of its own.
Fariborz Jahanian41170b52013-01-25 22:48:32 +0000455 QualType QT = TD->getUnderlyingType();
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +0000456 if (const TagType *TT = QT->getAs<TagType>())
457 if (const Decl *TD = TT->getDecl())
458 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000459 return cloneFullComment(FC, D);
Fariborz Jahanian41170b52013-01-25 22:48:32 +0000460 }
Fariborz Jahanian622bb4a2013-04-26 20:55:38 +0000461 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
462 while (IC->getSuperClass()) {
463 IC = IC->getSuperClass();
464 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
465 return cloneFullComment(FC, D);
466 }
467 }
468 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
469 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
470 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
471 return cloneFullComment(FC, D);
472 }
473 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
474 if (!(RD = RD->getDefinition()))
475 return NULL;
476 // Check non-virtual bases.
477 for (CXXRecordDecl::base_class_const_iterator I =
478 RD->bases_begin(), E = RD->bases_end(); I != E; ++I) {
Fariborz Jahanian91efca02013-04-26 23:34:36 +0000479 if (I->isVirtual() || (I->getAccessSpecifier() != AS_public))
Fariborz Jahanian622bb4a2013-04-26 20:55:38 +0000480 continue;
481 QualType Ty = I->getType();
482 if (Ty.isNull())
483 continue;
484 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
485 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
486 continue;
487
488 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
489 return cloneFullComment(FC, D);
490 }
491 }
492 // Check virtual bases.
493 for (CXXRecordDecl::base_class_const_iterator I =
494 RD->vbases_begin(), E = RD->vbases_end(); I != E; ++I) {
Fariborz Jahanian91efca02013-04-26 23:34:36 +0000495 if (I->getAccessSpecifier() != AS_public)
496 continue;
Fariborz Jahanian622bb4a2013-04-26 20:55:38 +0000497 QualType Ty = I->getType();
498 if (Ty.isNull())
499 continue;
500 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
501 if (!(VirtualBase= VirtualBase->getDefinition()))
502 continue;
503 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
504 return cloneFullComment(FC, D);
505 }
506 }
507 }
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000508 return NULL;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000509 }
510
Dmitri Gribenko4b41c652012-08-22 18:12:19 +0000511 // If the RawComment was attached to other redeclaration of this Decl, we
512 // should parse the comment in context of that other Decl. This is important
513 // because comments can contain references to parameter names which can be
514 // different across redeclarations.
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000515 if (D != OriginalDecl)
Dmitri Gribenko19523542012-09-29 11:40:46 +0000516 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000517
Dmitri Gribenko19523542012-09-29 11:40:46 +0000518 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000519 ParsedComments[Canonical] = FC;
520 return FC;
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000521}
522
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000523void
524ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
525 TemplateTemplateParmDecl *Parm) {
526 ID.AddInteger(Parm->getDepth());
527 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +0000528 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000529
530 TemplateParameterList *Params = Parm->getTemplateParameters();
531 ID.AddInteger(Params->size());
532 for (TemplateParameterList::const_iterator P = Params->begin(),
533 PEnd = Params->end();
534 P != PEnd; ++P) {
535 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
536 ID.AddInteger(0);
537 ID.AddBoolean(TTP->isParameterPack());
538 continue;
539 }
540
541 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
542 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000543 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000544 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000545 if (NTTP->isExpandedParameterPack()) {
546 ID.AddBoolean(true);
547 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000548 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
549 QualType T = NTTP->getExpansionType(I);
550 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
551 }
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000552 } else
553 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000554 continue;
555 }
556
557 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
558 ID.AddInteger(2);
559 Profile(ID, TTP);
560 }
561}
562
563TemplateTemplateParmDecl *
564ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +0000565 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000566 // Check if we already have a canonical template template parameter.
567 llvm::FoldingSetNodeID ID;
568 CanonicalTemplateTemplateParm::Profile(ID, TTP);
569 void *InsertPos = 0;
570 CanonicalTemplateTemplateParm *Canonical
571 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
572 if (Canonical)
573 return Canonical->getParam();
574
575 // Build a canonical template parameter list.
576 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000577 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000578 CanonParams.reserve(Params->size());
579 for (TemplateParameterList::const_iterator P = Params->begin(),
580 PEnd = Params->end();
581 P != PEnd; ++P) {
582 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
583 CanonParams.push_back(
584 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000585 SourceLocation(),
586 SourceLocation(),
587 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000588 TTP->getIndex(), 0, false,
589 TTP->isParameterPack()));
590 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000591 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
592 QualType T = getCanonicalType(NTTP->getType());
593 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
594 NonTypeTemplateParmDecl *Param;
595 if (NTTP->isExpandedParameterPack()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000596 SmallVector<QualType, 2> ExpandedTypes;
597 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000598 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
599 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
600 ExpandedTInfos.push_back(
601 getTrivialTypeSourceInfo(ExpandedTypes.back()));
602 }
603
604 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000605 SourceLocation(),
606 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000607 NTTP->getDepth(),
608 NTTP->getPosition(), 0,
609 T,
610 TInfo,
611 ExpandedTypes.data(),
612 ExpandedTypes.size(),
613 ExpandedTInfos.data());
614 } else {
615 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000616 SourceLocation(),
617 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000618 NTTP->getDepth(),
619 NTTP->getPosition(), 0,
620 T,
621 NTTP->isParameterPack(),
622 TInfo);
623 }
624 CanonParams.push_back(Param);
625
626 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000627 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
628 cast<TemplateTemplateParmDecl>(*P)));
629 }
630
631 TemplateTemplateParmDecl *CanonTTP
632 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
633 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000634 TTP->getPosition(),
635 TTP->isParameterPack(),
636 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000637 TemplateParameterList::Create(*this, SourceLocation(),
638 SourceLocation(),
639 CanonParams.data(),
640 CanonParams.size(),
641 SourceLocation()));
642
643 // Get the new insert position for the node we care about.
644 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
645 assert(Canonical == 0 && "Shouldn't be in the map!");
646 (void)Canonical;
647
648 // Create the canonical template template parameter entry.
649 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
650 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
651 return CanonTTP;
652}
653
Charles Davis071cc7d2010-08-16 03:33:14 +0000654CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000655 if (!LangOpts.CPlusPlus) return 0;
656
John McCallb8b2c9d2013-01-25 22:30:49 +0000657 switch (T.getCXXABI().getKind()) {
658 case TargetCXXABI::GenericARM:
659 case TargetCXXABI::iOS:
John McCallee79a4c2010-08-21 22:46:04 +0000660 return CreateARMCXXABI(*this);
Tim Northoverc264e162013-01-31 12:13:10 +0000661 case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
John McCallb8b2c9d2013-01-25 22:30:49 +0000662 case TargetCXXABI::GenericItanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000663 return CreateItaniumCXXABI(*this);
John McCallb8b2c9d2013-01-25 22:30:49 +0000664 case TargetCXXABI::Microsoft:
Charles Davis20cf7172010-08-19 02:18:14 +0000665 return CreateMicrosoftCXXABI(*this);
666 }
David Blaikie7530c032012-01-17 06:56:22 +0000667 llvm_unreachable("Invalid CXXABI type!");
Charles Davis071cc7d2010-08-16 03:33:14 +0000668}
669
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000670static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000671 const LangOptions &LOpts) {
672 if (LOpts.FakeAddressSpaceMap) {
673 // The fake address space map must have a distinct entry for each
674 // language-specific address space.
675 static const unsigned FakeAddrSpaceMap[] = {
676 1, // opencl_global
677 2, // opencl_local
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +0000678 3, // opencl_constant
679 4, // cuda_device
680 5, // cuda_constant
681 6 // cuda_shared
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000682 };
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000683 return &FakeAddrSpaceMap;
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000684 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000685 return &T.getAddressSpaceMap();
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000686 }
687}
688
Douglas Gregor3e3cd932011-09-01 20:23:19 +0000689ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000690 const TargetInfo *t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000691 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000692 Builtin::Context &builtins,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000693 unsigned size_reserve,
694 bool DelayInitialization)
695 : FunctionProtoTypes(this_()),
696 TemplateSpecializationTypes(this_()),
697 DependentTemplateSpecializationTypes(this_()),
698 SubstTemplateTemplateParmPacks(this_()),
699 GlobalNestedNameSpecifier(0),
700 Int128Decl(0), UInt128Decl(0),
Meador Ingec5613b22012-06-16 03:34:49 +0000701 BuiltinVaListDecl(0),
Douglas Gregora6ea10e2012-01-17 18:09:05 +0000702 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanian96171302012-08-30 18:49:41 +0000703 BOOLDecl(0),
Douglas Gregore97179c2011-09-08 01:46:34 +0000704 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000705 FILEDecl(0),
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +0000706 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
707 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
708 cudaConfigureCallDecl(0),
Douglas Gregore6649772011-12-03 00:30:27 +0000709 NullTypeSourceInfo(QualType()),
710 FirstLocalImport(), LastLocalImport(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000711 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor30c42402011-09-27 22:38:19 +0000712 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000713 Idents(idents), Selectors(sels),
714 BuiltinInfo(builtins),
715 DeclarationNames(*this),
Douglas Gregor30c42402011-09-27 22:38:19 +0000716 ExternalSource(0), Listener(0),
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000717 Comments(SM), CommentsLoaded(false),
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +0000718 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
Rafael Espindola42b78612013-05-29 19:51:12 +0000719 LastSDM(0, 0)
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000720{
Mike Stump1eb44332009-09-09 15:08:12 +0000721 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000722 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000723
724 if (!DelayInitialization) {
725 assert(t && "No target supplied for ASTContext initialization");
726 InitBuiltinTypes(*t);
727 }
Daniel Dunbare91593e2008-08-11 04:54:23 +0000728}
729
Reid Spencer5f016e22007-07-11 17:01:13 +0000730ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000731 // Release the DenseMaps associated with DeclContext objects.
732 // FIXME: Is this the ideal solution?
733 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000734
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000735 // Call all of the deallocation functions.
736 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
737 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000738
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000739 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000740 // because they can contain DenseMaps.
741 for (llvm::DenseMap<const ObjCContainerDecl*,
742 const ASTRecordLayout*>::iterator
743 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
744 // Increment in loop to prevent using deallocated memory.
745 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
746 R->Destroy(*this);
747
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000748 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
749 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
750 // Increment in loop to prevent using deallocated memory.
751 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
752 R->Destroy(*this);
753 }
Douglas Gregor63200642010-08-30 16:49:28 +0000754
755 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
756 AEnd = DeclAttrs.end();
757 A != AEnd; ++A)
758 A->second->~AttrVec();
759}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000760
Douglas Gregor00545312010-05-23 18:26:36 +0000761void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
762 Deallocations.push_back(std::make_pair(Callback, Data));
763}
764
Mike Stump1eb44332009-09-09 15:08:12 +0000765void
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000766ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000767 ExternalSource.reset(Source.take());
768}
769
Reid Spencer5f016e22007-07-11 17:01:13 +0000770void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000771 llvm::errs() << "\n*** AST Context Stats:\n";
772 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000773
Douglas Gregordbe833d2009-05-26 14:40:08 +0000774 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000775#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000776#define ABSTRACT_TYPE(Name, Parent)
777#include "clang/AST/TypeNodes.def"
778 0 // Extra
779 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000780
Reid Spencer5f016e22007-07-11 17:01:13 +0000781 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
782 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000783 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000784 }
785
Douglas Gregordbe833d2009-05-26 14:40:08 +0000786 unsigned Idx = 0;
787 unsigned TotalBytes = 0;
788#define TYPE(Name, Parent) \
789 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000790 llvm::errs() << " " << counts[Idx] << " " << #Name \
791 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000792 TotalBytes += counts[Idx] * sizeof(Name##Type); \
793 ++Idx;
794#define ABSTRACT_TYPE(Name, Parent)
795#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000796
Chandler Carruthcd92a652011-07-04 05:32:14 +0000797 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
798
Douglas Gregor4923aa22010-07-02 20:37:36 +0000799 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000800 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
801 << NumImplicitDefaultConstructors
802 << " implicit default constructors created\n";
803 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
804 << NumImplicitCopyConstructors
805 << " implicit copy constructors created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000806 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000807 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
808 << NumImplicitMoveConstructors
809 << " implicit move constructors created\n";
810 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
811 << NumImplicitCopyAssignmentOperators
812 << " implicit copy assignment operators created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000813 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000814 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
815 << NumImplicitMoveAssignmentOperators
816 << " implicit move assignment operators created\n";
817 llvm::errs() << NumImplicitDestructorsDeclared << "/"
818 << NumImplicitDestructors
819 << " implicit destructors created\n";
820
Douglas Gregor2cf26342009-04-09 22:27:44 +0000821 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000822 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000823 ExternalSource->PrintStats();
824 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000825
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000826 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000827}
828
Douglas Gregor772eeae2011-08-12 06:49:56 +0000829TypedefDecl *ASTContext::getInt128Decl() const {
830 if (!Int128Decl) {
831 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
832 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
833 getTranslationUnitDecl(),
834 SourceLocation(),
835 SourceLocation(),
836 &Idents.get("__int128_t"),
837 TInfo);
838 }
839
840 return Int128Decl;
841}
842
843TypedefDecl *ASTContext::getUInt128Decl() const {
844 if (!UInt128Decl) {
845 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
846 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
847 getTranslationUnitDecl(),
848 SourceLocation(),
849 SourceLocation(),
850 &Idents.get("__uint128_t"),
851 TInfo);
852 }
853
854 return UInt128Decl;
855}
Reid Spencer5f016e22007-07-11 17:01:13 +0000856
John McCalle27ec8a2009-10-23 23:03:21 +0000857void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000858 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000859 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000860 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000861}
862
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000863void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
864 assert((!this->Target || this->Target == &Target) &&
865 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000866 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000867
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000868 this->Target = &Target;
869
870 ABI.reset(createCXXABI(Target));
871 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
872
Reid Spencer5f016e22007-07-11 17:01:13 +0000873 // C99 6.2.5p19.
874 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000875
Reid Spencer5f016e22007-07-11 17:01:13 +0000876 // C99 6.2.5p2.
877 InitBuiltinType(BoolTy, BuiltinType::Bool);
878 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000879 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000880 InitBuiltinType(CharTy, BuiltinType::Char_S);
881 else
882 InitBuiltinType(CharTy, BuiltinType::Char_U);
883 // C99 6.2.5p4.
884 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
885 InitBuiltinType(ShortTy, BuiltinType::Short);
886 InitBuiltinType(IntTy, BuiltinType::Int);
887 InitBuiltinType(LongTy, BuiltinType::Long);
888 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000889
Reid Spencer5f016e22007-07-11 17:01:13 +0000890 // C99 6.2.5p6.
891 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
892 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
893 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
894 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
895 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000896
Reid Spencer5f016e22007-07-11 17:01:13 +0000897 // C99 6.2.5p10.
898 InitBuiltinType(FloatTy, BuiltinType::Float);
899 InitBuiltinType(DoubleTy, BuiltinType::Double);
900 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000901
Chris Lattner2df9ced2009-04-30 02:43:43 +0000902 // GNU extension, 128-bit integers.
903 InitBuiltinType(Int128Ty, BuiltinType::Int128);
904 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
905
Hans Wennborg15f92ba2013-05-10 10:08:40 +0000906 // C++ 3.9.1p5
907 if (TargetInfo::isTypeSigned(Target.getWCharType()))
908 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
909 else // -fshort-wchar makes wchar_t be unsigned.
910 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
911 if (LangOpts.CPlusPlus && LangOpts.WChar)
912 WideCharTy = WCharTy;
913 else {
914 // C99 (or C++ using -fno-wchar).
915 WideCharTy = getFromTargetType(Target.getWCharType());
916 }
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000917
James Molloy392da482012-05-04 10:55:22 +0000918 WIntTy = getFromTargetType(Target.getWIntType());
919
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000920 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
921 InitBuiltinType(Char16Ty, BuiltinType::Char16);
922 else // C99
923 Char16Ty = getFromTargetType(Target.getChar16Type());
924
925 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
926 InitBuiltinType(Char32Ty, BuiltinType::Char32);
927 else // C99
928 Char32Ty = getFromTargetType(Target.getChar32Type());
929
Douglas Gregor898574e2008-12-05 23:32:09 +0000930 // Placeholder type for type-dependent expressions whose type is
931 // completely unknown. No code should ever check a type against
932 // DependentTy and users should never see it; however, it is here to
933 // help diagnose failures to properly check for type-dependent
934 // expressions.
935 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000936
John McCall2a984ca2010-10-12 00:20:44 +0000937 // Placeholder type for functions.
938 InitBuiltinType(OverloadTy, BuiltinType::Overload);
939
John McCall864c0412011-04-26 20:42:42 +0000940 // Placeholder type for bound members.
941 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
942
John McCall3c3b7f92011-10-25 17:37:35 +0000943 // Placeholder type for pseudo-objects.
944 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
945
John McCall1de4d4e2011-04-07 08:22:57 +0000946 // "any" type; useful for debugger-like clients.
947 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
948
John McCall0ddaeb92011-10-17 18:09:15 +0000949 // Placeholder type for unbridged ARC casts.
950 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
951
Eli Friedmana6c66ce2012-08-31 00:14:07 +0000952 // Placeholder type for builtin functions.
953 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
954
Reid Spencer5f016e22007-07-11 17:01:13 +0000955 // C99 6.2.5p11.
956 FloatComplexTy = getComplexType(FloatTy);
957 DoubleComplexTy = getComplexType(DoubleTy);
958 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000959
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000960 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000961 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
962 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000963 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeib13621d2012-12-18 14:38:23 +0000964
965 if (LangOpts.OpenCL) {
966 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
967 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
968 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
969 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
970 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
971 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000972
Guy Benyei21f18c42013-02-07 10:55:47 +0000973 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000974 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeib13621d2012-12-18 14:38:23 +0000975 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000976
977 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian93a49942012-04-16 21:03:30 +0000978 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
979 SignedCharTy : BoolTy);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000980
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000981 ObjCConstantStringType = QualType();
Fariborz Jahanianf7992132013-01-04 18:45:40 +0000982
983 ObjCSuperType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000984
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000985 // void * type
986 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000987
988 // nullptr type (C++0x 2.14.7)
989 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000990
991 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
992 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingefb40e3f2012-07-01 15:57:25 +0000993
994 // Builtin type used to help define __builtin_va_list.
995 VaListTagTy = QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000996}
997
David Blaikied6471f72011-09-25 23:23:43 +0000998DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000999 return SourceMgr.getDiagnostics();
1000}
1001
Douglas Gregor63200642010-08-30 16:49:28 +00001002AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1003 AttrVec *&Result = DeclAttrs[D];
1004 if (!Result) {
1005 void *Mem = Allocate(sizeof(AttrVec));
1006 Result = new (Mem) AttrVec;
1007 }
1008
1009 return *Result;
1010}
1011
1012/// \brief Erase the attributes corresponding to the given declaration.
1013void ASTContext::eraseDeclAttrs(const Decl *D) {
1014 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1015 if (Pos != DeclAttrs.end()) {
1016 Pos->second->~AttrVec();
1017 DeclAttrs.erase(Pos);
1018 }
1019}
1020
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001021MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +00001022ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001023 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +00001024 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +00001025 = InstantiatedFromStaticDataMember.find(Var);
1026 if (Pos == InstantiatedFromStaticDataMember.end())
1027 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001028
Douglas Gregor7caa6822009-07-24 20:34:43 +00001029 return Pos->second;
1030}
1031
Mike Stump1eb44332009-09-09 15:08:12 +00001032void
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001033ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +00001034 TemplateSpecializationKind TSK,
1035 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001036 assert(Inst->isStaticDataMember() && "Not a static data member");
1037 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1038 assert(!InstantiatedFromStaticDataMember[Inst] &&
1039 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001040 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +00001041 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +00001042}
1043
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001044FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1045 const FunctionDecl *FD){
1046 assert(FD && "Specialization is 0");
1047 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +00001048 = ClassScopeSpecializationPattern.find(FD);
1049 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001050 return 0;
1051
1052 return Pos->second;
1053}
1054
1055void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1056 FunctionDecl *Pattern) {
1057 assert(FD && "Specialization is 0");
1058 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +00001059 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001060}
1061
John McCall7ba107a2009-11-18 02:36:19 +00001062NamedDecl *
John McCalled976492009-12-04 22:46:56 +00001063ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +00001064 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +00001065 = InstantiatedFromUsingDecl.find(UUD);
1066 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +00001067 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001068
Anders Carlsson0d8df782009-08-29 19:37:28 +00001069 return Pos->second;
1070}
1071
1072void
John McCalled976492009-12-04 22:46:56 +00001073ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1074 assert((isa<UsingDecl>(Pattern) ||
1075 isa<UnresolvedUsingValueDecl>(Pattern) ||
1076 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1077 "pattern decl is not a using decl");
1078 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1079 InstantiatedFromUsingDecl[Inst] = Pattern;
1080}
1081
1082UsingShadowDecl *
1083ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1084 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1085 = InstantiatedFromUsingShadowDecl.find(Inst);
1086 if (Pos == InstantiatedFromUsingShadowDecl.end())
1087 return 0;
1088
1089 return Pos->second;
1090}
1091
1092void
1093ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1094 UsingShadowDecl *Pattern) {
1095 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1096 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00001097}
1098
Anders Carlssond8b285f2009-09-01 04:26:58 +00001099FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1100 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1101 = InstantiatedFromUnnamedFieldDecl.find(Field);
1102 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1103 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001104
Anders Carlssond8b285f2009-09-01 04:26:58 +00001105 return Pos->second;
1106}
1107
1108void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1109 FieldDecl *Tmpl) {
1110 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1111 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1112 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1113 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +00001114
Anders Carlssond8b285f2009-09-01 04:26:58 +00001115 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1116}
1117
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +00001118bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
1119 const FieldDecl *LastFD) const {
1120 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001121 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +00001122}
1123
Fariborz Jahanian340fa242011-05-02 17:20:56 +00001124bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
1125 const FieldDecl *LastFD) const {
1126 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001127 FD->getBitWidthValue(*this) == 0 &&
1128 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +00001129}
1130
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001131bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
1132 const FieldDecl *LastFD) const {
1133 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001134 FD->getBitWidthValue(*this) &&
1135 LastFD->getBitWidthValue(*this));
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001136}
1137
Chad Rosierdd7fddb2011-08-04 23:34:15 +00001138bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001139 const FieldDecl *LastFD) const {
1140 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001141 LastFD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001142}
1143
Chad Rosierdd7fddb2011-08-04 23:34:15 +00001144bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001145 const FieldDecl *LastFD) const {
1146 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001147 FD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001148}
1149
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001150ASTContext::overridden_cxx_method_iterator
1151ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1152 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001153 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001154 if (Pos == OverriddenMethods.end())
1155 return 0;
1156
1157 return Pos->second.begin();
1158}
1159
1160ASTContext::overridden_cxx_method_iterator
1161ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1162 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001163 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001164 if (Pos == OverriddenMethods.end())
1165 return 0;
1166
1167 return Pos->second.end();
1168}
1169
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001170unsigned
1171ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1172 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001173 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001174 if (Pos == OverriddenMethods.end())
1175 return 0;
1176
1177 return Pos->second.size();
1178}
1179
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001180void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1181 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001182 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001183 OverriddenMethods[Method].push_back(Overridden);
1184}
1185
Dmitri Gribenko1e905da2012-11-03 14:24:57 +00001186void ASTContext::getOverriddenMethods(
1187 const NamedDecl *D,
1188 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001189 assert(D);
1190
1191 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis685d1042013-04-17 00:09:03 +00001192 Overridden.append(overridden_methods_begin(CXXMethod),
1193 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001194 return;
1195 }
1196
1197 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1198 if (!Method)
1199 return;
1200
Argyrios Kyrtzidis740ae672012-10-09 18:19:01 +00001201 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1202 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisbc0a2bb2012-10-09 20:08:43 +00001203 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001204}
1205
Douglas Gregore6649772011-12-03 00:30:27 +00001206void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1207 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1208 assert(!Import->isFromASTFile() && "Non-local import declaration");
1209 if (!FirstLocalImport) {
1210 FirstLocalImport = Import;
1211 LastLocalImport = Import;
1212 return;
1213 }
1214
1215 LastLocalImport->NextLocalImport = Import;
1216 LastLocalImport = Import;
1217}
1218
Chris Lattner464175b2007-07-18 17:52:12 +00001219//===----------------------------------------------------------------------===//
1220// Type Sizing and Analysis
1221//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +00001222
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001223/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1224/// scalar floating point type.
1225const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +00001226 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001227 assert(BT && "Not a floating point type!");
1228 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001229 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001230 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001231 case BuiltinType::Float: return Target->getFloatFormat();
1232 case BuiltinType::Double: return Target->getDoubleFormat();
1233 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001234 }
1235}
1236
Ken Dyck8b752f12010-01-27 17:10:57 +00001237/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +00001238/// specified decl. Note that bitfields do not have a valid alignment, so
1239/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +00001240/// If @p RefAsPointee, references are treated like their underlying type
1241/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +00001242CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001243 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +00001244
John McCall4081a5c2010-10-08 18:24:19 +00001245 bool UseAlignAttrOnly = false;
1246 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1247 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +00001248
John McCall4081a5c2010-10-08 18:24:19 +00001249 // __attribute__((aligned)) can increase or decrease alignment
1250 // *except* on a struct or struct member, where it only increases
1251 // alignment unless 'packed' is also specified.
1252 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +00001253 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +00001254 // ignore that possibility; Sema should diagnose it.
1255 if (isa<FieldDecl>(D)) {
1256 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1257 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1258 } else {
1259 UseAlignAttrOnly = true;
1260 }
1261 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +00001262 else if (isa<FieldDecl>(D))
1263 UseAlignAttrOnly =
1264 D->hasAttr<PackedAttr>() ||
1265 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +00001266
John McCallba4f5d52011-01-20 07:57:12 +00001267 // If we're using the align attribute only, just ignore everything
1268 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +00001269 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +00001270 // do nothing
1271
John McCall4081a5c2010-10-08 18:24:19 +00001272 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001273 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001274 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001275 if (RefAsPointee)
1276 T = RT->getPointeeType();
1277 else
1278 T = getPointerType(RT->getPointeeType());
1279 }
1280 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +00001281 // Adjust alignments of declarations with array type by the
1282 // large-array alignment on the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001283 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +00001284 const ArrayType *arrayType;
1285 if (MinWidth && (arrayType = getAsArrayType(T))) {
1286 if (isa<VariableArrayType>(arrayType))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001287 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall3b657512011-01-19 10:06:00 +00001288 else if (isa<ConstantArrayType>(arrayType) &&
1289 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001290 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +00001291
John McCall3b657512011-01-19 10:06:00 +00001292 // Walk through any array types while we're at it.
1293 T = getBaseElementType(arrayType);
1294 }
Chad Rosier9f1210c2011-07-26 07:03:04 +00001295 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigand6b203512013-05-06 16:23:57 +00001296 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1297 if (VD->hasGlobalStorage())
1298 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1299 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001300 }
John McCallba4f5d52011-01-20 07:57:12 +00001301
1302 // Fields can be subject to extra alignment constraints, like if
1303 // the field is packed, the struct is packed, or the struct has a
1304 // a max-field-alignment constraint (#pragma pack). So calculate
1305 // the actual alignment of the field within the struct, and then
1306 // (as we're expected to) constrain that by the alignment of the type.
1307 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1308 // So calculate the alignment of the field.
1309 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1310
1311 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +00001312 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +00001313
1314 // Use the GCD of that and the offset within the record.
1315 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1316 if (offset > 0) {
1317 // Alignment is always a power of 2, so the GCD will be a power of 2,
1318 // which means we get to do this crazy thing instead of Euclid's.
1319 uint64_t lowBitOfOffset = offset & (~offset + 1);
1320 if (lowBitOfOffset < fieldAlign)
1321 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1322 }
1323
1324 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +00001325 }
Chris Lattneraf707ab2009-01-24 21:53:27 +00001326 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001327
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001328 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001329}
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001330
John McCall929bbfb2012-08-21 04:10:00 +00001331// getTypeInfoDataSizeInChars - Return the size of a type, in
1332// chars. If the type is a record, its data size is returned. This is
1333// the size of the memcpy that's performed when assigning this type
1334// using a trivial copy/move assignment operator.
1335std::pair<CharUnits, CharUnits>
1336ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1337 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1338
1339 // In C++, objects can sometimes be allocated into the tail padding
1340 // of a base-class subobject. We decide whether that's possible
1341 // during class layout, so here we can just trust the layout results.
1342 if (getLangOpts().CPlusPlus) {
1343 if (const RecordType *RT = T->getAs<RecordType>()) {
1344 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1345 sizeAndAlign.first = layout.getDataSize();
1346 }
1347 }
1348
1349 return sizeAndAlign;
1350}
1351
Richard Trieu910f17e2013-05-14 21:59:17 +00001352/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1353/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1354std::pair<CharUnits, CharUnits>
1355static getConstantArrayInfoInChars(const ASTContext &Context,
1356 const ConstantArrayType *CAT) {
1357 std::pair<CharUnits, CharUnits> EltInfo =
1358 Context.getTypeInfoInChars(CAT->getElementType());
1359 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieu1069b732013-05-14 23:41:50 +00001360 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1361 (uint64_t)(-1)/Size) &&
Richard Trieu910f17e2013-05-14 21:59:17 +00001362 "Overflow in array type char size evaluation");
1363 uint64_t Width = EltInfo.first.getQuantity() * Size;
1364 unsigned Align = EltInfo.second.getQuantity();
1365 Width = llvm::RoundUpToAlignment(Width, Align);
1366 return std::make_pair(CharUnits::fromQuantity(Width),
1367 CharUnits::fromQuantity(Align));
1368}
1369
John McCallea1471e2010-05-20 01:18:31 +00001370std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001371ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001372 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1373 return getConstantArrayInfoInChars(*this, CAT);
John McCallea1471e2010-05-20 01:18:31 +00001374 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001375 return std::make_pair(toCharUnitsFromBits(Info.first),
1376 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +00001377}
1378
1379std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001380ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +00001381 return getTypeInfoInChars(T.getTypePtr());
1382}
1383
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001384std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1385 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1386 if (it != MemoizedTypeInfo.end())
1387 return it->second;
1388
1389 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1390 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1391 return Info;
1392}
1393
1394/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1395/// method does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +00001396///
1397/// FIXME: Pointers into different addr spaces could have different sizes and
1398/// alignment requirements: getPointerInfo should take an AddrSpace, this
1399/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001400std::pair<uint64_t, unsigned>
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001401ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +00001402 uint64_t Width=0;
1403 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +00001404 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001405#define TYPE(Class, Base)
1406#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +00001407#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +00001408#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1409#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +00001410 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +00001411
Chris Lattner692233e2007-07-13 22:27:08 +00001412 case Type::FunctionNoProto:
1413 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +00001414 // GCC extension: alignof(function) = 32 bits
1415 Width = 0;
1416 Align = 32;
1417 break;
1418
Douglas Gregor72564e72009-02-26 23:50:07 +00001419 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +00001420 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +00001421 Width = 0;
1422 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1423 break;
1424
Steve Narofffb22d962007-08-30 01:06:46 +00001425 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001426 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001427
Chris Lattner98be4942008-03-05 18:54:05 +00001428 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001429 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001430 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1431 "Overflow in array type bit size evaluation");
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001432 Width = EltInfo.first*Size;
Chris Lattner030d8842007-07-19 22:06:24 +00001433 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +00001434 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +00001435 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +00001436 }
Nate Begeman213541a2008-04-18 23:10:10 +00001437 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +00001438 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001439 const VectorType *VT = cast<VectorType>(T);
1440 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1441 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +00001442 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001443 // If the alignment is not a power of 2, round up to the next power of 2.
1444 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +00001445 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001446 Align = llvm::NextPowerOf2(Align);
1447 Width = llvm::RoundUpToAlignment(Width, Align);
1448 }
Chad Rosierf9e9af72012-07-13 23:57:43 +00001449 // Adjust the alignment based on the target max.
1450 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1451 if (TargetVectorAlign && TargetVectorAlign < Align)
1452 Align = TargetVectorAlign;
Chris Lattner030d8842007-07-19 22:06:24 +00001453 break;
1454 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001455
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001456 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +00001457 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001458 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001459 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +00001460 // GCC extension: alignof(void) = 8 bits.
1461 Width = 0;
1462 Align = 8;
1463 break;
1464
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001465 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001466 Width = Target->getBoolWidth();
1467 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001468 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001469 case BuiltinType::Char_S:
1470 case BuiltinType::Char_U:
1471 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001472 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001473 Width = Target->getCharWidth();
1474 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001475 break;
Chris Lattner3f59c972010-12-25 23:25:43 +00001476 case BuiltinType::WChar_S:
1477 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001478 Width = Target->getWCharWidth();
1479 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001480 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001481 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001482 Width = Target->getChar16Width();
1483 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001484 break;
1485 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001486 Width = Target->getChar32Width();
1487 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001488 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001489 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001490 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001491 Width = Target->getShortWidth();
1492 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001493 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001494 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001495 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001496 Width = Target->getIntWidth();
1497 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001498 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001499 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001500 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001501 Width = Target->getLongWidth();
1502 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001503 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001504 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001505 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001506 Width = Target->getLongLongWidth();
1507 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001508 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +00001509 case BuiltinType::Int128:
1510 case BuiltinType::UInt128:
1511 Width = 128;
1512 Align = 128; // int128_t is 128-bit aligned on all targets.
1513 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001514 case BuiltinType::Half:
1515 Width = Target->getHalfWidth();
1516 Align = Target->getHalfAlign();
1517 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001518 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001519 Width = Target->getFloatWidth();
1520 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001521 break;
1522 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001523 Width = Target->getDoubleWidth();
1524 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001525 break;
1526 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001527 Width = Target->getLongDoubleWidth();
1528 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001529 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001530 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001531 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1532 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +00001533 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001534 case BuiltinType::ObjCId:
1535 case BuiltinType::ObjCClass:
1536 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001537 Width = Target->getPointerWidth(0);
1538 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001539 break;
Guy Benyei21f18c42013-02-07 10:55:47 +00001540 case BuiltinType::OCLSampler:
1541 // Samplers are modeled as integers.
1542 Width = Target->getIntWidth();
1543 Align = Target->getIntAlign();
1544 break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00001545 case BuiltinType::OCLEvent:
Guy Benyeib13621d2012-12-18 14:38:23 +00001546 case BuiltinType::OCLImage1d:
1547 case BuiltinType::OCLImage1dArray:
1548 case BuiltinType::OCLImage1dBuffer:
1549 case BuiltinType::OCLImage2d:
1550 case BuiltinType::OCLImage2dArray:
1551 case BuiltinType::OCLImage3d:
1552 // Currently these types are pointers to opaque types.
1553 Width = Target->getPointerWidth(0);
1554 Align = Target->getPointerAlign(0);
1555 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001556 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +00001557 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001558 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001559 Width = Target->getPointerWidth(0);
1560 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001561 break;
Steve Naroff485eeff2008-09-24 15:05:44 +00001562 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001563 unsigned AS = getTargetAddressSpace(
1564 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001565 Width = Target->getPointerWidth(AS);
1566 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +00001567 break;
1568 }
Sebastian Redl5d484e82009-11-23 17:18:46 +00001569 case Type::LValueReference:
1570 case Type::RValueReference: {
1571 // alignof and sizeof should never enter this code path here, so we go
1572 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001573 unsigned AS = getTargetAddressSpace(
1574 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001575 Width = Target->getPointerWidth(AS);
1576 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +00001577 break;
1578 }
Chris Lattnerf72a4432008-03-08 08:34:58 +00001579 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001580 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001581 Width = Target->getPointerWidth(AS);
1582 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +00001583 break;
1584 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00001585 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +00001586 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Reid Kleckner84e9ab42013-03-28 20:02:56 +00001587 llvm::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001588 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001589 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001590 case Type::Complex: {
1591 // Complex types have the same alignment as their elements, but twice the
1592 // size.
Mike Stump1eb44332009-09-09 15:08:12 +00001593 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +00001594 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001595 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +00001596 Align = EltInfo.second;
1597 break;
1598 }
John McCallc12c5bb2010-05-15 11:32:37 +00001599 case Type::ObjCObject:
1600 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +00001601 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001602 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +00001603 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001604 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001605 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +00001606 break;
1607 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001608 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001609 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001610 const TagType *TT = cast<TagType>(T);
1611
1612 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001613 Width = 8;
1614 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001615 break;
1616 }
Mike Stump1eb44332009-09-09 15:08:12 +00001617
Daniel Dunbar1d751182008-11-08 05:48:37 +00001618 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001619 return getTypeInfo(ET->getDecl()->getIntegerType());
1620
Daniel Dunbar1d751182008-11-08 05:48:37 +00001621 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001622 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001623 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001624 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001625 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001626 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001627
Chris Lattner9fcfe922009-10-22 05:17:15 +00001628 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001629 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1630 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001631
Richard Smith34b41d92011-02-20 03:19:35 +00001632 case Type::Auto: {
1633 const AutoType *A = cast<AutoType>(T);
Richard Smithdc7a4f52013-04-30 13:56:41 +00001634 assert(!A->getDeducedType().isNull() &&
1635 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001636 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001637 }
1638
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001639 case Type::Paren:
1640 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1641
Douglas Gregor18857642009-04-30 17:32:17 +00001642 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001643 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001644 std::pair<uint64_t, unsigned> Info
1645 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001646 // If the typedef has an aligned attribute on it, it overrides any computed
1647 // alignment we have. This violates the GCC documentation (which says that
1648 // attribute(aligned) can only round up) but matches its implementation.
1649 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1650 Align = AttrAlign;
1651 else
1652 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001653 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001654 break;
Chris Lattner71763312008-04-06 22:05:18 +00001655 }
Douglas Gregor18857642009-04-30 17:32:17 +00001656
1657 case Type::TypeOfExpr:
1658 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1659 .getTypePtr());
1660
1661 case Type::TypeOf:
1662 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1663
Anders Carlsson395b4752009-06-24 19:06:50 +00001664 case Type::Decltype:
1665 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1666 .getTypePtr());
1667
Sean Huntca63c202011-05-24 22:41:36 +00001668 case Type::UnaryTransform:
1669 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1670
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001671 case Type::Elaborated:
1672 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001673
John McCall9d156a72011-01-06 01:58:22 +00001674 case Type::Attributed:
1675 return getTypeInfo(
1676 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1677
Richard Smith3e4c6c42011-05-05 21:57:07 +00001678 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00001679 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +00001680 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +00001681 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1682 // A type alias template specialization may refer to a typedef with the
1683 // aligned attribute on it.
1684 if (TST->isTypeAlias())
1685 return getTypeInfo(TST->getAliasedType().getTypePtr());
1686 else
1687 return getTypeInfo(getCanonicalType(T));
1688 }
1689
Eli Friedmanb001de72011-10-06 23:00:33 +00001690 case Type::Atomic: {
John McCall9eda3ab2013-03-07 21:37:17 +00001691 // Start with the base type information.
Eli Friedman2be46072011-10-14 20:59:01 +00001692 std::pair<uint64_t, unsigned> Info
1693 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1694 Width = Info.first;
1695 Align = Info.second;
John McCall9eda3ab2013-03-07 21:37:17 +00001696
1697 // If the size of the type doesn't exceed the platform's max
1698 // atomic promotion width, make the size and alignment more
1699 // favorable to atomic operations:
1700 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1701 // Round the size up to a power of 2.
1702 if (!llvm::isPowerOf2_64(Width))
1703 Width = llvm::NextPowerOf2(Width);
1704
1705 // Set the alignment equal to the size.
Eli Friedman2be46072011-10-14 20:59:01 +00001706 Align = static_cast<unsigned>(Width);
1707 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001708 }
1709
Douglas Gregor18857642009-04-30 17:32:17 +00001710 }
Mike Stump1eb44332009-09-09 15:08:12 +00001711
Eli Friedman2be46072011-10-14 20:59:01 +00001712 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001713 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001714}
1715
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001716/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1717CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1718 return CharUnits::fromQuantity(BitSize / getCharWidth());
1719}
1720
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001721/// toBits - Convert a size in characters to a size in characters.
1722int64_t ASTContext::toBits(CharUnits CharSize) const {
1723 return CharSize.getQuantity() * getCharWidth();
1724}
1725
Ken Dyckbdc601b2009-12-22 14:23:30 +00001726/// getTypeSizeInChars - Return the size of the specified type, in characters.
1727/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001728CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001729 return getTypeInfoInChars(T).first;
Ken Dyckbdc601b2009-12-22 14:23:30 +00001730}
Jay Foad4ba2a172011-01-12 09:06:06 +00001731CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001732 return getTypeInfoInChars(T).first;
Ken Dyckbdc601b2009-12-22 14:23:30 +00001733}
1734
Ken Dyck16e20cc2010-01-26 17:25:18 +00001735/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001736/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001737CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001738 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001739}
Jay Foad4ba2a172011-01-12 09:06:06 +00001740CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001741 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001742}
1743
Chris Lattner34ebde42009-01-27 18:08:34 +00001744/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1745/// type for the current target in bits. This can be different than the ABI
1746/// alignment in cases where it is beneficial for performance to overalign
1747/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001748unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001749 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001750
1751 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001752 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001753 T = CT->getElementType().getTypePtr();
1754 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosiercde7a1d2012-03-21 20:20:47 +00001755 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1756 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman1eed6022009-05-25 21:27:19 +00001757 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1758
Chris Lattner34ebde42009-01-27 18:08:34 +00001759 return ABIAlign;
1760}
1761
Ulrich Weigand6b203512013-05-06 16:23:57 +00001762/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1763/// to a global variable of the specified type.
1764unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1765 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1766}
1767
1768/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1769/// should be given to a global variable of the specified type.
1770CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1771 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1772}
1773
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001774/// DeepCollectObjCIvars -
1775/// This routine first collects all declared, but not synthesized, ivars in
1776/// super class and then collects all ivars, including those synthesized for
1777/// current class. This routine is used for implementation of current class
1778/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001779///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001780void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1781 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001782 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001783 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1784 DeepCollectObjCIvars(SuperClass, false, Ivars);
1785 if (!leafClass) {
1786 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1787 E = OI->ivar_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001788 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001789 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001790 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001791 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001792 Iv= Iv->getNextIvar())
1793 Ivars.push_back(Iv);
1794 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001795}
1796
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001797/// CollectInheritedProtocols - Collect all protocols in current class and
1798/// those inherited by it.
1799void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001800 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001801 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001802 // We can use protocol_iterator here instead of
1803 // all_referenced_protocol_iterator since we are walking all categories.
1804 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1805 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001806 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001807 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001808 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001809 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001810 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001811 CollectInheritedProtocols(*P, Protocols);
1812 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001813 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001814
1815 // Categories of this Interface.
Douglas Gregord3297242013-01-16 23:00:23 +00001816 for (ObjCInterfaceDecl::visible_categories_iterator
1817 Cat = OI->visible_categories_begin(),
1818 CatEnd = OI->visible_categories_end();
1819 Cat != CatEnd; ++Cat) {
1820 CollectInheritedProtocols(*Cat, Protocols);
1821 }
1822
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001823 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1824 while (SD) {
1825 CollectInheritedProtocols(SD, Protocols);
1826 SD = SD->getSuperClass();
1827 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001828 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001829 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001830 PE = OC->protocol_end(); P != PE; ++P) {
1831 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001832 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001833 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1834 PE = Proto->protocol_end(); P != PE; ++P)
1835 CollectInheritedProtocols(*P, Protocols);
1836 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001837 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001838 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1839 PE = OP->protocol_end(); P != PE; ++P) {
1840 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001841 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001842 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1843 PE = Proto->protocol_end(); P != PE; ++P)
1844 CollectInheritedProtocols(*P, Protocols);
1845 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001846 }
1847}
1848
Jay Foad4ba2a172011-01-12 09:06:06 +00001849unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001850 unsigned count = 0;
1851 // Count ivars declared in class extension.
Douglas Gregord3297242013-01-16 23:00:23 +00001852 for (ObjCInterfaceDecl::known_extensions_iterator
1853 Ext = OI->known_extensions_begin(),
1854 ExtEnd = OI->known_extensions_end();
1855 Ext != ExtEnd; ++Ext) {
1856 count += Ext->ivar_size();
1857 }
1858
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001859 // Count ivar defined in this class's implementation. This
1860 // includes synthesized ivars.
1861 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001862 count += ImplDecl->ivar_size();
1863
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001864 return count;
1865}
1866
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +00001867bool ASTContext::isSentinelNullExpr(const Expr *E) {
1868 if (!E)
1869 return false;
1870
1871 // nullptr_t is always treated as null.
1872 if (E->getType()->isNullPtrType()) return true;
1873
1874 if (E->getType()->isAnyPointerType() &&
1875 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1876 Expr::NPC_ValueDependentIsNull))
1877 return true;
1878
1879 // Unfortunately, __null has type 'int'.
1880 if (isa<GNUNullExpr>(E)) return true;
1881
1882 return false;
1883}
1884
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001885/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1886ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1887 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1888 I = ObjCImpls.find(D);
1889 if (I != ObjCImpls.end())
1890 return cast<ObjCImplementationDecl>(I->second);
1891 return 0;
1892}
1893/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1894ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1895 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1896 I = ObjCImpls.find(D);
1897 if (I != ObjCImpls.end())
1898 return cast<ObjCCategoryImplDecl>(I->second);
1899 return 0;
1900}
1901
1902/// \brief Set the implementation of ObjCInterfaceDecl.
1903void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1904 ObjCImplementationDecl *ImplD) {
1905 assert(IFaceD && ImplD && "Passed null params");
1906 ObjCImpls[IFaceD] = ImplD;
1907}
1908/// \brief Set the implementation of ObjCCategoryDecl.
1909void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1910 ObjCCategoryImplDecl *ImplD) {
1911 assert(CatD && ImplD && "Passed null params");
1912 ObjCImpls[CatD] = ImplD;
1913}
1914
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001915const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1916 const NamedDecl *ND) const {
1917 if (const ObjCInterfaceDecl *ID =
1918 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001919 return ID;
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001920 if (const ObjCCategoryDecl *CD =
1921 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001922 return CD->getClassInterface();
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001923 if (const ObjCImplDecl *IMD =
1924 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001925 return IMD->getClassInterface();
1926
1927 return 0;
1928}
1929
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001930/// \brief Get the copy initialization expression of VarDecl,or NULL if
1931/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001932Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001933 assert(VD && "Passed null params");
1934 assert(VD->hasAttr<BlocksAttr>() &&
1935 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001936 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001937 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001938 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1939}
1940
1941/// \brief Set the copy inialization expression of a block var decl.
1942void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1943 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001944 assert(VD->hasAttr<BlocksAttr>() &&
1945 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001946 BlockVarCopyInits[VD] = Init;
1947}
1948
John McCalla93c9342009-12-07 02:54:59 +00001949TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001950 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001951 if (!DataSize)
1952 DataSize = TypeLoc::getFullDataSizeForType(T);
1953 else
1954 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001955 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001956
John McCalla93c9342009-12-07 02:54:59 +00001957 TypeSourceInfo *TInfo =
1958 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1959 new (TInfo) TypeSourceInfo(T);
1960 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001961}
1962
John McCalla93c9342009-12-07 02:54:59 +00001963TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001964 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001965 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001966 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001967 return DI;
1968}
1969
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001970const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001971ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001972 return getObjCLayout(D, 0);
1973}
1974
1975const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001976ASTContext::getASTObjCImplementationLayout(
1977 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001978 return getObjCLayout(D->getClassInterface(), D);
1979}
1980
Chris Lattnera7674d82007-07-13 22:13:22 +00001981//===----------------------------------------------------------------------===//
1982// Type creation/memoization methods
1983//===----------------------------------------------------------------------===//
1984
Jay Foad4ba2a172011-01-12 09:06:06 +00001985QualType
John McCall3b657512011-01-19 10:06:00 +00001986ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1987 unsigned fastQuals = quals.getFastQualifiers();
1988 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001989
1990 // Check if we've already instantiated this type.
1991 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001992 ExtQuals::Profile(ID, baseType, quals);
1993 void *insertPos = 0;
1994 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1995 assert(eq->getQualifiers() == quals);
1996 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001997 }
1998
John McCall3b657512011-01-19 10:06:00 +00001999 // If the base type is not canonical, make the appropriate canonical type.
2000 QualType canon;
2001 if (!baseType->isCanonicalUnqualified()) {
2002 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall200fa532012-02-08 00:46:36 +00002003 canonSplit.Quals.addConsistentQualifiers(quals);
2004 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00002005
2006 // Re-find the insert position.
2007 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2008 }
2009
2010 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2011 ExtQualNodes.InsertNode(eq, insertPos);
2012 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00002013}
2014
Jay Foad4ba2a172011-01-12 09:06:06 +00002015QualType
2016ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002017 QualType CanT = getCanonicalType(T);
2018 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00002019 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00002020
John McCall0953e762009-09-24 19:53:00 +00002021 // If we are composing extended qualifiers together, merge together
2022 // into one ExtQuals node.
2023 QualifierCollector Quals;
2024 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002025
John McCall0953e762009-09-24 19:53:00 +00002026 // If this type already has an address space specified, it cannot get
2027 // another one.
2028 assert(!Quals.hasAddressSpace() &&
2029 "Type cannot be in multiple addr spaces!");
2030 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002031
John McCall0953e762009-09-24 19:53:00 +00002032 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00002033}
2034
Chris Lattnerb7d25532009-02-18 22:53:11 +00002035QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00002036 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002037 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00002038 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002039 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00002040
John McCall7f040a92010-12-24 02:08:15 +00002041 if (const PointerType *ptr = T->getAs<PointerType>()) {
2042 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00002043 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00002044 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2045 return getPointerType(ResultType);
2046 }
2047 }
Mike Stump1eb44332009-09-09 15:08:12 +00002048
John McCall0953e762009-09-24 19:53:00 +00002049 // If we are composing extended qualifiers together, merge together
2050 // into one ExtQuals node.
2051 QualifierCollector Quals;
2052 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002053
John McCall0953e762009-09-24 19:53:00 +00002054 // If this type already has an ObjCGC specified, it cannot get
2055 // another one.
2056 assert(!Quals.hasObjCGCAttr() &&
2057 "Type cannot have multiple ObjCGCs!");
2058 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00002059
John McCall0953e762009-09-24 19:53:00 +00002060 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002061}
Chris Lattnera7674d82007-07-13 22:13:22 +00002062
John McCalle6a365d2010-12-19 02:44:49 +00002063const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2064 FunctionType::ExtInfo Info) {
2065 if (T->getExtInfo() == Info)
2066 return T;
2067
2068 QualType Result;
2069 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2070 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
2071 } else {
2072 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2073 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2074 EPI.ExtInfo = Info;
Jordan Rosebea522f2013-03-08 21:51:21 +00002075 Result = getFunctionType(FPT->getResultType(),
2076 ArrayRef<QualType>(FPT->arg_type_begin(),
2077 FPT->getNumArgs()),
2078 EPI);
John McCalle6a365d2010-12-19 02:44:49 +00002079 }
2080
2081 return cast<FunctionType>(Result.getTypePtr());
2082}
2083
Richard Smith60e141e2013-05-04 07:00:32 +00002084void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2085 QualType ResultType) {
Richard Smith9dadfab2013-05-11 05:45:24 +00002086 FD = FD->getMostRecentDecl();
2087 while (true) {
Richard Smith60e141e2013-05-04 07:00:32 +00002088 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2089 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2090 FD->setType(getFunctionType(ResultType, FPT->getArgTypes(), EPI));
Richard Smith9dadfab2013-05-11 05:45:24 +00002091 if (FunctionDecl *Next = FD->getPreviousDecl())
2092 FD = Next;
2093 else
2094 break;
Richard Smith60e141e2013-05-04 07:00:32 +00002095 }
Richard Smith9dadfab2013-05-11 05:45:24 +00002096 if (ASTMutationListener *L = getASTMutationListener())
2097 L->DeducedReturnType(FD, ResultType);
Richard Smith60e141e2013-05-04 07:00:32 +00002098}
2099
Reid Spencer5f016e22007-07-11 17:01:13 +00002100/// getComplexType - Return the uniqued reference to the type for a complex
2101/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002102QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002103 // Unique pointers, to guarantee there is only one pointer of a particular
2104 // structure.
2105 llvm::FoldingSetNodeID ID;
2106 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002107
Reid Spencer5f016e22007-07-11 17:01:13 +00002108 void *InsertPos = 0;
2109 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2110 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002111
Reid Spencer5f016e22007-07-11 17:01:13 +00002112 // If the pointee type isn't canonical, this won't be a canonical type either,
2113 // so fill in the canonical type field.
2114 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002115 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002116 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002117
Reid Spencer5f016e22007-07-11 17:01:13 +00002118 // Get the new insert position for the node we care about.
2119 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002120 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002121 }
John McCall6b304a02009-09-24 23:30:46 +00002122 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002123 Types.push_back(New);
2124 ComplexTypes.InsertNode(New, InsertPos);
2125 return QualType(New, 0);
2126}
2127
Reid Spencer5f016e22007-07-11 17:01:13 +00002128/// getPointerType - Return the uniqued reference to the type for a pointer to
2129/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002130QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002131 // Unique pointers, to guarantee there is only one pointer of a particular
2132 // structure.
2133 llvm::FoldingSetNodeID ID;
2134 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002135
Reid Spencer5f016e22007-07-11 17:01:13 +00002136 void *InsertPos = 0;
2137 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2138 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002139
Reid Spencer5f016e22007-07-11 17:01:13 +00002140 // If the pointee type isn't canonical, this won't be a canonical type either,
2141 // so fill in the canonical type field.
2142 QualType Canonical;
Bob Wilsonc90cc932013-03-15 17:12:43 +00002143 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002144 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002145
Bob Wilsonc90cc932013-03-15 17:12:43 +00002146 // Get the new insert position for the node we care about.
2147 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2148 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2149 }
John McCall6b304a02009-09-24 23:30:46 +00002150 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002151 Types.push_back(New);
2152 PointerTypes.InsertNode(New, InsertPos);
2153 return QualType(New, 0);
2154}
2155
Mike Stump1eb44332009-09-09 15:08:12 +00002156/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00002157/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00002158QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00002159 assert(T->isFunctionType() && "block of function types only");
2160 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00002161 // structure.
2162 llvm::FoldingSetNodeID ID;
2163 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002164
Steve Naroff5618bd42008-08-27 16:04:49 +00002165 void *InsertPos = 0;
2166 if (BlockPointerType *PT =
2167 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2168 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002169
2170 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00002171 // type either so fill in the canonical type field.
2172 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002173 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00002174 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002175
Steve Naroff5618bd42008-08-27 16:04:49 +00002176 // Get the new insert position for the node we care about.
2177 BlockPointerType *NewIP =
2178 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002179 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00002180 }
John McCall6b304a02009-09-24 23:30:46 +00002181 BlockPointerType *New
2182 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00002183 Types.push_back(New);
2184 BlockPointerTypes.InsertNode(New, InsertPos);
2185 return QualType(New, 0);
2186}
2187
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002188/// getLValueReferenceType - Return the uniqued reference to the type for an
2189/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002190QualType
2191ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00002192 assert(getCanonicalType(T) != OverloadTy &&
2193 "Unresolved overloaded function type");
2194
Reid Spencer5f016e22007-07-11 17:01:13 +00002195 // Unique pointers, to guarantee there is only one pointer of a particular
2196 // structure.
2197 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002198 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002199
2200 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002201 if (LValueReferenceType *RT =
2202 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002203 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002204
John McCall54e14c42009-10-22 22:37:11 +00002205 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2206
Reid Spencer5f016e22007-07-11 17:01:13 +00002207 // If the referencee type isn't canonical, this won't be a canonical type
2208 // either, so fill in the canonical type field.
2209 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002210 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2211 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2212 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002213
Reid Spencer5f016e22007-07-11 17:01:13 +00002214 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002215 LValueReferenceType *NewIP =
2216 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002217 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002218 }
2219
John McCall6b304a02009-09-24 23:30:46 +00002220 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00002221 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2222 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002223 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002224 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00002225
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002226 return QualType(New, 0);
2227}
2228
2229/// getRValueReferenceType - Return the uniqued reference to the type for an
2230/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002231QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002232 // Unique pointers, to guarantee there is only one pointer of a particular
2233 // structure.
2234 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002235 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002236
2237 void *InsertPos = 0;
2238 if (RValueReferenceType *RT =
2239 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2240 return QualType(RT, 0);
2241
John McCall54e14c42009-10-22 22:37:11 +00002242 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2243
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002244 // If the referencee type isn't canonical, this won't be a canonical type
2245 // either, so fill in the canonical type field.
2246 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002247 if (InnerRef || !T.isCanonical()) {
2248 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2249 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002250
2251 // Get the new insert position for the node we care about.
2252 RValueReferenceType *NewIP =
2253 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002254 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002255 }
2256
John McCall6b304a02009-09-24 23:30:46 +00002257 RValueReferenceType *New
2258 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002259 Types.push_back(New);
2260 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002261 return QualType(New, 0);
2262}
2263
Sebastian Redlf30208a2009-01-24 21:16:55 +00002264/// getMemberPointerType - Return the uniqued reference to the type for a
2265/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00002266QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002267 // Unique pointers, to guarantee there is only one pointer of a particular
2268 // structure.
2269 llvm::FoldingSetNodeID ID;
2270 MemberPointerType::Profile(ID, T, Cls);
2271
2272 void *InsertPos = 0;
2273 if (MemberPointerType *PT =
2274 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2275 return QualType(PT, 0);
2276
2277 // If the pointee or class type isn't canonical, this won't be a canonical
2278 // type either, so fill in the canonical type field.
2279 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00002280 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002281 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2282
2283 // Get the new insert position for the node we care about.
2284 MemberPointerType *NewIP =
2285 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002286 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00002287 }
John McCall6b304a02009-09-24 23:30:46 +00002288 MemberPointerType *New
2289 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002290 Types.push_back(New);
2291 MemberPointerTypes.InsertNode(New, InsertPos);
2292 return QualType(New, 0);
2293}
2294
Mike Stump1eb44332009-09-09 15:08:12 +00002295/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00002296/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002297QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00002298 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00002299 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002300 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00002301 assert((EltTy->isDependentType() ||
2302 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00002303 "Constant array of VLAs is illegal!");
2304
Chris Lattner38aeec72009-05-13 04:12:56 +00002305 // Convert the array size into a canonical width matching the pointer size for
2306 // the target.
2307 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002308 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002309 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00002310
Reid Spencer5f016e22007-07-11 17:01:13 +00002311 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002312 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00002313
Reid Spencer5f016e22007-07-11 17:01:13 +00002314 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002315 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002316 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002317 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002318
John McCall3b657512011-01-19 10:06:00 +00002319 // If the element type isn't canonical or has qualifiers, this won't
2320 // be a canonical type either, so fill in the canonical type field.
2321 QualType Canon;
2322 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2323 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002324 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002325 ASM, IndexTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002326 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00002327
Reid Spencer5f016e22007-07-11 17:01:13 +00002328 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00002329 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002330 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002331 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002332 }
Mike Stump1eb44332009-09-09 15:08:12 +00002333
John McCall6b304a02009-09-24 23:30:46 +00002334 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002335 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002336 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002337 Types.push_back(New);
2338 return QualType(New, 0);
2339}
2340
John McCallce889032011-01-18 08:40:38 +00002341/// getVariableArrayDecayedType - Turns the given type, which may be
2342/// variably-modified, into the corresponding type with all the known
2343/// sizes replaced with [*].
2344QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2345 // Vastly most common case.
2346 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002347
John McCallce889032011-01-18 08:40:38 +00002348 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002349
John McCallce889032011-01-18 08:40:38 +00002350 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00002351 const Type *ty = split.Ty;
John McCallce889032011-01-18 08:40:38 +00002352 switch (ty->getTypeClass()) {
2353#define TYPE(Class, Base)
2354#define ABSTRACT_TYPE(Class, Base)
2355#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2356#include "clang/AST/TypeNodes.def"
2357 llvm_unreachable("didn't desugar past all non-canonical types?");
2358
2359 // These types should never be variably-modified.
2360 case Type::Builtin:
2361 case Type::Complex:
2362 case Type::Vector:
2363 case Type::ExtVector:
2364 case Type::DependentSizedExtVector:
2365 case Type::ObjCObject:
2366 case Type::ObjCInterface:
2367 case Type::ObjCObjectPointer:
2368 case Type::Record:
2369 case Type::Enum:
2370 case Type::UnresolvedUsing:
2371 case Type::TypeOfExpr:
2372 case Type::TypeOf:
2373 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00002374 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00002375 case Type::DependentName:
2376 case Type::InjectedClassName:
2377 case Type::TemplateSpecialization:
2378 case Type::DependentTemplateSpecialization:
2379 case Type::TemplateTypeParm:
2380 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00002381 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00002382 case Type::PackExpansion:
2383 llvm_unreachable("type should never be variably-modified");
2384
2385 // These types can be variably-modified but should never need to
2386 // further decay.
2387 case Type::FunctionNoProto:
2388 case Type::FunctionProto:
2389 case Type::BlockPointer:
2390 case Type::MemberPointer:
2391 return type;
2392
2393 // These types can be variably-modified. All these modifications
2394 // preserve structure except as noted by comments.
2395 // TODO: if we ever care about optimizing VLAs, there are no-op
2396 // optimizations available here.
2397 case Type::Pointer:
2398 result = getPointerType(getVariableArrayDecayedType(
2399 cast<PointerType>(ty)->getPointeeType()));
2400 break;
2401
2402 case Type::LValueReference: {
2403 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2404 result = getLValueReferenceType(
2405 getVariableArrayDecayedType(lv->getPointeeType()),
2406 lv->isSpelledAsLValue());
2407 break;
2408 }
2409
2410 case Type::RValueReference: {
2411 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2412 result = getRValueReferenceType(
2413 getVariableArrayDecayedType(lv->getPointeeType()));
2414 break;
2415 }
2416
Eli Friedmanb001de72011-10-06 23:00:33 +00002417 case Type::Atomic: {
2418 const AtomicType *at = cast<AtomicType>(ty);
2419 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2420 break;
2421 }
2422
John McCallce889032011-01-18 08:40:38 +00002423 case Type::ConstantArray: {
2424 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2425 result = getConstantArrayType(
2426 getVariableArrayDecayedType(cat->getElementType()),
2427 cat->getSize(),
2428 cat->getSizeModifier(),
2429 cat->getIndexTypeCVRQualifiers());
2430 break;
2431 }
2432
2433 case Type::DependentSizedArray: {
2434 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2435 result = getDependentSizedArrayType(
2436 getVariableArrayDecayedType(dat->getElementType()),
2437 dat->getSizeExpr(),
2438 dat->getSizeModifier(),
2439 dat->getIndexTypeCVRQualifiers(),
2440 dat->getBracketsRange());
2441 break;
2442 }
2443
2444 // Turn incomplete types into [*] types.
2445 case Type::IncompleteArray: {
2446 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2447 result = getVariableArrayType(
2448 getVariableArrayDecayedType(iat->getElementType()),
2449 /*size*/ 0,
2450 ArrayType::Normal,
2451 iat->getIndexTypeCVRQualifiers(),
2452 SourceRange());
2453 break;
2454 }
2455
2456 // Turn VLA types into [*] types.
2457 case Type::VariableArray: {
2458 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2459 result = getVariableArrayType(
2460 getVariableArrayDecayedType(vat->getElementType()),
2461 /*size*/ 0,
2462 ArrayType::Star,
2463 vat->getIndexTypeCVRQualifiers(),
2464 vat->getBracketsRange());
2465 break;
2466 }
2467 }
2468
2469 // Apply the top-level qualifiers from the original.
John McCall200fa532012-02-08 00:46:36 +00002470 return getQualifiedType(result, split.Quals);
John McCallce889032011-01-18 08:40:38 +00002471}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002472
Steve Naroffbdbf7b02007-08-30 18:14:25 +00002473/// getVariableArrayType - Returns a non-unique reference to the type for a
2474/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002475QualType ASTContext::getVariableArrayType(QualType EltTy,
2476 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00002477 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002478 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00002479 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002480 // Since we don't unique expressions, it isn't possible to unique VLA's
2481 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00002482 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00002483
John McCall3b657512011-01-19 10:06:00 +00002484 // Be sure to pull qualifiers off the element type.
2485 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2486 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002487 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002488 IndexTypeQuals, Brackets);
John McCall200fa532012-02-08 00:46:36 +00002489 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor715e9c82010-05-23 16:10:32 +00002490 }
2491
John McCall6b304a02009-09-24 23:30:46 +00002492 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002493 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002494
2495 VariableArrayTypes.push_back(New);
2496 Types.push_back(New);
2497 return QualType(New, 0);
2498}
2499
Douglas Gregor898574e2008-12-05 23:32:09 +00002500/// getDependentSizedArrayType - Returns a non-unique reference to
2501/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00002502/// type.
John McCall3b657512011-01-19 10:06:00 +00002503QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2504 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00002505 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002506 unsigned elementTypeQuals,
2507 SourceRange brackets) const {
2508 assert((!numElements || numElements->isTypeDependent() ||
2509 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00002510 "Size must be type- or value-dependent!");
2511
John McCall3b657512011-01-19 10:06:00 +00002512 // Dependently-sized array types that do not have a specified number
2513 // of elements will have their sizes deduced from a dependent
2514 // initializer. We do no canonicalization here at all, which is okay
2515 // because they can't be used in most locations.
2516 if (!numElements) {
2517 DependentSizedArrayType *newType
2518 = new (*this, TypeAlignment)
2519 DependentSizedArrayType(*this, elementType, QualType(),
2520 numElements, ASM, elementTypeQuals,
2521 brackets);
2522 Types.push_back(newType);
2523 return QualType(newType, 0);
2524 }
2525
2526 // Otherwise, we actually build a new type every time, but we
2527 // also build a canonical type.
2528
2529 SplitQualType canonElementType = getCanonicalType(elementType).split();
2530
2531 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00002532 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002533 DependentSizedArrayType::Profile(ID, *this,
John McCall200fa532012-02-08 00:46:36 +00002534 QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002535 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002536
John McCall3b657512011-01-19 10:06:00 +00002537 // Look for an existing type with these properties.
2538 DependentSizedArrayType *canonTy =
2539 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002540
John McCall3b657512011-01-19 10:06:00 +00002541 // If we don't have one, build one.
2542 if (!canonTy) {
2543 canonTy = new (*this, TypeAlignment)
John McCall200fa532012-02-08 00:46:36 +00002544 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002545 QualType(), numElements, ASM, elementTypeQuals,
2546 brackets);
2547 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2548 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002549 }
2550
John McCall3b657512011-01-19 10:06:00 +00002551 // Apply qualifiers from the element type to the array.
2552 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall200fa532012-02-08 00:46:36 +00002553 canonElementType.Quals);
Mike Stump1eb44332009-09-09 15:08:12 +00002554
John McCall3b657512011-01-19 10:06:00 +00002555 // If we didn't need extra canonicalization for the element type,
2556 // then just use that as our result.
John McCall200fa532012-02-08 00:46:36 +00002557 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall3b657512011-01-19 10:06:00 +00002558 return canon;
2559
2560 // Otherwise, we need to build a type which follows the spelling
2561 // of the element type.
2562 DependentSizedArrayType *sugaredType
2563 = new (*this, TypeAlignment)
2564 DependentSizedArrayType(*this, elementType, canon, numElements,
2565 ASM, elementTypeQuals, brackets);
2566 Types.push_back(sugaredType);
2567 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00002568}
2569
John McCall3b657512011-01-19 10:06:00 +00002570QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00002571 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002572 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002573 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002574 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002575
John McCall3b657512011-01-19 10:06:00 +00002576 void *insertPos = 0;
2577 if (IncompleteArrayType *iat =
2578 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2579 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002580
2581 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00002582 // either, so fill in the canonical type field. We also have to pull
2583 // qualifiers off the element type.
2584 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00002585
John McCall3b657512011-01-19 10:06:00 +00002586 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2587 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall200fa532012-02-08 00:46:36 +00002588 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002589 ASM, elementTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002590 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002591
2592 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00002593 IncompleteArrayType *existing =
2594 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2595 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00002596 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00002597
John McCall3b657512011-01-19 10:06:00 +00002598 IncompleteArrayType *newType = new (*this, TypeAlignment)
2599 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002600
John McCall3b657512011-01-19 10:06:00 +00002601 IncompleteArrayTypes.InsertNode(newType, insertPos);
2602 Types.push_back(newType);
2603 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00002604}
2605
Steve Naroff73322922007-07-18 18:00:27 +00002606/// getVectorType - Return the unique reference to a vector type of
2607/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00002608QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00002609 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00002610 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00002611
Reid Spencer5f016e22007-07-11 17:01:13 +00002612 // Check if we've already instantiated a vector of this type.
2613 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00002614 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00002615
Reid Spencer5f016e22007-07-11 17:01:13 +00002616 void *InsertPos = 0;
2617 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2618 return QualType(VTP, 0);
2619
2620 // If the element type isn't canonical, this won't be a canonical type either,
2621 // so fill in the canonical type field.
2622 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00002623 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00002624 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002625
Reid Spencer5f016e22007-07-11 17:01:13 +00002626 // Get the new insert position for the node we care about.
2627 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002628 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002629 }
John McCall6b304a02009-09-24 23:30:46 +00002630 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00002631 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002632 VectorTypes.InsertNode(New, InsertPos);
2633 Types.push_back(New);
2634 return QualType(New, 0);
2635}
2636
Nate Begeman213541a2008-04-18 23:10:10 +00002637/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00002638/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002639QualType
2640ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00002641 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00002642
Steve Naroff73322922007-07-18 18:00:27 +00002643 // Check if we've already instantiated a vector of this type.
2644 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00002645 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002646 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00002647 void *InsertPos = 0;
2648 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2649 return QualType(VTP, 0);
2650
2651 // If the element type isn't canonical, this won't be a canonical type either,
2652 // so fill in the canonical type field.
2653 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002654 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002655 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00002656
Steve Naroff73322922007-07-18 18:00:27 +00002657 // Get the new insert position for the node we care about.
2658 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002659 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00002660 }
John McCall6b304a02009-09-24 23:30:46 +00002661 ExtVectorType *New = new (*this, TypeAlignment)
2662 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00002663 VectorTypes.InsertNode(New, InsertPos);
2664 Types.push_back(New);
2665 return QualType(New, 0);
2666}
2667
Jay Foad4ba2a172011-01-12 09:06:06 +00002668QualType
2669ASTContext::getDependentSizedExtVectorType(QualType vecType,
2670 Expr *SizeExpr,
2671 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002672 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002673 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002674 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002675
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002676 void *InsertPos = 0;
2677 DependentSizedExtVectorType *Canon
2678 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2679 DependentSizedExtVectorType *New;
2680 if (Canon) {
2681 // We already have a canonical version of this array type; use it as
2682 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002683 New = new (*this, TypeAlignment)
2684 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2685 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002686 } else {
2687 QualType CanonVecTy = getCanonicalType(vecType);
2688 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002689 New = new (*this, TypeAlignment)
2690 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2691 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002692
2693 DependentSizedExtVectorType *CanonCheck
2694 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2695 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2696 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002697 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2698 } else {
2699 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2700 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002701 New = new (*this, TypeAlignment)
2702 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002703 }
2704 }
Mike Stump1eb44332009-09-09 15:08:12 +00002705
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002706 Types.push_back(New);
2707 return QualType(New, 0);
2708}
2709
Douglas Gregor72564e72009-02-26 23:50:07 +00002710/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002711///
Jay Foad4ba2a172011-01-12 09:06:06 +00002712QualType
2713ASTContext::getFunctionNoProtoType(QualType ResultTy,
2714 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00002715 const CallingConv DefaultCC = Info.getCC();
2716 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2717 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00002718 // Unique functions, to guarantee there is only one function of a particular
2719 // structure.
2720 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002721 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002722
Reid Spencer5f016e22007-07-11 17:01:13 +00002723 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002724 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002725 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002726 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002727
Reid Spencer5f016e22007-07-11 17:01:13 +00002728 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00002729 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00002730 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00002731 Canonical =
2732 getFunctionNoProtoType(getCanonicalType(ResultTy),
2733 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00002734
Reid Spencer5f016e22007-07-11 17:01:13 +00002735 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002736 FunctionNoProtoType *NewIP =
2737 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002738 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002739 }
Mike Stump1eb44332009-09-09 15:08:12 +00002740
Roman Divackycfe9af22011-03-01 17:40:53 +00002741 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002742 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002743 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002744 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002745 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002746 return QualType(New, 0);
2747}
2748
Douglas Gregor02dd7982013-01-17 23:36:45 +00002749/// \brief Determine whether \p T is canonical as the result type of a function.
2750static bool isCanonicalResultType(QualType T) {
2751 return T.isCanonical() &&
2752 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2753 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2754}
2755
Reid Spencer5f016e22007-07-11 17:01:13 +00002756/// getFunctionType - Return a normal function type with a typed argument
2757/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002758QualType
Jordan Rosebea522f2013-03-08 21:51:21 +00002759ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad4ba2a172011-01-12 09:06:06 +00002760 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rosebea522f2013-03-08 21:51:21 +00002761 size_t NumArgs = ArgArray.size();
2762
Reid Spencer5f016e22007-07-11 17:01:13 +00002763 // Unique functions, to guarantee there is only one function of a particular
2764 // structure.
2765 llvm::FoldingSetNodeID ID;
Jordan Rosebea522f2013-03-08 21:51:21 +00002766 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2767 *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002768
2769 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002770 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002771 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002772 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002773
2774 // Determine whether the type being created is already canonical or not.
Richard Smitheefb3d52012-02-10 09:58:53 +00002775 bool isCanonical =
Douglas Gregor02dd7982013-01-17 23:36:45 +00002776 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smitheefb3d52012-02-10 09:58:53 +00002777 !EPI.HasTrailingReturn;
Reid Spencer5f016e22007-07-11 17:01:13 +00002778 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002779 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002780 isCanonical = false;
2781
Roman Divackycfe9af22011-03-01 17:40:53 +00002782 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2783 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2784 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002785
Reid Spencer5f016e22007-07-11 17:01:13 +00002786 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002787 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002788 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002789 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002790 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002791 CanonicalArgs.reserve(NumArgs);
2792 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002793 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002794
John McCalle23cf432010-12-14 08:05:40 +00002795 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +00002796 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002797 CanonicalEPI.ExceptionSpecType = EST_None;
2798 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002799 CanonicalEPI.ExtInfo
2800 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2801
Douglas Gregor02dd7982013-01-17 23:36:45 +00002802 // Result types do not have ARC lifetime qualifiers.
2803 QualType CanResultTy = getCanonicalType(ResultTy);
2804 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2805 Qualifiers Qs = CanResultTy.getQualifiers();
2806 Qs.removeObjCLifetime();
2807 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2808 }
2809
Jordan Rosebea522f2013-03-08 21:51:21 +00002810 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002811
Reid Spencer5f016e22007-07-11 17:01:13 +00002812 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002813 FunctionProtoType *NewIP =
2814 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002815 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002816 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002817
John McCallf85e1932011-06-15 23:02:42 +00002818 // FunctionProtoType objects are allocated with extra bytes after
2819 // them for three variable size arrays at the end:
2820 // - parameter types
2821 // - exception types
2822 // - consumed-arguments flags
2823 // Instead of the exception types, there could be a noexcept
Richard Smithb9d0b762012-07-27 04:22:15 +00002824 // expression, or information used to resolve the exception
2825 // specification.
John McCalle23cf432010-12-14 08:05:40 +00002826 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002827 NumArgs * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002828 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00002829 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002830 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002831 Size += sizeof(Expr*);
Richard Smithe6975e92012-04-17 00:58:00 +00002832 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smith13bffc52012-04-19 00:08:28 +00002833 Size += 2 * sizeof(FunctionDecl*);
Richard Smithb9d0b762012-07-27 04:22:15 +00002834 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2835 Size += sizeof(FunctionDecl*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002836 }
John McCallf85e1932011-06-15 23:02:42 +00002837 if (EPI.ConsumedArguments)
2838 Size += NumArgs * sizeof(bool);
2839
John McCalle23cf432010-12-14 08:05:40 +00002840 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002841 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2842 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Jordan Rosebea522f2013-03-08 21:51:21 +00002843 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002844 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002845 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002846 return QualType(FTP, 0);
2847}
2848
John McCall3cb0ebd2010-03-10 03:28:59 +00002849#ifndef NDEBUG
2850static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2851 if (!isa<CXXRecordDecl>(D)) return false;
2852 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2853 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2854 return true;
2855 if (RD->getDescribedClassTemplate() &&
2856 !isa<ClassTemplateSpecializationDecl>(RD))
2857 return true;
2858 return false;
2859}
2860#endif
2861
2862/// getInjectedClassNameType - Return the unique reference to the
2863/// injected class name type for the specified templated declaration.
2864QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002865 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002866 assert(NeedsInjectedClassNameType(Decl));
2867 if (Decl->TypeForDecl) {
2868 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregoref96ee02012-01-14 16:38:05 +00002869 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002870 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2871 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2872 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2873 } else {
John McCallf4c73712011-01-19 06:33:43 +00002874 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002875 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002876 Decl->TypeForDecl = newType;
2877 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002878 }
2879 return QualType(Decl->TypeForDecl, 0);
2880}
2881
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002882/// getTypeDeclType - Return the unique reference to the type for the
2883/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002884QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002885 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002886 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002887
Richard Smith162e1c12011-04-15 14:24:37 +00002888 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002889 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002890
John McCallbecb8d52010-03-10 06:48:02 +00002891 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2892 "Template type parameter types are always available.");
2893
John McCall19c85762010-02-16 03:57:14 +00002894 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002895 assert(!Record->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002896 "struct/union has previous declaration");
2897 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002898 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002899 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002900 assert(!Enum->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002901 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002902 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002903 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002904 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002905 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2906 Decl->TypeForDecl = newType;
2907 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002908 } else
John McCallbecb8d52010-03-10 06:48:02 +00002909 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002910
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002911 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002912}
2913
Reid Spencer5f016e22007-07-11 17:01:13 +00002914/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002915/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002916QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002917ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2918 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002919 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002920
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002921 if (Canonical.isNull())
2922 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002923 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002924 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002925 Decl->TypeForDecl = newType;
2926 Types.push_back(newType);
2927 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002928}
2929
Jay Foad4ba2a172011-01-12 09:06:06 +00002930QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002931 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2932
Douglas Gregoref96ee02012-01-14 16:38:05 +00002933 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002934 if (PrevDecl->TypeForDecl)
2935 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2936
John McCallf4c73712011-01-19 06:33:43 +00002937 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2938 Decl->TypeForDecl = newType;
2939 Types.push_back(newType);
2940 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002941}
2942
Jay Foad4ba2a172011-01-12 09:06:06 +00002943QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002944 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2945
Douglas Gregoref96ee02012-01-14 16:38:05 +00002946 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002947 if (PrevDecl->TypeForDecl)
2948 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2949
John McCallf4c73712011-01-19 06:33:43 +00002950 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2951 Decl->TypeForDecl = newType;
2952 Types.push_back(newType);
2953 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002954}
2955
John McCall9d156a72011-01-06 01:58:22 +00002956QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2957 QualType modifiedType,
2958 QualType equivalentType) {
2959 llvm::FoldingSetNodeID id;
2960 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2961
2962 void *insertPos = 0;
2963 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2964 if (type) return QualType(type, 0);
2965
2966 QualType canon = getCanonicalType(equivalentType);
2967 type = new (*this, TypeAlignment)
2968 AttributedType(canon, attrKind, modifiedType, equivalentType);
2969
2970 Types.push_back(type);
2971 AttributedTypes.InsertNode(type, insertPos);
2972
2973 return QualType(type, 0);
2974}
2975
2976
John McCall49a832b2009-10-18 09:09:24 +00002977/// \brief Retrieve a substitution-result type.
2978QualType
2979ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002980 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002981 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002982 && "replacement types must always be canonical");
2983
2984 llvm::FoldingSetNodeID ID;
2985 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2986 void *InsertPos = 0;
2987 SubstTemplateTypeParmType *SubstParm
2988 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2989
2990 if (!SubstParm) {
2991 SubstParm = new (*this, TypeAlignment)
2992 SubstTemplateTypeParmType(Parm, Replacement);
2993 Types.push_back(SubstParm);
2994 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2995 }
2996
2997 return QualType(SubstParm, 0);
2998}
2999
Douglas Gregorc3069d62011-01-14 02:55:32 +00003000/// \brief Retrieve a
3001QualType ASTContext::getSubstTemplateTypeParmPackType(
3002 const TemplateTypeParmType *Parm,
3003 const TemplateArgument &ArgPack) {
3004#ifndef NDEBUG
3005 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
3006 PEnd = ArgPack.pack_end();
3007 P != PEnd; ++P) {
3008 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3009 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
3010 }
3011#endif
3012
3013 llvm::FoldingSetNodeID ID;
3014 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3015 void *InsertPos = 0;
3016 if (SubstTemplateTypeParmPackType *SubstParm
3017 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3018 return QualType(SubstParm, 0);
3019
3020 QualType Canon;
3021 if (!Parm->isCanonicalUnqualified()) {
3022 Canon = getCanonicalType(QualType(Parm, 0));
3023 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3024 ArgPack);
3025 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3026 }
3027
3028 SubstTemplateTypeParmPackType *SubstParm
3029 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3030 ArgPack);
3031 Types.push_back(SubstParm);
3032 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3033 return QualType(SubstParm, 0);
3034}
3035
Douglas Gregorfab9d672009-02-05 23:33:38 +00003036/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00003037/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003038/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00003039QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003040 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003041 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00003042 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003043 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00003044 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003045 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00003046 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3047
3048 if (TypeParm)
3049 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003050
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003051 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003052 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003053 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003054
3055 TemplateTypeParmType *TypeCheck
3056 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3057 assert(!TypeCheck && "Template type parameter canonical type broken");
3058 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003059 } else
John McCall6b304a02009-09-24 23:30:46 +00003060 TypeParm = new (*this, TypeAlignment)
3061 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00003062
3063 Types.push_back(TypeParm);
3064 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3065
3066 return QualType(TypeParm, 0);
3067}
3068
John McCall3cb0ebd2010-03-10 03:28:59 +00003069TypeSourceInfo *
3070ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3071 SourceLocation NameLoc,
3072 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003073 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003074 assert(!Name.getAsDependentTemplateName() &&
3075 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00003076 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00003077
3078 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie39e6ab42013-02-18 22:06:02 +00003079 TemplateSpecializationTypeLoc TL =
3080 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara55d23c92012-02-06 14:41:24 +00003081 TL.setTemplateKeywordLoc(SourceLocation());
John McCall3cb0ebd2010-03-10 03:28:59 +00003082 TL.setTemplateNameLoc(NameLoc);
3083 TL.setLAngleLoc(Args.getLAngleLoc());
3084 TL.setRAngleLoc(Args.getRAngleLoc());
3085 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3086 TL.setArgLocInfo(i, Args[i].getLocInfo());
3087 return DI;
3088}
3089
Mike Stump1eb44332009-09-09 15:08:12 +00003090QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00003091ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00003092 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003093 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003094 assert(!Template.getAsDependentTemplateName() &&
3095 "No dependent template names here!");
3096
John McCalld5532b62009-11-23 01:53:49 +00003097 unsigned NumArgs = Args.size();
3098
Chris Lattner5f9e2722011-07-23 10:55:15 +00003099 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00003100 ArgVec.reserve(NumArgs);
3101 for (unsigned i = 0; i != NumArgs; ++i)
3102 ArgVec.push_back(Args[i].getArgument());
3103
John McCall31f17ec2010-04-27 00:57:59 +00003104 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003105 Underlying);
John McCall833ca992009-10-29 08:12:44 +00003106}
3107
Douglas Gregorb70126a2012-02-03 17:16:23 +00003108#ifndef NDEBUG
3109static bool hasAnyPackExpansions(const TemplateArgument *Args,
3110 unsigned NumArgs) {
3111 for (unsigned I = 0; I != NumArgs; ++I)
3112 if (Args[I].isPackExpansion())
3113 return true;
3114
3115 return true;
3116}
3117#endif
3118
John McCall833ca992009-10-29 08:12:44 +00003119QualType
3120ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003121 const TemplateArgument *Args,
3122 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003123 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003124 assert(!Template.getAsDependentTemplateName() &&
3125 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003126 // Look through qualified template names.
3127 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3128 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003129
Douglas Gregorb70126a2012-02-03 17:16:23 +00003130 bool IsTypeAlias =
Richard Smith3e4c6c42011-05-05 21:57:07 +00003131 Template.getAsTemplateDecl() &&
3132 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00003133 QualType CanonType;
3134 if (!Underlying.isNull())
3135 CanonType = getCanonicalType(Underlying);
3136 else {
Douglas Gregorb70126a2012-02-03 17:16:23 +00003137 // We can get here with an alias template when the specialization contains
3138 // a pack expansion that does not match up with a parameter pack.
3139 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3140 "Caller must compute aliased type");
3141 IsTypeAlias = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00003142 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3143 NumArgs);
3144 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00003145
Douglas Gregor1275ae02009-07-28 23:00:59 +00003146 // Allocate the (non-canonical) template specialization type, but don't
3147 // try to unique it: these types typically have location information that
3148 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00003149 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3150 sizeof(TemplateArgument) * NumArgs +
Douglas Gregorb70126a2012-02-03 17:16:23 +00003151 (IsTypeAlias? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00003152 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00003153 TemplateSpecializationType *Spec
Douglas Gregorb70126a2012-02-03 17:16:23 +00003154 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3155 IsTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00003156
Douglas Gregor55f6b142009-02-09 18:46:07 +00003157 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00003158 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00003159}
3160
Mike Stump1eb44332009-09-09 15:08:12 +00003161QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003162ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3163 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00003164 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003165 assert(!Template.getAsDependentTemplateName() &&
3166 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00003167
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003168 // Look through qualified template names.
3169 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3170 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003171
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003172 // Build the canonical template specialization type.
3173 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003174 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003175 CanonArgs.reserve(NumArgs);
3176 for (unsigned I = 0; I != NumArgs; ++I)
3177 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3178
3179 // Determine whether this canonical template specialization type already
3180 // exists.
3181 llvm::FoldingSetNodeID ID;
3182 TemplateSpecializationType::Profile(ID, CanonTemplate,
3183 CanonArgs.data(), NumArgs, *this);
3184
3185 void *InsertPos = 0;
3186 TemplateSpecializationType *Spec
3187 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3188
3189 if (!Spec) {
3190 // Allocate a new canonical template specialization type.
3191 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3192 sizeof(TemplateArgument) * NumArgs),
3193 TypeAlignment);
3194 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3195 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003196 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003197 Types.push_back(Spec);
3198 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3199 }
3200
3201 assert(Spec->isDependentType() &&
3202 "Non-dependent template-id type must have a canonical type");
3203 return QualType(Spec, 0);
3204}
3205
3206QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003207ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3208 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00003209 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00003210 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003211 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003212
3213 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003214 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003215 if (T)
3216 return QualType(T, 0);
3217
Douglas Gregor789b1f62010-02-04 18:10:26 +00003218 QualType Canon = NamedType;
3219 if (!Canon.isCanonical()) {
3220 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003221 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3222 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00003223 (void)CheckT;
3224 }
3225
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003226 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003227 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003228 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003229 return QualType(T, 0);
3230}
3231
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003232QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00003233ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003234 llvm::FoldingSetNodeID ID;
3235 ParenType::Profile(ID, InnerType);
3236
3237 void *InsertPos = 0;
3238 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3239 if (T)
3240 return QualType(T, 0);
3241
3242 QualType Canon = InnerType;
3243 if (!Canon.isCanonical()) {
3244 Canon = getCanonicalType(InnerType);
3245 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3246 assert(!CheckT && "Paren canonical type broken");
3247 (void)CheckT;
3248 }
3249
3250 T = new (*this) ParenType(InnerType, Canon);
3251 Types.push_back(T);
3252 ParenTypes.InsertNode(T, InsertPos);
3253 return QualType(T, 0);
3254}
3255
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003256QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3257 NestedNameSpecifier *NNS,
3258 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003259 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00003260 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3261
3262 if (Canon.isNull()) {
3263 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003264 ElaboratedTypeKeyword CanonKeyword = Keyword;
3265 if (Keyword == ETK_None)
3266 CanonKeyword = ETK_Typename;
3267
3268 if (CanonNNS != NNS || CanonKeyword != Keyword)
3269 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003270 }
3271
3272 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003273 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003274
3275 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00003276 DependentNameType *T
3277 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00003278 if (T)
3279 return QualType(T, 0);
3280
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003281 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00003282 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00003283 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003284 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00003285}
3286
Mike Stump1eb44332009-09-09 15:08:12 +00003287QualType
John McCall33500952010-06-11 00:33:02 +00003288ASTContext::getDependentTemplateSpecializationType(
3289 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003290 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00003291 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003292 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00003293 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00003294 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00003295 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3296 ArgCopy.push_back(Args[I].getArgument());
3297 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3298 ArgCopy.size(),
3299 ArgCopy.data());
3300}
3301
3302QualType
3303ASTContext::getDependentTemplateSpecializationType(
3304 ElaboratedTypeKeyword Keyword,
3305 NestedNameSpecifier *NNS,
3306 const IdentifierInfo *Name,
3307 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00003308 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003309 assert((!NNS || NNS->isDependent()) &&
3310 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00003311
Douglas Gregor789b1f62010-02-04 18:10:26 +00003312 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00003313 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3314 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003315
3316 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00003317 DependentTemplateSpecializationType *T
3318 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003319 if (T)
3320 return QualType(T, 0);
3321
John McCall33500952010-06-11 00:33:02 +00003322 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003323
John McCall33500952010-06-11 00:33:02 +00003324 ElaboratedTypeKeyword CanonKeyword = Keyword;
3325 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3326
3327 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003328 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00003329 for (unsigned I = 0; I != NumArgs; ++I) {
3330 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3331 if (!CanonArgs[I].structurallyEquals(Args[I]))
3332 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00003333 }
3334
John McCall33500952010-06-11 00:33:02 +00003335 QualType Canon;
3336 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3337 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3338 Name, NumArgs,
3339 CanonArgs.data());
3340
3341 // Find the insert position again.
3342 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3343 }
3344
3345 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3346 sizeof(TemplateArgument) * NumArgs),
3347 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00003348 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00003349 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00003350 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00003351 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003352 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00003353}
3354
Douglas Gregorcded4f62011-01-14 17:04:44 +00003355QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikiedc84cd52013-02-20 22:23:23 +00003356 Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00003357 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00003358 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003359
3360 assert(Pattern->containsUnexpandedParameterPack() &&
3361 "Pack expansions must expand one or more parameter packs");
3362 void *InsertPos = 0;
3363 PackExpansionType *T
3364 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3365 if (T)
3366 return QualType(T, 0);
3367
3368 QualType Canon;
3369 if (!Pattern.isCanonical()) {
Richard Smithd8672ef2012-07-16 00:20:35 +00003370 Canon = getCanonicalType(Pattern);
3371 // The canonical type might not contain an unexpanded parameter pack, if it
3372 // contains an alias template specialization which ignores one of its
3373 // parameters.
3374 if (Canon->containsUnexpandedParameterPack()) {
3375 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003376
Richard Smithd8672ef2012-07-16 00:20:35 +00003377 // Find the insert position again, in case we inserted an element into
3378 // PackExpansionTypes and invalidated our insert position.
3379 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3380 }
Douglas Gregor7536dd52010-12-20 02:24:11 +00003381 }
3382
Douglas Gregorcded4f62011-01-14 17:04:44 +00003383 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003384 Types.push_back(T);
3385 PackExpansionTypes.InsertNode(T, InsertPos);
3386 return QualType(T, 0);
3387}
3388
Chris Lattner88cb27a2008-04-07 04:56:42 +00003389/// CmpProtocolNames - Comparison predicate for sorting protocols
3390/// alphabetically.
3391static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3392 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003393 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00003394}
3395
John McCallc12c5bb2010-05-15 11:32:37 +00003396static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00003397 unsigned NumProtocols) {
3398 if (NumProtocols == 0) return true;
3399
Douglas Gregor61cc2962012-01-02 02:00:30 +00003400 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3401 return false;
3402
John McCall54e14c42009-10-22 22:37:11 +00003403 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregor61cc2962012-01-02 02:00:30 +00003404 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3405 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCall54e14c42009-10-22 22:37:11 +00003406 return false;
3407 return true;
3408}
3409
3410static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00003411 unsigned &NumProtocols) {
3412 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00003413
Chris Lattner88cb27a2008-04-07 04:56:42 +00003414 // Sort protocols, keyed by name.
3415 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3416
Douglas Gregor61cc2962012-01-02 02:00:30 +00003417 // Canonicalize.
3418 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3419 Protocols[I] = Protocols[I]->getCanonicalDecl();
3420
Chris Lattner88cb27a2008-04-07 04:56:42 +00003421 // Remove duplicates.
3422 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3423 NumProtocols = ProtocolsEnd-Protocols;
3424}
3425
John McCallc12c5bb2010-05-15 11:32:37 +00003426QualType ASTContext::getObjCObjectType(QualType BaseType,
3427 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00003428 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003429 // If the base type is an interface and there aren't any protocols
3430 // to add, then the interface type will do just fine.
3431 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3432 return BaseType;
3433
3434 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003435 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00003436 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003437 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00003438 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3439 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003440
John McCallc12c5bb2010-05-15 11:32:37 +00003441 // Build the canonical type, which has the canonical base type and
3442 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00003443 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00003444 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3445 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3446 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003447 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00003448 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003449 unsigned UniqueCount = NumProtocols;
3450
John McCall54e14c42009-10-22 22:37:11 +00003451 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00003452 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3453 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00003454 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00003455 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3456 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003457 }
3458
3459 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00003460 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3461 }
3462
3463 unsigned Size = sizeof(ObjCObjectTypeImpl);
3464 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3465 void *Mem = Allocate(Size, TypeAlignment);
3466 ObjCObjectTypeImpl *T =
3467 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3468
3469 Types.push_back(T);
3470 ObjCObjectTypes.InsertNode(T, InsertPos);
3471 return QualType(T, 0);
3472}
3473
3474/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3475/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003476QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003477 llvm::FoldingSetNodeID ID;
3478 ObjCObjectPointerType::Profile(ID, ObjectT);
3479
3480 void *InsertPos = 0;
3481 if (ObjCObjectPointerType *QT =
3482 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3483 return QualType(QT, 0);
3484
3485 // Find the canonical object type.
3486 QualType Canonical;
3487 if (!ObjectT.isCanonical()) {
3488 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3489
3490 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00003491 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3492 }
3493
Douglas Gregorfd6a0882010-02-08 22:59:26 +00003494 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00003495 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3496 ObjCObjectPointerType *QType =
3497 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00003498
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003499 Types.push_back(QType);
3500 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00003501 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003502}
Chris Lattner88cb27a2008-04-07 04:56:42 +00003503
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003504/// getObjCInterfaceType - Return the unique reference to the type for the
3505/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00003506QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3507 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003508 if (Decl->TypeForDecl)
3509 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003510
Douglas Gregor0af55012011-12-16 03:12:41 +00003511 if (PrevDecl) {
3512 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3513 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3514 return QualType(PrevDecl->TypeForDecl, 0);
3515 }
3516
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00003517 // Prefer the definition, if there is one.
3518 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3519 Decl = Def;
3520
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003521 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3522 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3523 Decl->TypeForDecl = T;
3524 Types.push_back(T);
3525 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00003526}
3527
Douglas Gregor72564e72009-02-26 23:50:07 +00003528/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3529/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00003530/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00003531/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003532/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003533QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003534 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00003535 if (tofExpr->isTypeDependent()) {
3536 llvm::FoldingSetNodeID ID;
3537 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00003538
Douglas Gregorb1975722009-07-30 23:18:24 +00003539 void *InsertPos = 0;
3540 DependentTypeOfExprType *Canon
3541 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3542 if (Canon) {
3543 // We already have a "canonical" version of an identical, dependent
3544 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00003545 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00003546 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003547 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00003548 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003549 Canon
3550 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00003551 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3552 toe = Canon;
3553 }
3554 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003555 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00003556 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00003557 }
Steve Naroff9752f252007-08-01 18:02:17 +00003558 Types.push_back(toe);
3559 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003560}
3561
Steve Naroff9752f252007-08-01 18:02:17 +00003562/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3563/// TypeOfType AST's. The only motivation to unique these nodes would be
3564/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003565/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003566/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003567QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00003568 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00003569 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00003570 Types.push_back(tot);
3571 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003572}
3573
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00003574
Anders Carlsson395b4752009-06-24 19:06:50 +00003575/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3576/// DecltypeType AST's. The only motivation to unique these nodes would be
3577/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003578/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00003579/// on canonical types (which are always unique).
Douglas Gregorf8af9822012-02-12 18:42:33 +00003580QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003581 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00003582
3583 // C++0x [temp.type]p2:
3584 // If an expression e involves a template parameter, decltype(e) denotes a
3585 // unique dependent type. Two such decltype-specifiers refer to the same
3586 // type only if their expressions are equivalent (14.5.6.1).
3587 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003588 llvm::FoldingSetNodeID ID;
3589 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00003590
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003591 void *InsertPos = 0;
3592 DependentDecltypeType *Canon
3593 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3594 if (Canon) {
3595 // We already have a "canonical" version of an equivalent, dependent
3596 // decltype type. Use that as our canonical type.
Richard Smith0d729102012-08-13 20:08:14 +00003597 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003598 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003599 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003600 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003601 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003602 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3603 dt = Canon;
3604 }
3605 } else {
Douglas Gregorf8af9822012-02-12 18:42:33 +00003606 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3607 getCanonicalType(UnderlyingType));
Douglas Gregordd0257c2009-07-08 00:03:05 +00003608 }
Anders Carlsson395b4752009-06-24 19:06:50 +00003609 Types.push_back(dt);
3610 return QualType(dt, 0);
3611}
3612
Sean Huntca63c202011-05-24 22:41:36 +00003613/// getUnaryTransformationType - We don't unique these, since the memory
3614/// savings are minimal and these are rare.
3615QualType ASTContext::getUnaryTransformType(QualType BaseType,
3616 QualType UnderlyingType,
3617 UnaryTransformType::UTTKind Kind)
3618 const {
3619 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00003620 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3621 Kind,
3622 UnderlyingType->isDependentType() ?
Peter Collingbourne12fc4b02012-03-05 16:02:06 +00003623 QualType() : getCanonicalType(UnderlyingType));
Sean Huntca63c202011-05-24 22:41:36 +00003624 Types.push_back(Ty);
3625 return QualType(Ty, 0);
3626}
3627
Richard Smith60e141e2013-05-04 07:00:32 +00003628/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3629/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3630/// canonical deduced-but-dependent 'auto' type.
3631QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Richard Smithdc7a4f52013-04-30 13:56:41 +00003632 bool IsDependent) const {
Richard Smith60e141e2013-05-04 07:00:32 +00003633 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
3634 return getAutoDeductType();
3635
3636 // Look in the folding set for an existing type.
Richard Smith483b9f32011-02-21 20:05:19 +00003637 void *InsertPos = 0;
Richard Smith60e141e2013-05-04 07:00:32 +00003638 llvm::FoldingSetNodeID ID;
3639 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
3640 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3641 return QualType(AT, 0);
Richard Smith483b9f32011-02-21 20:05:19 +00003642
Richard Smitha2c36462013-04-26 16:15:35 +00003643 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithdc7a4f52013-04-30 13:56:41 +00003644 IsDecltypeAuto,
3645 IsDependent);
Richard Smith483b9f32011-02-21 20:05:19 +00003646 Types.push_back(AT);
3647 if (InsertPos)
3648 AutoTypes.InsertNode(AT, InsertPos);
3649 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00003650}
3651
Eli Friedmanb001de72011-10-06 23:00:33 +00003652/// getAtomicType - Return the uniqued reference to the atomic type for
3653/// the given value type.
3654QualType ASTContext::getAtomicType(QualType T) const {
3655 // Unique pointers, to guarantee there is only one pointer of a particular
3656 // structure.
3657 llvm::FoldingSetNodeID ID;
3658 AtomicType::Profile(ID, T);
3659
3660 void *InsertPos = 0;
3661 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3662 return QualType(AT, 0);
3663
3664 // If the atomic value type isn't canonical, this won't be a canonical type
3665 // either, so fill in the canonical type field.
3666 QualType Canonical;
3667 if (!T.isCanonical()) {
3668 Canonical = getAtomicType(getCanonicalType(T));
3669
3670 // Get the new insert position for the node we care about.
3671 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3672 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3673 }
3674 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3675 Types.push_back(New);
3676 AtomicTypes.InsertNode(New, InsertPos);
3677 return QualType(New, 0);
3678}
3679
Richard Smithad762fc2011-04-14 22:09:26 +00003680/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3681QualType ASTContext::getAutoDeductType() const {
3682 if (AutoDeductTy.isNull())
Richard Smith60e141e2013-05-04 07:00:32 +00003683 AutoDeductTy = QualType(
3684 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
3685 /*dependent*/false),
3686 0);
Richard Smithad762fc2011-04-14 22:09:26 +00003687 return AutoDeductTy;
3688}
3689
3690/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3691QualType ASTContext::getAutoRRefDeductType() const {
3692 if (AutoRRefDeductTy.isNull())
3693 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3694 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3695 return AutoRRefDeductTy;
3696}
3697
Reid Spencer5f016e22007-07-11 17:01:13 +00003698/// getTagDeclType - Return the unique reference to the type for the
3699/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003700QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003701 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003702 // FIXME: What is the design on getTagDeclType when it requires casting
3703 // away const? mutable?
3704 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003705}
3706
Mike Stump1eb44332009-09-09 15:08:12 +00003707/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3708/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3709/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003710CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003711 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003712}
3713
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003714/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3715CanQualType ASTContext::getIntMaxType() const {
3716 return getFromTargetType(Target->getIntMaxType());
3717}
3718
3719/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3720CanQualType ASTContext::getUIntMaxType() const {
3721 return getFromTargetType(Target->getUIntMaxType());
3722}
3723
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003724/// getSignedWCharType - Return the type of "signed wchar_t".
3725/// Used when in C++, as a GCC extension.
3726QualType ASTContext::getSignedWCharType() const {
3727 // FIXME: derive from "Target" ?
3728 return WCharTy;
3729}
3730
3731/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3732/// Used when in C++, as a GCC extension.
3733QualType ASTContext::getUnsignedWCharType() const {
3734 // FIXME: derive from "Target" ?
3735 return UnsignedIntTy;
3736}
3737
Enea Zaffanella9677eb82013-01-26 17:08:37 +00003738QualType ASTContext::getIntPtrType() const {
3739 return getFromTargetType(Target->getIntPtrType());
3740}
3741
3742QualType ASTContext::getUIntPtrType() const {
3743 return getCorrespondingUnsignedType(getIntPtrType());
3744}
3745
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003746/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003747/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3748QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003749 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003750}
3751
Eli Friedman6902e412012-11-27 02:58:24 +00003752/// \brief Return the unique type for "pid_t" defined in
3753/// <sys/types.h>. We need this to compute the correct type for vfork().
3754QualType ASTContext::getProcessIDType() const {
3755 return getFromTargetType(Target->getProcessIDType());
3756}
3757
Chris Lattnere6327742008-04-02 05:18:44 +00003758//===----------------------------------------------------------------------===//
3759// Type Operators
3760//===----------------------------------------------------------------------===//
3761
Jay Foad4ba2a172011-01-12 09:06:06 +00003762CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003763 // Push qualifiers into arrays, and then discard any remaining
3764 // qualifiers.
3765 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003766 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003767 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003768 QualType Result;
3769 if (isa<ArrayType>(Ty)) {
3770 Result = getArrayDecayedType(QualType(Ty,0));
3771 } else if (isa<FunctionType>(Ty)) {
3772 Result = getPointerType(QualType(Ty, 0));
3773 } else {
3774 Result = QualType(Ty, 0);
3775 }
3776
3777 return CanQualType::CreateUnsafe(Result);
3778}
3779
John McCall62c28c82011-01-18 07:41:22 +00003780QualType ASTContext::getUnqualifiedArrayType(QualType type,
3781 Qualifiers &quals) {
3782 SplitQualType splitType = type.getSplitUnqualifiedType();
3783
3784 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3785 // the unqualified desugared type and then drops it on the floor.
3786 // We then have to strip that sugar back off with
3787 // getUnqualifiedDesugaredType(), which is silly.
3788 const ArrayType *AT =
John McCall200fa532012-02-08 00:46:36 +00003789 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall62c28c82011-01-18 07:41:22 +00003790
3791 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003792 if (!AT) {
John McCall200fa532012-02-08 00:46:36 +00003793 quals = splitType.Quals;
3794 return QualType(splitType.Ty, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003795 }
3796
John McCall62c28c82011-01-18 07:41:22 +00003797 // Otherwise, recurse on the array's element type.
3798 QualType elementType = AT->getElementType();
3799 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3800
3801 // If that didn't change the element type, AT has no qualifiers, so we
3802 // can just use the results in splitType.
3803 if (elementType == unqualElementType) {
3804 assert(quals.empty()); // from the recursive call
John McCall200fa532012-02-08 00:46:36 +00003805 quals = splitType.Quals;
3806 return QualType(splitType.Ty, 0);
John McCall62c28c82011-01-18 07:41:22 +00003807 }
3808
3809 // Otherwise, add in the qualifiers from the outermost type, then
3810 // build the type back up.
John McCall200fa532012-02-08 00:46:36 +00003811 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003812
Douglas Gregor9dadd942010-05-17 18:45:21 +00003813 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003814 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003815 CAT->getSizeModifier(), 0);
3816 }
3817
Douglas Gregor9dadd942010-05-17 18:45:21 +00003818 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003819 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003820 }
3821
Douglas Gregor9dadd942010-05-17 18:45:21 +00003822 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003823 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003824 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003825 VAT->getSizeModifier(),
3826 VAT->getIndexTypeCVRQualifiers(),
3827 VAT->getBracketsRange());
3828 }
3829
3830 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003831 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003832 DSAT->getSizeModifier(), 0,
3833 SourceRange());
3834}
3835
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003836/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3837/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3838/// they point to and return true. If T1 and T2 aren't pointer types
3839/// or pointer-to-member types, or if they are not similar at this
3840/// level, returns false and leaves T1 and T2 unchanged. Top-level
3841/// qualifiers on T1 and T2 are ignored. This function will typically
3842/// be called in a loop that successively "unwraps" pointer and
3843/// pointer-to-member types to compare them at each level.
3844bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3845 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3846 *T2PtrType = T2->getAs<PointerType>();
3847 if (T1PtrType && T2PtrType) {
3848 T1 = T1PtrType->getPointeeType();
3849 T2 = T2PtrType->getPointeeType();
3850 return true;
3851 }
3852
3853 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3854 *T2MPType = T2->getAs<MemberPointerType>();
3855 if (T1MPType && T2MPType &&
3856 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3857 QualType(T2MPType->getClass(), 0))) {
3858 T1 = T1MPType->getPointeeType();
3859 T2 = T2MPType->getPointeeType();
3860 return true;
3861 }
3862
David Blaikie4e4d0842012-03-11 07:00:24 +00003863 if (getLangOpts().ObjC1) {
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003864 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3865 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3866 if (T1OPType && T2OPType) {
3867 T1 = T1OPType->getPointeeType();
3868 T2 = T2OPType->getPointeeType();
3869 return true;
3870 }
3871 }
3872
3873 // FIXME: Block pointers, too?
3874
3875 return false;
3876}
3877
Jay Foad4ba2a172011-01-12 09:06:06 +00003878DeclarationNameInfo
3879ASTContext::getNameForTemplate(TemplateName Name,
3880 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003881 switch (Name.getKind()) {
3882 case TemplateName::QualifiedTemplate:
3883 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003884 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003885 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3886 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003887
John McCall14606042011-06-30 08:33:18 +00003888 case TemplateName::OverloadedTemplate: {
3889 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3890 // DNInfo work in progress: CHECKME: what about DNLoc?
3891 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3892 }
3893
3894 case TemplateName::DependentTemplate: {
3895 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003896 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003897 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003898 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3899 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003900 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003901 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3902 // DNInfo work in progress: FIXME: source locations?
3903 DeclarationNameLoc DNLoc;
3904 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3905 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3906 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003907 }
3908 }
3909
John McCall14606042011-06-30 08:33:18 +00003910 case TemplateName::SubstTemplateTemplateParm: {
3911 SubstTemplateTemplateParmStorage *subst
3912 = Name.getAsSubstTemplateTemplateParm();
3913 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3914 NameLoc);
3915 }
3916
3917 case TemplateName::SubstTemplateTemplateParmPack: {
3918 SubstTemplateTemplateParmPackStorage *subst
3919 = Name.getAsSubstTemplateTemplateParmPack();
3920 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3921 NameLoc);
3922 }
3923 }
3924
3925 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003926}
3927
Jay Foad4ba2a172011-01-12 09:06:06 +00003928TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003929 switch (Name.getKind()) {
3930 case TemplateName::QualifiedTemplate:
3931 case TemplateName::Template: {
3932 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003933 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003934 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003935 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3936
3937 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003938 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003939 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003940
John McCall14606042011-06-30 08:33:18 +00003941 case TemplateName::OverloadedTemplate:
3942 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003943
John McCall14606042011-06-30 08:33:18 +00003944 case TemplateName::DependentTemplate: {
3945 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3946 assert(DTN && "Non-dependent template names must refer to template decls.");
3947 return DTN->CanonicalTemplateName;
3948 }
3949
3950 case TemplateName::SubstTemplateTemplateParm: {
3951 SubstTemplateTemplateParmStorage *subst
3952 = Name.getAsSubstTemplateTemplateParm();
3953 return getCanonicalTemplateName(subst->getReplacement());
3954 }
3955
3956 case TemplateName::SubstTemplateTemplateParmPack: {
3957 SubstTemplateTemplateParmPackStorage *subst
3958 = Name.getAsSubstTemplateTemplateParmPack();
3959 TemplateTemplateParmDecl *canonParameter
3960 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3961 TemplateArgument canonArgPack
3962 = getCanonicalTemplateArgument(subst->getArgumentPack());
3963 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3964 }
3965 }
3966
3967 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003968}
3969
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003970bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3971 X = getCanonicalTemplateName(X);
3972 Y = getCanonicalTemplateName(Y);
3973 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3974}
3975
Mike Stump1eb44332009-09-09 15:08:12 +00003976TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003977ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003978 switch (Arg.getKind()) {
3979 case TemplateArgument::Null:
3980 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003981
Douglas Gregor1275ae02009-07-28 23:00:59 +00003982 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003983 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003984
Douglas Gregord2008e22012-04-06 22:40:38 +00003985 case TemplateArgument::Declaration: {
Eli Friedmand7a6b162012-09-26 02:36:12 +00003986 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
3987 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregord2008e22012-04-06 22:40:38 +00003988 }
Mike Stump1eb44332009-09-09 15:08:12 +00003989
Eli Friedmand7a6b162012-09-26 02:36:12 +00003990 case TemplateArgument::NullPtr:
3991 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
3992 /*isNullPtr*/true);
3993
Douglas Gregor788cd062009-11-11 01:00:40 +00003994 case TemplateArgument::Template:
3995 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003996
3997 case TemplateArgument::TemplateExpansion:
3998 return TemplateArgument(getCanonicalTemplateName(
3999 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00004000 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00004001
Douglas Gregor1275ae02009-07-28 23:00:59 +00004002 case TemplateArgument::Integral:
Benjamin Kramer85524372012-06-07 15:09:51 +00004003 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00004004
Douglas Gregor1275ae02009-07-28 23:00:59 +00004005 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00004006 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00004007
Douglas Gregor1275ae02009-07-28 23:00:59 +00004008 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00004009 if (Arg.pack_size() == 0)
4010 return Arg;
4011
Douglas Gregor910f8002010-11-07 23:05:16 +00004012 TemplateArgument *CanonArgs
4013 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00004014 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004015 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00004016 AEnd = Arg.pack_end();
4017 A != AEnd; (void)++A, ++Idx)
4018 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00004019
Douglas Gregor910f8002010-11-07 23:05:16 +00004020 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00004021 }
4022 }
4023
4024 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00004025 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00004026}
4027
Douglas Gregord57959a2009-03-27 23:10:48 +00004028NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00004029ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004030 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00004031 return 0;
4032
4033 switch (NNS->getKind()) {
4034 case NestedNameSpecifier::Identifier:
4035 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00004036 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00004037 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4038 NNS->getAsIdentifier());
4039
4040 case NestedNameSpecifier::Namespace:
4041 // A namespace is canonical; build a nested-name-specifier with
4042 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00004043 return NestedNameSpecifier::Create(*this, 0,
4044 NNS->getAsNamespace()->getOriginalNamespace());
4045
4046 case NestedNameSpecifier::NamespaceAlias:
4047 // A namespace is canonical; build a nested-name-specifier with
4048 // this namespace and no prefix.
4049 return NestedNameSpecifier::Create(*this, 0,
4050 NNS->getAsNamespaceAlias()->getNamespace()
4051 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00004052
4053 case NestedNameSpecifier::TypeSpec:
4054 case NestedNameSpecifier::TypeSpecWithTemplate: {
4055 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00004056
4057 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4058 // break it apart into its prefix and identifier, then reconsititute those
4059 // as the canonical nested-name-specifier. This is required to canonicalize
4060 // a dependent nested-name-specifier involving typedefs of dependent-name
4061 // types, e.g.,
4062 // typedef typename T::type T1;
4063 // typedef typename T1::type T2;
Eli Friedman16412ef2012-03-03 04:09:56 +00004064 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4065 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor264bf662010-11-04 00:09:33 +00004066 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor264bf662010-11-04 00:09:33 +00004067
Eli Friedman16412ef2012-03-03 04:09:56 +00004068 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4069 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4070 // first place?
John McCall3b657512011-01-19 10:06:00 +00004071 return NestedNameSpecifier::Create(*this, 0, false,
4072 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00004073 }
4074
4075 case NestedNameSpecifier::Global:
4076 // The global specifier is canonical and unique.
4077 return NNS;
4078 }
4079
David Blaikie7530c032012-01-17 06:56:22 +00004080 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregord57959a2009-03-27 23:10:48 +00004081}
4082
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004083
Jay Foad4ba2a172011-01-12 09:06:06 +00004084const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004085 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004086 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004087 // Handle the common positive case fast.
4088 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4089 return AT;
4090 }
Mike Stump1eb44332009-09-09 15:08:12 +00004091
John McCall0953e762009-09-24 19:53:00 +00004092 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00004093 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004094 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004095
John McCall0953e762009-09-24 19:53:00 +00004096 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004097 // implements C99 6.7.3p8: "If the specification of an array type includes
4098 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00004099
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004100 // If we get here, we either have type qualifiers on the type, or we have
4101 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00004102 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00004103
John McCall3b657512011-01-19 10:06:00 +00004104 SplitQualType split = T.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004105 Qualifiers qs = split.Quals;
Mike Stump1eb44332009-09-09 15:08:12 +00004106
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004107 // If we have a simple case, just return now.
John McCall200fa532012-02-08 00:46:36 +00004108 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall3b657512011-01-19 10:06:00 +00004109 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004110 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00004111
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004112 // Otherwise, we have an array and we have qualifiers on it. Push the
4113 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00004114 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00004115
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004116 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4117 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4118 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004119 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004120 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4121 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4122 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004123 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00004124
Mike Stump1eb44332009-09-09 15:08:12 +00004125 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00004126 = dyn_cast<DependentSizedArrayType>(ATy))
4127 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00004128 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00004129 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00004130 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004131 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004132 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00004133
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004134 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004135 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00004136 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004137 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004138 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004139 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00004140}
4141
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004142QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004143 // C99 6.7.5.3p7:
4144 // A declaration of a parameter as "array of type" shall be
4145 // adjusted to "qualified pointer to type", where the type
4146 // qualifiers (if any) are those specified within the [ and ] of
4147 // the array type derivation.
4148 if (T->isArrayType())
4149 return getArrayDecayedType(T);
4150
4151 // C99 6.7.5.3p8:
4152 // A declaration of a parameter as "function returning type"
4153 // shall be adjusted to "pointer to function returning type", as
4154 // in 6.3.2.1.
4155 if (T->isFunctionType())
4156 return getPointerType(T);
4157
4158 return T;
4159}
4160
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004161QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004162 T = getVariableArrayDecayedType(T);
4163 T = getAdjustedParameterType(T);
4164 return T.getUnqualifiedType();
4165}
4166
Chris Lattnere6327742008-04-02 05:18:44 +00004167/// getArrayDecayedType - Return the properly qualified result of decaying the
4168/// specified array type to a pointer. This operation is non-trivial when
4169/// handling typedefs etc. The canonical type of "T" must be an array type,
4170/// this returns a pointer to a properly qualified element of the array.
4171///
4172/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00004173QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004174 // Get the element type with 'getAsArrayType' so that we don't lose any
4175 // typedefs in the element type of the array. This also handles propagation
4176 // of type qualifiers from the array type into the element type if present
4177 // (C99 6.7.3p8).
4178 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4179 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00004180
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004181 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00004182
4183 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00004184 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00004185}
4186
John McCall3b657512011-01-19 10:06:00 +00004187QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4188 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00004189}
4190
John McCall3b657512011-01-19 10:06:00 +00004191QualType ASTContext::getBaseElementType(QualType type) const {
4192 Qualifiers qs;
4193 while (true) {
4194 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004195 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall3b657512011-01-19 10:06:00 +00004196 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00004197
John McCall3b657512011-01-19 10:06:00 +00004198 type = array->getElementType();
John McCall200fa532012-02-08 00:46:36 +00004199 qs.addConsistentQualifiers(split.Quals);
John McCall3b657512011-01-19 10:06:00 +00004200 }
Mike Stump1eb44332009-09-09 15:08:12 +00004201
John McCall3b657512011-01-19 10:06:00 +00004202 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00004203}
4204
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004205/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00004206uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004207ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4208 uint64_t ElementCount = 1;
4209 do {
4210 ElementCount *= CA->getSize().getZExtValue();
Richard Smithd5e83942012-12-06 03:04:50 +00004211 CA = dyn_cast_or_null<ConstantArrayType>(
4212 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004213 } while (CA);
4214 return ElementCount;
4215}
4216
Reid Spencer5f016e22007-07-11 17:01:13 +00004217/// getFloatingRank - Return a relative rank for floating point types.
4218/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00004219static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00004220 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00004221 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00004222
John McCall183700f2009-09-21 23:43:11 +00004223 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4224 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004225 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00004226 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00004227 case BuiltinType::Float: return FloatRank;
4228 case BuiltinType::Double: return DoubleRank;
4229 case BuiltinType::LongDouble: return LongDoubleRank;
4230 }
4231}
4232
Mike Stump1eb44332009-09-09 15:08:12 +00004233/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4234/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00004235/// 'typeDomain' is a real floating point or complex type.
4236/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00004237QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4238 QualType Domain) const {
4239 FloatingRank EltRank = getFloatingRank(Size);
4240 if (Domain->isComplexType()) {
4241 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00004242 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Narofff1448a02007-08-27 01:27:54 +00004243 case FloatRank: return FloatComplexTy;
4244 case DoubleRank: return DoubleComplexTy;
4245 case LongDoubleRank: return LongDoubleComplexTy;
4246 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004247 }
Chris Lattner1361b112008-04-06 23:58:54 +00004248
4249 assert(Domain->isRealFloatingType() && "Unknown domain!");
4250 switch (EltRank) {
Joey Gouly19dbb202013-01-23 11:56:20 +00004251 case HalfRank: return HalfTy;
Chris Lattner1361b112008-04-06 23:58:54 +00004252 case FloatRank: return FloatTy;
4253 case DoubleRank: return DoubleTy;
4254 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00004255 }
David Blaikie561d3ab2012-01-17 02:30:50 +00004256 llvm_unreachable("getFloatingRank(): illegal value for rank");
Reid Spencer5f016e22007-07-11 17:01:13 +00004257}
4258
Chris Lattner7cfeb082008-04-06 23:55:33 +00004259/// getFloatingTypeOrder - Compare the rank of the two specified floating
4260/// point types, ignoring the domain of the type (i.e. 'double' ==
4261/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004262/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004263int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00004264 FloatingRank LHSR = getFloatingRank(LHS);
4265 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004266
Chris Lattnera75cea32008-04-06 23:38:49 +00004267 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004268 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00004269 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004270 return 1;
4271 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004272}
4273
Chris Lattnerf52ab252008-04-06 22:59:24 +00004274/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4275/// routine will assert if passed a built-in type that isn't an integer or enum,
4276/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00004277unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00004278 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00004279
Chris Lattnerf52ab252008-04-06 22:59:24 +00004280 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004281 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00004282 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004283 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004284 case BuiltinType::Char_S:
4285 case BuiltinType::Char_U:
4286 case BuiltinType::SChar:
4287 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004288 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004289 case BuiltinType::Short:
4290 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004291 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004292 case BuiltinType::Int:
4293 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004294 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004295 case BuiltinType::Long:
4296 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004297 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004298 case BuiltinType::LongLong:
4299 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004300 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00004301 case BuiltinType::Int128:
4302 case BuiltinType::UInt128:
4303 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00004304 }
4305}
4306
Eli Friedman04e83572009-08-20 04:21:42 +00004307/// \brief Whether this is a promotable bitfield reference according
4308/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4309///
4310/// \returns the type this bit-field will promote to, or NULL if no
4311/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00004312QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00004313 if (E->isTypeDependent() || E->isValueDependent())
4314 return QualType();
4315
John McCall993f43f2013-05-06 21:39:12 +00004316 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman04e83572009-08-20 04:21:42 +00004317 if (!Field)
4318 return QualType();
4319
4320 QualType FT = Field->getType();
4321
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004322 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00004323 uint64_t IntSize = getTypeSize(IntTy);
4324 // GCC extension compatibility: if the bit-field size is less than or equal
4325 // to the size of int, it gets promoted no matter what its type is.
4326 // For instance, unsigned long bf : 4 gets promoted to signed int.
4327 if (BitWidth < IntSize)
4328 return IntTy;
4329
4330 if (BitWidth == IntSize)
4331 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4332
4333 // Types bigger than int are not subject to promotions, and therefore act
4334 // like the base type.
4335 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4336 // is ridiculous.
4337 return QualType();
4338}
4339
Eli Friedmana95d7572009-08-19 07:44:53 +00004340/// getPromotedIntegerType - Returns the type that Promotable will
4341/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4342/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00004343QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00004344 assert(!Promotable.isNull());
4345 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00004346 if (const EnumType *ET = Promotable->getAs<EnumType>())
4347 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00004348
4349 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4350 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4351 // (3.9.1) can be converted to a prvalue of the first of the following
4352 // types that can represent all the values of its underlying type:
4353 // int, unsigned int, long int, unsigned long int, long long int, or
4354 // unsigned long long int [...]
4355 // FIXME: Is there some better way to compute this?
4356 if (BT->getKind() == BuiltinType::WChar_S ||
4357 BT->getKind() == BuiltinType::WChar_U ||
4358 BT->getKind() == BuiltinType::Char16 ||
4359 BT->getKind() == BuiltinType::Char32) {
4360 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4361 uint64_t FromSize = getTypeSize(BT);
4362 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4363 LongLongTy, UnsignedLongLongTy };
4364 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4365 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4366 if (FromSize < ToSize ||
4367 (FromSize == ToSize &&
4368 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4369 return PromoteTypes[Idx];
4370 }
4371 llvm_unreachable("char type should fit into long long");
4372 }
4373 }
4374
4375 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00004376 if (Promotable->isSignedIntegerType())
4377 return IntTy;
Eli Friedman5b64e772012-11-15 01:21:59 +00004378 uint64_t PromotableSize = getIntWidth(Promotable);
4379 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedmana95d7572009-08-19 07:44:53 +00004380 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4381 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4382}
4383
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004384/// \brief Recurses in pointer/array types until it finds an objc retainable
4385/// type and returns its ownership.
4386Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4387 while (!T.isNull()) {
4388 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4389 return T.getObjCLifetime();
4390 if (T->isArrayType())
4391 T = getBaseElementType(T);
4392 else if (const PointerType *PT = T->getAs<PointerType>())
4393 T = PT->getPointeeType();
4394 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00004395 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004396 else
4397 break;
4398 }
4399
4400 return Qualifiers::OCL_None;
4401}
4402
Mike Stump1eb44332009-09-09 15:08:12 +00004403/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00004404/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004405/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004406int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00004407 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4408 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00004409 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004410
Chris Lattnerf52ab252008-04-06 22:59:24 +00004411 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4412 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00004413
Chris Lattner7cfeb082008-04-06 23:55:33 +00004414 unsigned LHSRank = getIntegerRank(LHSC);
4415 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00004416
Chris Lattner7cfeb082008-04-06 23:55:33 +00004417 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4418 if (LHSRank == RHSRank) return 0;
4419 return LHSRank > RHSRank ? 1 : -1;
4420 }
Mike Stump1eb44332009-09-09 15:08:12 +00004421
Chris Lattner7cfeb082008-04-06 23:55:33 +00004422 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4423 if (LHSUnsigned) {
4424 // If the unsigned [LHS] type is larger, return it.
4425 if (LHSRank >= RHSRank)
4426 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004427
Chris Lattner7cfeb082008-04-06 23:55:33 +00004428 // If the signed type can represent all values of the unsigned type, it
4429 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004430 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004431 return -1;
4432 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00004433
Chris Lattner7cfeb082008-04-06 23:55:33 +00004434 // If the unsigned [RHS] type is larger, return it.
4435 if (RHSRank >= LHSRank)
4436 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00004437
Chris Lattner7cfeb082008-04-06 23:55:33 +00004438 // If the signed type can represent all values of the unsigned type, it
4439 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004440 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004441 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004442}
Anders Carlsson71993dd2007-08-17 05:31:46 +00004443
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004444static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004445CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4446 DeclContext *DC, IdentifierInfo *Id) {
4447 SourceLocation Loc;
David Blaikie4e4d0842012-03-11 07:00:24 +00004448 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004449 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004450 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004451 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004452}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004453
Mike Stump1eb44332009-09-09 15:08:12 +00004454// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00004455QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00004456 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004457 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004458 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004459 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00004460 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004461
Anders Carlssonf06273f2007-11-19 00:25:30 +00004462 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00004463
Anders Carlsson71993dd2007-08-17 05:31:46 +00004464 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00004465 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00004466 // int flags;
4467 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00004468 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00004469 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00004470 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00004471 FieldTypes[3] = LongTy;
4472
Anders Carlsson71993dd2007-08-17 05:31:46 +00004473 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00004474 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00004475 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004476 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00004477 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00004478 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00004479 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004480 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004481 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004482 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004483 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00004484 }
4485
Douglas Gregor838db382010-02-11 01:19:42 +00004486 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00004487 }
Mike Stump1eb44332009-09-09 15:08:12 +00004488
Anders Carlsson71993dd2007-08-17 05:31:46 +00004489 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00004490}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004491
Fariborz Jahanianf7992132013-01-04 18:45:40 +00004492QualType ASTContext::getObjCSuperType() const {
4493 if (ObjCSuperType.isNull()) {
4494 RecordDecl *ObjCSuperTypeDecl =
4495 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4496 TUDecl->addDecl(ObjCSuperTypeDecl);
4497 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4498 }
4499 return ObjCSuperType;
4500}
4501
Douglas Gregor319ac892009-04-23 22:29:11 +00004502void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004503 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00004504 assert(Rec && "Invalid CFConstantStringType");
4505 CFConstantStringTypeDecl = Rec->getDecl();
4506}
4507
Jay Foad4ba2a172011-01-12 09:06:06 +00004508QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00004509 if (BlockDescriptorType)
4510 return getTagDeclType(BlockDescriptorType);
4511
4512 RecordDecl *T;
4513 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004514 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004515 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00004516 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004517
4518 QualType FieldTypes[] = {
4519 UnsignedLongTy,
4520 UnsignedLongTy,
4521 };
4522
4523 const char *FieldNames[] = {
4524 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00004525 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00004526 };
4527
4528 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004529 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00004530 SourceLocation(),
4531 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004532 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00004533 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004534 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004535 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004536 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00004537 T->addDecl(Field);
4538 }
4539
Douglas Gregor838db382010-02-11 01:19:42 +00004540 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004541
4542 BlockDescriptorType = T;
4543
4544 return getTagDeclType(BlockDescriptorType);
4545}
4546
Jay Foad4ba2a172011-01-12 09:06:06 +00004547QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00004548 if (BlockDescriptorExtendedType)
4549 return getTagDeclType(BlockDescriptorExtendedType);
4550
4551 RecordDecl *T;
4552 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004553 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004554 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00004555 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004556
4557 QualType FieldTypes[] = {
4558 UnsignedLongTy,
4559 UnsignedLongTy,
4560 getPointerType(VoidPtrTy),
4561 getPointerType(VoidPtrTy)
4562 };
4563
4564 const char *FieldNames[] = {
4565 "reserved",
4566 "Size",
4567 "CopyFuncPtr",
4568 "DestroyFuncPtr"
4569 };
4570
4571 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004572 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00004573 SourceLocation(),
4574 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004575 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00004576 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004577 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004578 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004579 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00004580 T->addDecl(Field);
4581 }
4582
Douglas Gregor838db382010-02-11 01:19:42 +00004583 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004584
4585 BlockDescriptorExtendedType = T;
4586
4587 return getTagDeclType(BlockDescriptorExtendedType);
4588}
4589
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004590/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4591/// requires copy/dispose. Note that this must match the logic
4592/// in buildByrefHelpers.
4593bool ASTContext::BlockRequiresCopying(QualType Ty,
4594 const VarDecl *D) {
4595 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4596 const Expr *copyExpr = getBlockVarCopyInits(D);
4597 if (!copyExpr && record->hasTrivialDestructor()) return false;
4598
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004599 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00004600 }
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004601
4602 if (!Ty->isObjCRetainableType()) return false;
4603
4604 Qualifiers qs = Ty.getQualifiers();
4605
4606 // If we have lifetime, that dominates.
4607 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4608 assert(getLangOpts().ObjCAutoRefCount);
4609
4610 switch (lifetime) {
4611 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4612
4613 // These are just bits as far as the runtime is concerned.
4614 case Qualifiers::OCL_ExplicitNone:
4615 case Qualifiers::OCL_Autoreleasing:
4616 return false;
4617
4618 // Tell the runtime that this is ARC __weak, called by the
4619 // byref routines.
4620 case Qualifiers::OCL_Weak:
4621 // ARC __strong __block variables need to be retained.
4622 case Qualifiers::OCL_Strong:
4623 return true;
4624 }
4625 llvm_unreachable("fell out of lifetime switch!");
4626 }
4627 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4628 Ty->isObjCObjectPointerType());
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004629}
4630
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004631bool ASTContext::getByrefLifetime(QualType Ty,
4632 Qualifiers::ObjCLifetime &LifeTime,
4633 bool &HasByrefExtendedLayout) const {
4634
4635 if (!getLangOpts().ObjC1 ||
4636 getLangOpts().getGC() != LangOptions::NonGC)
4637 return false;
4638
4639 HasByrefExtendedLayout = false;
Fariborz Jahanian34db84f2012-12-11 19:58:01 +00004640 if (Ty->isRecordType()) {
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004641 HasByrefExtendedLayout = true;
4642 LifeTime = Qualifiers::OCL_None;
4643 }
4644 else if (getLangOpts().ObjCAutoRefCount)
4645 LifeTime = Ty.getObjCLifetime();
4646 // MRR.
4647 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4648 LifeTime = Qualifiers::OCL_ExplicitNone;
4649 else
4650 LifeTime = Qualifiers::OCL_None;
4651 return true;
4652}
4653
Douglas Gregore97179c2011-09-08 01:46:34 +00004654TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4655 if (!ObjCInstanceTypeDecl)
4656 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4657 getTranslationUnitDecl(),
4658 SourceLocation(),
4659 SourceLocation(),
4660 &Idents.get("instancetype"),
4661 getTrivialTypeSourceInfo(getObjCIdType()));
4662 return ObjCInstanceTypeDecl;
4663}
4664
Anders Carlssone8c49532007-10-29 06:33:42 +00004665// This returns true if a type has been typedefed to BOOL:
4666// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00004667static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00004668 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00004669 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4670 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00004671
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004672 return false;
4673}
4674
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004675/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004676/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00004677CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00004678 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4679 return CharUnits::Zero();
4680
Ken Dyck199c3d62010-01-11 17:06:35 +00004681 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004682
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004683 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004684 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004685 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004686 // Treat arrays as pointers, since that's how they're passed in.
4687 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004688 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004689 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004690}
4691
4692static inline
4693std::string charUnitsToString(const CharUnits &CU) {
4694 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004695}
4696
John McCall6b5a61b2011-02-07 10:33:21 +00004697/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004698/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004699std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4700 std::string S;
4701
David Chisnall5e530af2009-11-17 19:33:30 +00004702 const BlockDecl *Decl = Expr->getBlockDecl();
4703 QualType BlockTy =
4704 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4705 // Encode result type.
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004706 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004707 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4708 BlockTy->getAs<FunctionType>()->getResultType(),
4709 S, true /*Extended*/);
4710 else
4711 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4712 S);
David Chisnall5e530af2009-11-17 19:33:30 +00004713 // Compute size of all parameters.
4714 // Start with computing size of a pointer in number of bytes.
4715 // FIXME: There might(should) be a better way of doing this computation!
4716 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004717 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4718 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004719 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004720 E = Decl->param_end(); PI != E; ++PI) {
4721 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004722 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahanian075a5432012-06-30 00:48:59 +00004723 if (sz.isZero())
4724 continue;
Ken Dyck199c3d62010-01-11 17:06:35 +00004725 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004726 ParmOffset += sz;
4727 }
4728 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004729 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004730 // Block pointer and offset.
4731 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004732
4733 // Argument types.
4734 ParmOffset = PtrSize;
4735 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4736 Decl->param_end(); PI != E; ++PI) {
4737 ParmVarDecl *PVDecl = *PI;
4738 QualType PType = PVDecl->getOriginalType();
4739 if (const ArrayType *AT =
4740 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4741 // Use array's original type only if it has known number of
4742 // elements.
4743 if (!isa<ConstantArrayType>(AT))
4744 PType = PVDecl->getType();
4745 } else if (PType->isFunctionType())
4746 PType = PVDecl->getType();
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004747 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004748 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4749 S, true /*Extended*/);
4750 else
4751 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004752 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004753 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004754 }
John McCall6b5a61b2011-02-07 10:33:21 +00004755
4756 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004757}
4758
Douglas Gregorf968d832011-05-27 01:19:52 +00004759bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004760 std::string& S) {
4761 // Encode result type.
4762 getObjCEncodingForType(Decl->getResultType(), S);
4763 CharUnits ParmOffset;
4764 // Compute size of all parameters.
4765 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4766 E = Decl->param_end(); PI != E; ++PI) {
4767 QualType PType = (*PI)->getType();
4768 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004769 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004770 continue;
4771
David Chisnall5389f482010-12-30 14:05:53 +00004772 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004773 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004774 ParmOffset += sz;
4775 }
4776 S += charUnitsToString(ParmOffset);
4777 ParmOffset = CharUnits::Zero();
4778
4779 // Argument types.
4780 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4781 E = Decl->param_end(); PI != E; ++PI) {
4782 ParmVarDecl *PVDecl = *PI;
4783 QualType PType = PVDecl->getOriginalType();
4784 if (const ArrayType *AT =
4785 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4786 // Use array's original type only if it has known number of
4787 // elements.
4788 if (!isa<ConstantArrayType>(AT))
4789 PType = PVDecl->getType();
4790 } else if (PType->isFunctionType())
4791 PType = PVDecl->getType();
4792 getObjCEncodingForType(PType, S);
4793 S += charUnitsToString(ParmOffset);
4794 ParmOffset += getObjCEncodingTypeSize(PType);
4795 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004796
4797 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004798}
4799
Bob Wilsondc8dab62011-11-30 01:57:58 +00004800/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4801/// method parameter or return type. If Extended, include class names and
4802/// block object types.
4803void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4804 QualType T, std::string& S,
4805 bool Extended) const {
4806 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4807 getObjCEncodingForTypeQualifier(QT, S);
4808 // Encode parameter type.
4809 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4810 true /*OutermostType*/,
4811 false /*EncodingProperty*/,
4812 false /*StructField*/,
4813 Extended /*EncodeBlockParameters*/,
4814 Extended /*EncodeClassNames*/);
4815}
4816
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004817/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004818/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004819bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004820 std::string& S,
4821 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004822 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004823 // Encode return type.
4824 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4825 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004826 // Compute size of all parameters.
4827 // Start with computing size of a pointer in number of bytes.
4828 // FIXME: There might(should) be a better way of doing this computation!
4829 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004830 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004831 // The first two arguments (self and _cmd) are pointers; account for
4832 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004833 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004834 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004835 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004836 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004837 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004838 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004839 continue;
4840
Ken Dyck199c3d62010-01-11 17:06:35 +00004841 assert (sz.isPositive() &&
4842 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004843 ParmOffset += sz;
4844 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004845 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004846 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004847 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004848
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004849 // Argument types.
4850 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004851 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004852 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004853 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004854 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004855 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004856 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4857 // Use array's original type only if it has known number of
4858 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004859 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004860 PType = PVDecl->getType();
4861 } else if (PType->isFunctionType())
4862 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004863 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4864 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004865 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004866 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004867 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004868
4869 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004870}
4871
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004872/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004873/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004874/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4875/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004876/// Property attributes are stored as a comma-delimited C string. The simple
4877/// attributes readonly and bycopy are encoded as single characters. The
4878/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4879/// encoded as single characters, followed by an identifier. Property types
4880/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004881/// these attributes are defined by the following enumeration:
4882/// @code
4883/// enum PropertyAttributes {
4884/// kPropertyReadOnly = 'R', // property is read-only.
4885/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4886/// kPropertyByref = '&', // property is a reference to the value last assigned
4887/// kPropertyDynamic = 'D', // property is dynamic
4888/// kPropertyGetter = 'G', // followed by getter selector name
4889/// kPropertySetter = 'S', // followed by setter selector name
4890/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson0d4cb852012-03-22 17:48:02 +00004891/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004892/// kPropertyWeak = 'W' // 'weak' property
4893/// kPropertyStrong = 'P' // property GC'able
4894/// kPropertyNonAtomic = 'N' // property non-atomic
4895/// };
4896/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004897void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004898 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004899 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004900 // Collect information from the property implementation decl(s).
4901 bool Dynamic = false;
4902 ObjCPropertyImplDecl *SynthesizePID = 0;
4903
4904 // FIXME: Duplicated code due to poor abstraction.
4905 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004906 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004907 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4908 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004909 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004910 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004911 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004912 if (PID->getPropertyDecl() == PD) {
4913 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4914 Dynamic = true;
4915 } else {
4916 SynthesizePID = PID;
4917 }
4918 }
4919 }
4920 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004921 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004922 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004923 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004924 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004925 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004926 if (PID->getPropertyDecl() == PD) {
4927 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4928 Dynamic = true;
4929 } else {
4930 SynthesizePID = PID;
4931 }
4932 }
Mike Stump1eb44332009-09-09 15:08:12 +00004933 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004934 }
4935 }
4936
4937 // FIXME: This is not very efficient.
4938 S = "T";
4939
4940 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004941 // GCC has some special rules regarding encoding of properties which
4942 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004943 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004944 true /* outermost type */,
4945 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004946
4947 if (PD->isReadOnly()) {
4948 S += ",R";
Nico Weberd7ceab32013-05-08 23:47:40 +00004949 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
4950 S += ",C";
4951 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
4952 S += ",&";
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004953 } else {
4954 switch (PD->getSetterKind()) {
4955 case ObjCPropertyDecl::Assign: break;
4956 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004957 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004958 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004959 }
4960 }
4961
4962 // It really isn't clear at all what this means, since properties
4963 // are "dynamic by default".
4964 if (Dynamic)
4965 S += ",D";
4966
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004967 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4968 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004969
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004970 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4971 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004972 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004973 }
4974
4975 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4976 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004977 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004978 }
4979
4980 if (SynthesizePID) {
4981 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4982 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004983 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004984 }
4985
4986 // FIXME: OBJCGC: weak & strong
4987}
4988
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004989/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004990/// Another legacy compatibility encoding: 32-bit longs are encoded as
4991/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004992/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4993///
4994void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004995 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004996 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004997 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004998 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004999 else
Jay Foad4ba2a172011-01-12 09:06:06 +00005000 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005001 PointeeTy = IntTy;
5002 }
5003 }
5004}
5005
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005006void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00005007 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005008 // We follow the behavior of gcc, expanding structures which are
5009 // directly pointed to, and expanding embedded structures. Note that
5010 // these rules are sufficient to prevent recursive encoding of the
5011 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00005012 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00005013 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005014}
5015
John McCall3624e9e2012-12-20 02:45:14 +00005016static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5017 BuiltinType::Kind kind) {
5018 switch (kind) {
David Chisnall64fd7e82010-06-04 01:10:52 +00005019 case BuiltinType::Void: return 'v';
5020 case BuiltinType::Bool: return 'B';
5021 case BuiltinType::Char_U:
5022 case BuiltinType::UChar: return 'C';
John McCall3624e9e2012-12-20 02:45:14 +00005023 case BuiltinType::Char16:
David Chisnall64fd7e82010-06-04 01:10:52 +00005024 case BuiltinType::UShort: return 'S';
John McCall3624e9e2012-12-20 02:45:14 +00005025 case BuiltinType::Char32:
David Chisnall64fd7e82010-06-04 01:10:52 +00005026 case BuiltinType::UInt: return 'I';
5027 case BuiltinType::ULong:
John McCall3624e9e2012-12-20 02:45:14 +00005028 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00005029 case BuiltinType::UInt128: return 'T';
5030 case BuiltinType::ULongLong: return 'Q';
5031 case BuiltinType::Char_S:
5032 case BuiltinType::SChar: return 'c';
5033 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00005034 case BuiltinType::WChar_S:
5035 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00005036 case BuiltinType::Int: return 'i';
5037 case BuiltinType::Long:
John McCall3624e9e2012-12-20 02:45:14 +00005038 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00005039 case BuiltinType::LongLong: return 'q';
5040 case BuiltinType::Int128: return 't';
5041 case BuiltinType::Float: return 'f';
5042 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00005043 case BuiltinType::LongDouble: return 'D';
John McCall3624e9e2012-12-20 02:45:14 +00005044 case BuiltinType::NullPtr: return '*'; // like char*
5045
5046 case BuiltinType::Half:
5047 // FIXME: potentially need @encodes for these!
5048 return ' ';
5049
5050 case BuiltinType::ObjCId:
5051 case BuiltinType::ObjCClass:
5052 case BuiltinType::ObjCSel:
5053 llvm_unreachable("@encoding ObjC primitive type");
5054
5055 // OpenCL and placeholder types don't need @encodings.
5056 case BuiltinType::OCLImage1d:
5057 case BuiltinType::OCLImage1dArray:
5058 case BuiltinType::OCLImage1dBuffer:
5059 case BuiltinType::OCLImage2d:
5060 case BuiltinType::OCLImage2dArray:
5061 case BuiltinType::OCLImage3d:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005062 case BuiltinType::OCLEvent:
Guy Benyei21f18c42013-02-07 10:55:47 +00005063 case BuiltinType::OCLSampler:
John McCall3624e9e2012-12-20 02:45:14 +00005064 case BuiltinType::Dependent:
5065#define BUILTIN_TYPE(KIND, ID)
5066#define PLACEHOLDER_TYPE(KIND, ID) \
5067 case BuiltinType::KIND:
5068#include "clang/AST/BuiltinTypes.def"
5069 llvm_unreachable("invalid builtin type for @encode");
David Chisnall64fd7e82010-06-04 01:10:52 +00005070 }
David Blaikie719e53f2013-01-09 17:48:41 +00005071 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnall64fd7e82010-06-04 01:10:52 +00005072}
5073
Douglas Gregor5471bc82011-09-08 17:18:35 +00005074static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5075 EnumDecl *Enum = ET->getDecl();
5076
5077 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5078 if (!Enum->isFixed())
5079 return 'i';
5080
5081 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall3624e9e2012-12-20 02:45:14 +00005082 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5083 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor5471bc82011-09-08 17:18:35 +00005084}
5085
Jay Foad4ba2a172011-01-12 09:06:06 +00005086static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00005087 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005088 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00005089 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00005090 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5091 // The GNU runtime requires more information; bitfields are encoded as b,
5092 // then the offset (in bits) of the first element, then the type of the
5093 // bitfield, then the size in bits. For example, in this structure:
5094 //
5095 // struct
5096 // {
5097 // int integer;
5098 // int flags:2;
5099 // };
5100 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5101 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5102 // information is not especially sensible, but we're stuck with it for
5103 // compatibility with GCC, although providing it breaks anything that
5104 // actually uses runtime introspection and wants to work on both runtimes...
John McCall260611a2012-06-20 06:18:46 +00005105 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnall64fd7e82010-06-04 01:10:52 +00005106 const RecordDecl *RD = FD->getParent();
5107 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00005108 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00005109 if (const EnumType *ET = T->getAs<EnumType>())
5110 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall3624e9e2012-12-20 02:45:14 +00005111 else {
5112 const BuiltinType *BT = T->castAs<BuiltinType>();
5113 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5114 }
David Chisnall64fd7e82010-06-04 01:10:52 +00005115 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005116 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00005117}
5118
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00005119// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005120void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5121 bool ExpandPointedToStructures,
5122 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00005123 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00005124 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005125 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00005126 bool StructField,
5127 bool EncodeBlockParameters,
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005128 bool EncodeClassNames,
5129 bool EncodePointerToObjCTypedef) const {
John McCall3624e9e2012-12-20 02:45:14 +00005130 CanQualType CT = getCanonicalType(T);
5131 switch (CT->getTypeClass()) {
5132 case Type::Builtin:
5133 case Type::Enum:
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005134 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00005135 return EncodeBitField(this, S, T, FD);
John McCall3624e9e2012-12-20 02:45:14 +00005136 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5137 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5138 else
5139 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005140 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005141
John McCall3624e9e2012-12-20 02:45:14 +00005142 case Type::Complex: {
5143 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005144 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00005145 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005146 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005147 return;
5148 }
John McCall3624e9e2012-12-20 02:45:14 +00005149
5150 case Type::Atomic: {
5151 const AtomicType *AT = T->castAs<AtomicType>();
5152 S += 'A';
5153 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5154 false, false);
5155 return;
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00005156 }
John McCall3624e9e2012-12-20 02:45:14 +00005157
5158 // encoding for pointer or reference types.
5159 case Type::Pointer:
5160 case Type::LValueReference:
5161 case Type::RValueReference: {
5162 QualType PointeeTy;
5163 if (isa<PointerType>(CT)) {
5164 const PointerType *PT = T->castAs<PointerType>();
5165 if (PT->isObjCSelType()) {
5166 S += ':';
5167 return;
5168 }
5169 PointeeTy = PT->getPointeeType();
5170 } else {
5171 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5172 }
5173
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005174 bool isReadOnly = false;
5175 // For historical/compatibility reasons, the read-only qualifier of the
5176 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5177 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00005178 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00005179 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005180 if (OutermostType && T.isConstQualified()) {
5181 isReadOnly = true;
5182 S += 'r';
5183 }
Mike Stump9fdbab32009-07-31 02:02:20 +00005184 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005185 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00005186 while (P->getAs<PointerType>())
5187 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005188 if (P.isConstQualified()) {
5189 isReadOnly = true;
5190 S += 'r';
5191 }
5192 }
5193 if (isReadOnly) {
5194 // Another legacy compatibility encoding. Some ObjC qualifier and type
5195 // combinations need to be rearranged.
5196 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00005197 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00005198 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005199 }
Mike Stump1eb44332009-09-09 15:08:12 +00005200
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005201 if (PointeeTy->isCharType()) {
5202 // char pointer types should be encoded as '*' unless it is a
5203 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00005204 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005205 S += '*';
5206 return;
5207 }
Ted Kremenek6217b802009-07-29 21:53:49 +00005208 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00005209 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5210 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5211 S += '#';
5212 return;
5213 }
5214 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5215 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5216 S += '@';
5217 return;
5218 }
5219 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005220 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005221 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005222 getLegacyIntegralTypeEncoding(PointeeTy);
5223
Mike Stump1eb44332009-09-09 15:08:12 +00005224 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005225 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005226 return;
5227 }
John McCall3624e9e2012-12-20 02:45:14 +00005228
5229 case Type::ConstantArray:
5230 case Type::IncompleteArray:
5231 case Type::VariableArray: {
5232 const ArrayType *AT = cast<ArrayType>(CT);
5233
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005234 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00005235 // Incomplete arrays are encoded as a pointer to the array element.
5236 S += '^';
5237
Mike Stump1eb44332009-09-09 15:08:12 +00005238 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005239 false, ExpandStructures, FD);
5240 } else {
5241 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00005242
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005243 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
5244 if (getTypeSize(CAT->getElementType()) == 0)
5245 S += '0';
5246 else
5247 S += llvm::utostr(CAT->getSize().getZExtValue());
5248 } else {
Anders Carlsson559a8332009-02-22 01:38:57 +00005249 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005250 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5251 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00005252 S += '0';
5253 }
Mike Stump1eb44332009-09-09 15:08:12 +00005254
5255 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005256 false, ExpandStructures, FD);
5257 S += ']';
5258 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005259 return;
5260 }
Mike Stump1eb44332009-09-09 15:08:12 +00005261
John McCall3624e9e2012-12-20 02:45:14 +00005262 case Type::FunctionNoProto:
5263 case Type::FunctionProto:
Anders Carlssonc0a87b72007-10-30 00:06:20 +00005264 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005265 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005266
John McCall3624e9e2012-12-20 02:45:14 +00005267 case Type::Record: {
5268 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005269 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005270 // Anonymous structures print as '?'
5271 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5272 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005273 if (ClassTemplateSpecializationDecl *Spec
5274 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5275 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer5eada842013-02-22 15:46:01 +00005276 llvm::raw_string_ostream OS(S);
5277 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor910f8002010-11-07 23:05:16 +00005278 TemplateArgs.data(),
5279 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00005280 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005281 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005282 } else {
5283 S += '?';
5284 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00005285 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005286 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005287 if (!RDecl->isUnion()) {
5288 getObjCEncodingForStructureImpl(RDecl, S, FD);
5289 } else {
5290 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5291 FieldEnd = RDecl->field_end();
5292 Field != FieldEnd; ++Field) {
5293 if (FD) {
5294 S += '"';
5295 S += Field->getNameAsString();
5296 S += '"';
5297 }
Mike Stump1eb44332009-09-09 15:08:12 +00005298
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005299 // Special case bit-fields.
5300 if (Field->isBitField()) {
5301 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie581deb32012-06-06 20:45:41 +00005302 *Field);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005303 } else {
5304 QualType qt = Field->getType();
5305 getLegacyIntegralTypeEncoding(qt);
5306 getObjCEncodingForTypeImpl(qt, S, false, true,
5307 FD, /*OutermostType*/false,
5308 /*EncodingProperty*/false,
5309 /*StructField*/true);
5310 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005311 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005312 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00005313 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005314 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005315 return;
5316 }
Mike Stump1eb44332009-09-09 15:08:12 +00005317
John McCall3624e9e2012-12-20 02:45:14 +00005318 case Type::BlockPointer: {
5319 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff21a98b12009-02-02 18:24:29 +00005320 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00005321 if (EncodeBlockParameters) {
John McCall3624e9e2012-12-20 02:45:14 +00005322 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilsondc8dab62011-11-30 01:57:58 +00005323
5324 S += '<';
5325 // Block return type
5326 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5327 ExpandPointedToStructures, ExpandStructures,
5328 FD,
5329 false /* OutermostType */,
5330 EncodingProperty,
5331 false /* StructField */,
5332 EncodeBlockParameters,
5333 EncodeClassNames);
5334 // Block self
5335 S += "@?";
5336 // Block parameters
5337 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5338 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5339 E = FPT->arg_type_end(); I && (I != E); ++I) {
5340 getObjCEncodingForTypeImpl(*I, S,
5341 ExpandPointedToStructures,
5342 ExpandStructures,
5343 FD,
5344 false /* OutermostType */,
5345 EncodingProperty,
5346 false /* StructField */,
5347 EncodeBlockParameters,
5348 EncodeClassNames);
5349 }
5350 }
5351 S += '>';
5352 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005353 return;
5354 }
Mike Stump1eb44332009-09-09 15:08:12 +00005355
John McCall3624e9e2012-12-20 02:45:14 +00005356 case Type::ObjCObject:
5357 case Type::ObjCInterface: {
5358 // Ignore protocol qualifiers when mangling at this level.
5359 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCallc12c5bb2010-05-15 11:32:37 +00005360
John McCall3624e9e2012-12-20 02:45:14 +00005361 // The assumption seems to be that this assert will succeed
5362 // because nested levels will have filtered out 'id' and 'Class'.
5363 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005364 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00005365 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005366 S += '{';
5367 const IdentifierInfo *II = OI->getIdentifier();
5368 S += II->getName();
5369 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00005370 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005371 DeepCollectObjCIvars(OI, true, Ivars);
5372 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00005373 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005374 if (Field->isBitField())
5375 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005376 else
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005377 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5378 false, false, false, false, false,
5379 EncodePointerToObjCTypedef);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005380 }
5381 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005382 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005383 }
Mike Stump1eb44332009-09-09 15:08:12 +00005384
John McCall3624e9e2012-12-20 02:45:14 +00005385 case Type::ObjCObjectPointer: {
5386 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00005387 if (OPT->isObjCIdType()) {
5388 S += '@';
5389 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005390 }
Mike Stump1eb44332009-09-09 15:08:12 +00005391
Steve Naroff27d20a22009-10-28 22:03:49 +00005392 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5393 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5394 // Since this is a binary compatibility issue, need to consult with runtime
5395 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00005396 S += '#';
5397 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005398 }
Mike Stump1eb44332009-09-09 15:08:12 +00005399
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005400 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005401 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00005402 ExpandPointedToStructures,
5403 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00005404 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00005405 // Note that we do extended encoding of protocol qualifer list
5406 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00005407 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005408 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5409 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00005410 S += '<';
5411 S += (*I)->getNameAsString();
5412 S += '>';
5413 }
5414 S += '"';
5415 }
5416 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005417 }
Mike Stump1eb44332009-09-09 15:08:12 +00005418
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005419 QualType PointeeTy = OPT->getPointeeType();
5420 if (!EncodingProperty &&
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005421 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5422 !EncodePointerToObjCTypedef) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005423 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00005424 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005425 // {...};
5426 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00005427 getObjCEncodingForTypeImpl(PointeeTy, S,
5428 false, ExpandPointedToStructures,
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005429 NULL,
5430 false, false, false, false, false,
5431 /*EncodePointerToObjCTypedef*/true);
Steve Naroff14108da2009-07-10 23:34:53 +00005432 return;
5433 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005434
5435 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00005436 if (OPT->getInterfaceDecl() &&
5437 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005438 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00005439 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005440 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5441 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005442 S += '<';
5443 S += (*I)->getNameAsString();
5444 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00005445 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005446 S += '"';
5447 }
5448 return;
5449 }
Mike Stump1eb44332009-09-09 15:08:12 +00005450
John McCall532ec7b2010-05-17 23:56:34 +00005451 // gcc just blithely ignores member pointers.
John McCall3624e9e2012-12-20 02:45:14 +00005452 // FIXME: we shoul do better than that. 'M' is available.
5453 case Type::MemberPointer:
John McCall532ec7b2010-05-17 23:56:34 +00005454 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005455
John McCall3624e9e2012-12-20 02:45:14 +00005456 case Type::Vector:
5457 case Type::ExtVector:
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005458 // This matches gcc's encoding, even though technically it is
5459 // insufficient.
5460 // FIXME. We should do a better job than gcc.
5461 return;
John McCall3624e9e2012-12-20 02:45:14 +00005462
Richard Smithdc7a4f52013-04-30 13:56:41 +00005463 case Type::Auto:
5464 // We could see an undeduced auto type here during error recovery.
5465 // Just ignore it.
5466 return;
5467
John McCall3624e9e2012-12-20 02:45:14 +00005468#define ABSTRACT_TYPE(KIND, BASE)
5469#define TYPE(KIND, BASE)
5470#define DEPENDENT_TYPE(KIND, BASE) \
5471 case Type::KIND:
5472#define NON_CANONICAL_TYPE(KIND, BASE) \
5473 case Type::KIND:
5474#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5475 case Type::KIND:
5476#include "clang/AST/TypeNodes.def"
5477 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005478 }
John McCall3624e9e2012-12-20 02:45:14 +00005479 llvm_unreachable("bad type kind!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005480}
5481
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005482void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5483 std::string &S,
5484 const FieldDecl *FD,
5485 bool includeVBases) const {
5486 assert(RDecl && "Expected non-null RecordDecl");
5487 assert(!RDecl->isUnion() && "Should not be called for unions");
5488 if (!RDecl->getDefinition())
5489 return;
5490
5491 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5492 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5493 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5494
5495 if (CXXRec) {
5496 for (CXXRecordDecl::base_class_iterator
5497 BI = CXXRec->bases_begin(),
5498 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5499 if (!BI->isVirtual()) {
5500 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005501 if (base->isEmpty())
5502 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005503 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005504 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5505 std::make_pair(offs, base));
5506 }
5507 }
5508 }
5509
5510 unsigned i = 0;
5511 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5512 FieldEnd = RDecl->field_end();
5513 Field != FieldEnd; ++Field, ++i) {
5514 uint64_t offs = layout.getFieldOffset(i);
5515 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie581deb32012-06-06 20:45:41 +00005516 std::make_pair(offs, *Field));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005517 }
5518
5519 if (CXXRec && includeVBases) {
5520 for (CXXRecordDecl::base_class_iterator
5521 BI = CXXRec->vbases_begin(),
5522 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5523 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005524 if (base->isEmpty())
5525 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005526 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00005527 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5528 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5529 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005530 }
5531 }
5532
5533 CharUnits size;
5534 if (CXXRec) {
5535 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5536 } else {
5537 size = layout.getSize();
5538 }
5539
5540 uint64_t CurOffs = 0;
5541 std::multimap<uint64_t, NamedDecl *>::iterator
5542 CurLayObj = FieldOrBaseOffsets.begin();
5543
Douglas Gregor58db7a52012-04-27 22:30:01 +00005544 if (CXXRec && CXXRec->isDynamicClass() &&
5545 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005546 if (FD) {
5547 S += "\"_vptr$";
5548 std::string recname = CXXRec->getNameAsString();
5549 if (recname.empty()) recname = "?";
5550 S += recname;
5551 S += '"';
5552 }
5553 S += "^^?";
5554 CurOffs += getTypeSize(VoidPtrTy);
5555 }
5556
5557 if (!RDecl->hasFlexibleArrayMember()) {
5558 // Mark the end of the structure.
5559 uint64_t offs = toBits(size);
5560 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5561 std::make_pair(offs, (NamedDecl*)0));
5562 }
5563
5564 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5565 assert(CurOffs <= CurLayObj->first);
5566
5567 if (CurOffs < CurLayObj->first) {
5568 uint64_t padding = CurLayObj->first - CurOffs;
5569 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5570 // packing/alignment of members is different that normal, in which case
5571 // the encoding will be out-of-sync with the real layout.
5572 // If the runtime switches to just consider the size of types without
5573 // taking into account alignment, we could make padding explicit in the
5574 // encoding (e.g. using arrays of chars). The encoding strings would be
5575 // longer then though.
5576 CurOffs += padding;
5577 }
5578
5579 NamedDecl *dcl = CurLayObj->second;
5580 if (dcl == 0)
5581 break; // reached end of structure.
5582
5583 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5584 // We expand the bases without their virtual bases since those are going
5585 // in the initial structure. Note that this differs from gcc which
5586 // expands virtual bases each time one is encountered in the hierarchy,
5587 // making the encoding type bigger than it really is.
5588 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005589 assert(!base->isEmpty());
5590 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005591 } else {
5592 FieldDecl *field = cast<FieldDecl>(dcl);
5593 if (FD) {
5594 S += '"';
5595 S += field->getNameAsString();
5596 S += '"';
5597 }
5598
5599 if (field->isBitField()) {
5600 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005601 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005602 } else {
5603 QualType qt = field->getType();
5604 getLegacyIntegralTypeEncoding(qt);
5605 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5606 /*OutermostType*/false,
5607 /*EncodingProperty*/false,
5608 /*StructField*/true);
5609 CurOffs += getTypeSize(field->getType());
5610 }
5611 }
5612 }
5613}
5614
Mike Stump1eb44332009-09-09 15:08:12 +00005615void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00005616 std::string& S) const {
5617 if (QT & Decl::OBJC_TQ_In)
5618 S += 'n';
5619 if (QT & Decl::OBJC_TQ_Inout)
5620 S += 'N';
5621 if (QT & Decl::OBJC_TQ_Out)
5622 S += 'o';
5623 if (QT & Decl::OBJC_TQ_Bycopy)
5624 S += 'O';
5625 if (QT & Decl::OBJC_TQ_Byref)
5626 S += 'R';
5627 if (QT & Decl::OBJC_TQ_Oneway)
5628 S += 'V';
5629}
5630
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00005631TypedefDecl *ASTContext::getObjCIdDecl() const {
5632 if (!ObjCIdDecl) {
5633 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5634 T = getObjCObjectPointerType(T);
5635 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5636 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5637 getTranslationUnitDecl(),
5638 SourceLocation(), SourceLocation(),
5639 &Idents.get("id"), IdInfo);
5640 }
5641
5642 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00005643}
5644
Douglas Gregor7a27ea52011-08-12 06:17:30 +00005645TypedefDecl *ASTContext::getObjCSelDecl() const {
5646 if (!ObjCSelDecl) {
5647 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5648 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5649 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5650 getTranslationUnitDecl(),
5651 SourceLocation(), SourceLocation(),
5652 &Idents.get("SEL"), SelInfo);
5653 }
5654 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00005655}
5656
Douglas Gregor79d67262011-08-12 05:59:41 +00005657TypedefDecl *ASTContext::getObjCClassDecl() const {
5658 if (!ObjCClassDecl) {
5659 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5660 T = getObjCObjectPointerType(T);
5661 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5662 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5663 getTranslationUnitDecl(),
5664 SourceLocation(), SourceLocation(),
5665 &Idents.get("Class"), ClassInfo);
5666 }
5667
5668 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00005669}
5670
Douglas Gregora6ea10e2012-01-17 18:09:05 +00005671ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5672 if (!ObjCProtocolClassDecl) {
5673 ObjCProtocolClassDecl
5674 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5675 SourceLocation(),
5676 &Idents.get("Protocol"),
5677 /*PrevDecl=*/0,
5678 SourceLocation(), true);
5679 }
5680
5681 return ObjCProtocolClassDecl;
5682}
5683
Meador Ingec5613b22012-06-16 03:34:49 +00005684//===----------------------------------------------------------------------===//
5685// __builtin_va_list Construction Functions
5686//===----------------------------------------------------------------------===//
5687
5688static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5689 // typedef char* __builtin_va_list;
5690 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5691 TypeSourceInfo *TInfo
5692 = Context->getTrivialTypeSourceInfo(CharPtrType);
5693
5694 TypedefDecl *VaListTypeDecl
5695 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5696 Context->getTranslationUnitDecl(),
5697 SourceLocation(), SourceLocation(),
5698 &Context->Idents.get("__builtin_va_list"),
5699 TInfo);
5700 return VaListTypeDecl;
5701}
5702
5703static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5704 // typedef void* __builtin_va_list;
5705 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5706 TypeSourceInfo *TInfo
5707 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5708
5709 TypedefDecl *VaListTypeDecl
5710 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5711 Context->getTranslationUnitDecl(),
5712 SourceLocation(), SourceLocation(),
5713 &Context->Idents.get("__builtin_va_list"),
5714 TInfo);
5715 return VaListTypeDecl;
5716}
5717
Tim Northoverc264e162013-01-31 12:13:10 +00005718static TypedefDecl *
5719CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5720 RecordDecl *VaListTagDecl;
5721 if (Context->getLangOpts().CPlusPlus) {
5722 // namespace std { struct __va_list {
5723 NamespaceDecl *NS;
5724 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5725 Context->getTranslationUnitDecl(),
5726 /*Inline*/false, SourceLocation(),
5727 SourceLocation(), &Context->Idents.get("std"),
5728 /*PrevDecl*/0);
5729
5730 VaListTagDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5731 Context->getTranslationUnitDecl(),
5732 SourceLocation(), SourceLocation(),
5733 &Context->Idents.get("__va_list"));
5734 VaListTagDecl->setDeclContext(NS);
5735 } else {
5736 // struct __va_list
5737 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5738 Context->getTranslationUnitDecl(),
5739 &Context->Idents.get("__va_list"));
5740 }
5741
5742 VaListTagDecl->startDefinition();
5743
5744 const size_t NumFields = 5;
5745 QualType FieldTypes[NumFields];
5746 const char *FieldNames[NumFields];
5747
5748 // void *__stack;
5749 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5750 FieldNames[0] = "__stack";
5751
5752 // void *__gr_top;
5753 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5754 FieldNames[1] = "__gr_top";
5755
5756 // void *__vr_top;
5757 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5758 FieldNames[2] = "__vr_top";
5759
5760 // int __gr_offs;
5761 FieldTypes[3] = Context->IntTy;
5762 FieldNames[3] = "__gr_offs";
5763
5764 // int __vr_offs;
5765 FieldTypes[4] = Context->IntTy;
5766 FieldNames[4] = "__vr_offs";
5767
5768 // Create fields
5769 for (unsigned i = 0; i < NumFields; ++i) {
5770 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5771 VaListTagDecl,
5772 SourceLocation(),
5773 SourceLocation(),
5774 &Context->Idents.get(FieldNames[i]),
5775 FieldTypes[i], /*TInfo=*/0,
5776 /*BitWidth=*/0,
5777 /*Mutable=*/false,
5778 ICIS_NoInit);
5779 Field->setAccess(AS_public);
5780 VaListTagDecl->addDecl(Field);
5781 }
5782 VaListTagDecl->completeDefinition();
5783 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5784 Context->VaListTagTy = VaListTagType;
5785
5786 // } __builtin_va_list;
5787 TypedefDecl *VaListTypedefDecl
5788 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5789 Context->getTranslationUnitDecl(),
5790 SourceLocation(), SourceLocation(),
5791 &Context->Idents.get("__builtin_va_list"),
5792 Context->getTrivialTypeSourceInfo(VaListTagType));
5793
5794 return VaListTypedefDecl;
5795}
5796
Meador Ingec5613b22012-06-16 03:34:49 +00005797static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5798 // typedef struct __va_list_tag {
5799 RecordDecl *VaListTagDecl;
5800
5801 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5802 Context->getTranslationUnitDecl(),
5803 &Context->Idents.get("__va_list_tag"));
5804 VaListTagDecl->startDefinition();
5805
5806 const size_t NumFields = 5;
5807 QualType FieldTypes[NumFields];
5808 const char *FieldNames[NumFields];
5809
5810 // unsigned char gpr;
5811 FieldTypes[0] = Context->UnsignedCharTy;
5812 FieldNames[0] = "gpr";
5813
5814 // unsigned char fpr;
5815 FieldTypes[1] = Context->UnsignedCharTy;
5816 FieldNames[1] = "fpr";
5817
5818 // unsigned short reserved;
5819 FieldTypes[2] = Context->UnsignedShortTy;
5820 FieldNames[2] = "reserved";
5821
5822 // void* overflow_arg_area;
5823 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5824 FieldNames[3] = "overflow_arg_area";
5825
5826 // void* reg_save_area;
5827 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5828 FieldNames[4] = "reg_save_area";
5829
5830 // Create fields
5831 for (unsigned i = 0; i < NumFields; ++i) {
5832 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5833 SourceLocation(),
5834 SourceLocation(),
5835 &Context->Idents.get(FieldNames[i]),
5836 FieldTypes[i], /*TInfo=*/0,
5837 /*BitWidth=*/0,
5838 /*Mutable=*/false,
5839 ICIS_NoInit);
5840 Field->setAccess(AS_public);
5841 VaListTagDecl->addDecl(Field);
5842 }
5843 VaListTagDecl->completeDefinition();
5844 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005845 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005846
5847 // } __va_list_tag;
5848 TypedefDecl *VaListTagTypedefDecl
5849 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5850 Context->getTranslationUnitDecl(),
5851 SourceLocation(), SourceLocation(),
5852 &Context->Idents.get("__va_list_tag"),
5853 Context->getTrivialTypeSourceInfo(VaListTagType));
5854 QualType VaListTagTypedefType =
5855 Context->getTypedefType(VaListTagTypedefDecl);
5856
5857 // typedef __va_list_tag __builtin_va_list[1];
5858 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5859 QualType VaListTagArrayType
5860 = Context->getConstantArrayType(VaListTagTypedefType,
5861 Size, ArrayType::Normal, 0);
5862 TypeSourceInfo *TInfo
5863 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5864 TypedefDecl *VaListTypedefDecl
5865 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5866 Context->getTranslationUnitDecl(),
5867 SourceLocation(), SourceLocation(),
5868 &Context->Idents.get("__builtin_va_list"),
5869 TInfo);
5870
5871 return VaListTypedefDecl;
5872}
5873
5874static TypedefDecl *
5875CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5876 // typedef struct __va_list_tag {
5877 RecordDecl *VaListTagDecl;
5878 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5879 Context->getTranslationUnitDecl(),
5880 &Context->Idents.get("__va_list_tag"));
5881 VaListTagDecl->startDefinition();
5882
5883 const size_t NumFields = 4;
5884 QualType FieldTypes[NumFields];
5885 const char *FieldNames[NumFields];
5886
5887 // unsigned gp_offset;
5888 FieldTypes[0] = Context->UnsignedIntTy;
5889 FieldNames[0] = "gp_offset";
5890
5891 // unsigned fp_offset;
5892 FieldTypes[1] = Context->UnsignedIntTy;
5893 FieldNames[1] = "fp_offset";
5894
5895 // void* overflow_arg_area;
5896 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5897 FieldNames[2] = "overflow_arg_area";
5898
5899 // void* reg_save_area;
5900 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5901 FieldNames[3] = "reg_save_area";
5902
5903 // Create fields
5904 for (unsigned i = 0; i < NumFields; ++i) {
5905 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5906 VaListTagDecl,
5907 SourceLocation(),
5908 SourceLocation(),
5909 &Context->Idents.get(FieldNames[i]),
5910 FieldTypes[i], /*TInfo=*/0,
5911 /*BitWidth=*/0,
5912 /*Mutable=*/false,
5913 ICIS_NoInit);
5914 Field->setAccess(AS_public);
5915 VaListTagDecl->addDecl(Field);
5916 }
5917 VaListTagDecl->completeDefinition();
5918 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005919 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005920
5921 // } __va_list_tag;
5922 TypedefDecl *VaListTagTypedefDecl
5923 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5924 Context->getTranslationUnitDecl(),
5925 SourceLocation(), SourceLocation(),
5926 &Context->Idents.get("__va_list_tag"),
5927 Context->getTrivialTypeSourceInfo(VaListTagType));
5928 QualType VaListTagTypedefType =
5929 Context->getTypedefType(VaListTagTypedefDecl);
5930
5931 // typedef __va_list_tag __builtin_va_list[1];
5932 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5933 QualType VaListTagArrayType
5934 = Context->getConstantArrayType(VaListTagTypedefType,
5935 Size, ArrayType::Normal,0);
5936 TypeSourceInfo *TInfo
5937 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5938 TypedefDecl *VaListTypedefDecl
5939 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5940 Context->getTranslationUnitDecl(),
5941 SourceLocation(), SourceLocation(),
5942 &Context->Idents.get("__builtin_va_list"),
5943 TInfo);
5944
5945 return VaListTypedefDecl;
5946}
5947
5948static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5949 // typedef int __builtin_va_list[4];
5950 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5951 QualType IntArrayType
5952 = Context->getConstantArrayType(Context->IntTy,
5953 Size, ArrayType::Normal, 0);
5954 TypedefDecl *VaListTypedefDecl
5955 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5956 Context->getTranslationUnitDecl(),
5957 SourceLocation(), SourceLocation(),
5958 &Context->Idents.get("__builtin_va_list"),
5959 Context->getTrivialTypeSourceInfo(IntArrayType));
5960
5961 return VaListTypedefDecl;
5962}
5963
Logan Chieneae5a8202012-10-10 06:56:20 +00005964static TypedefDecl *
5965CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5966 RecordDecl *VaListDecl;
5967 if (Context->getLangOpts().CPlusPlus) {
5968 // namespace std { struct __va_list {
5969 NamespaceDecl *NS;
5970 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5971 Context->getTranslationUnitDecl(),
5972 /*Inline*/false, SourceLocation(),
5973 SourceLocation(), &Context->Idents.get("std"),
5974 /*PrevDecl*/0);
5975
5976 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5977 Context->getTranslationUnitDecl(),
5978 SourceLocation(), SourceLocation(),
5979 &Context->Idents.get("__va_list"));
5980
5981 VaListDecl->setDeclContext(NS);
5982
5983 } else {
5984 // struct __va_list {
5985 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
5986 Context->getTranslationUnitDecl(),
5987 &Context->Idents.get("__va_list"));
5988 }
5989
5990 VaListDecl->startDefinition();
5991
5992 // void * __ap;
5993 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5994 VaListDecl,
5995 SourceLocation(),
5996 SourceLocation(),
5997 &Context->Idents.get("__ap"),
5998 Context->getPointerType(Context->VoidTy),
5999 /*TInfo=*/0,
6000 /*BitWidth=*/0,
6001 /*Mutable=*/false,
6002 ICIS_NoInit);
6003 Field->setAccess(AS_public);
6004 VaListDecl->addDecl(Field);
6005
6006 // };
6007 VaListDecl->completeDefinition();
6008
6009 // typedef struct __va_list __builtin_va_list;
6010 TypeSourceInfo *TInfo
6011 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
6012
6013 TypedefDecl *VaListTypeDecl
6014 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6015 Context->getTranslationUnitDecl(),
6016 SourceLocation(), SourceLocation(),
6017 &Context->Idents.get("__builtin_va_list"),
6018 TInfo);
6019
6020 return VaListTypeDecl;
6021}
6022
Ulrich Weigandb8409212013-05-06 16:26:41 +00006023static TypedefDecl *
6024CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6025 // typedef struct __va_list_tag {
6026 RecordDecl *VaListTagDecl;
6027 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
6028 Context->getTranslationUnitDecl(),
6029 &Context->Idents.get("__va_list_tag"));
6030 VaListTagDecl->startDefinition();
6031
6032 const size_t NumFields = 4;
6033 QualType FieldTypes[NumFields];
6034 const char *FieldNames[NumFields];
6035
6036 // long __gpr;
6037 FieldTypes[0] = Context->LongTy;
6038 FieldNames[0] = "__gpr";
6039
6040 // long __fpr;
6041 FieldTypes[1] = Context->LongTy;
6042 FieldNames[1] = "__fpr";
6043
6044 // void *__overflow_arg_area;
6045 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6046 FieldNames[2] = "__overflow_arg_area";
6047
6048 // void *__reg_save_area;
6049 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6050 FieldNames[3] = "__reg_save_area";
6051
6052 // Create fields
6053 for (unsigned i = 0; i < NumFields; ++i) {
6054 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6055 VaListTagDecl,
6056 SourceLocation(),
6057 SourceLocation(),
6058 &Context->Idents.get(FieldNames[i]),
6059 FieldTypes[i], /*TInfo=*/0,
6060 /*BitWidth=*/0,
6061 /*Mutable=*/false,
6062 ICIS_NoInit);
6063 Field->setAccess(AS_public);
6064 VaListTagDecl->addDecl(Field);
6065 }
6066 VaListTagDecl->completeDefinition();
6067 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6068 Context->VaListTagTy = VaListTagType;
6069
6070 // } __va_list_tag;
6071 TypedefDecl *VaListTagTypedefDecl
6072 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6073 Context->getTranslationUnitDecl(),
6074 SourceLocation(), SourceLocation(),
6075 &Context->Idents.get("__va_list_tag"),
6076 Context->getTrivialTypeSourceInfo(VaListTagType));
6077 QualType VaListTagTypedefType =
6078 Context->getTypedefType(VaListTagTypedefDecl);
6079
6080 // typedef __va_list_tag __builtin_va_list[1];
6081 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6082 QualType VaListTagArrayType
6083 = Context->getConstantArrayType(VaListTagTypedefType,
6084 Size, ArrayType::Normal,0);
6085 TypeSourceInfo *TInfo
6086 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
6087 TypedefDecl *VaListTypedefDecl
6088 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6089 Context->getTranslationUnitDecl(),
6090 SourceLocation(), SourceLocation(),
6091 &Context->Idents.get("__builtin_va_list"),
6092 TInfo);
6093
6094 return VaListTypedefDecl;
6095}
6096
Meador Ingec5613b22012-06-16 03:34:49 +00006097static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6098 TargetInfo::BuiltinVaListKind Kind) {
6099 switch (Kind) {
6100 case TargetInfo::CharPtrBuiltinVaList:
6101 return CreateCharPtrBuiltinVaListDecl(Context);
6102 case TargetInfo::VoidPtrBuiltinVaList:
6103 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northoverc264e162013-01-31 12:13:10 +00006104 case TargetInfo::AArch64ABIBuiltinVaList:
6105 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00006106 case TargetInfo::PowerABIBuiltinVaList:
6107 return CreatePowerABIBuiltinVaListDecl(Context);
6108 case TargetInfo::X86_64ABIBuiltinVaList:
6109 return CreateX86_64ABIBuiltinVaListDecl(Context);
6110 case TargetInfo::PNaClABIBuiltinVaList:
6111 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chieneae5a8202012-10-10 06:56:20 +00006112 case TargetInfo::AAPCSABIBuiltinVaList:
6113 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigandb8409212013-05-06 16:26:41 +00006114 case TargetInfo::SystemZBuiltinVaList:
6115 return CreateSystemZBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00006116 }
6117
6118 llvm_unreachable("Unhandled __builtin_va_list type kind");
6119}
6120
6121TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6122 if (!BuiltinVaListDecl)
6123 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6124
6125 return BuiltinVaListDecl;
6126}
6127
Meador Ingefb40e3f2012-07-01 15:57:25 +00006128QualType ASTContext::getVaListTagType() const {
6129 // Force the creation of VaListTagTy by building the __builtin_va_list
6130 // declaration.
6131 if (VaListTagTy.isNull())
6132 (void) getBuiltinVaListDecl();
6133
6134 return VaListTagTy;
6135}
6136
Ted Kremeneka526c5c2008-01-07 19:49:32 +00006137void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00006138 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00006139 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00006140
Ted Kremeneka526c5c2008-01-07 19:49:32 +00006141 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00006142}
6143
John McCall0bd6feb2009-12-02 08:04:21 +00006144/// \brief Retrieve the template name that corresponds to a non-empty
6145/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00006146TemplateName
6147ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6148 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00006149 unsigned size = End - Begin;
6150 assert(size > 1 && "set is not overloaded!");
6151
6152 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6153 size * sizeof(FunctionTemplateDecl*));
6154 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6155
6156 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00006157 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00006158 NamedDecl *D = *I;
6159 assert(isa<FunctionTemplateDecl>(D) ||
6160 (isa<UsingShadowDecl>(D) &&
6161 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6162 *Storage++ = D;
6163 }
6164
6165 return TemplateName(OT);
6166}
6167
Douglas Gregor7532dc62009-03-30 22:58:21 +00006168/// \brief Retrieve the template name that represents a qualified
6169/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00006170TemplateName
6171ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6172 bool TemplateKeyword,
6173 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00006174 assert(NNS && "Missing nested-name-specifier in qualified template name");
6175
Douglas Gregor789b1f62010-02-04 18:10:26 +00006176 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00006177 llvm::FoldingSetNodeID ID;
6178 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6179
6180 void *InsertPos = 0;
6181 QualifiedTemplateName *QTN =
6182 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6183 if (!QTN) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006184 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6185 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregor7532dc62009-03-30 22:58:21 +00006186 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6187 }
6188
6189 return TemplateName(QTN);
6190}
6191
6192/// \brief Retrieve the template name that represents a dependent
6193/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00006194TemplateName
6195ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6196 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00006197 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00006198 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00006199
6200 llvm::FoldingSetNodeID ID;
6201 DependentTemplateName::Profile(ID, NNS, Name);
6202
6203 void *InsertPos = 0;
6204 DependentTemplateName *QTN =
6205 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6206
6207 if (QTN)
6208 return TemplateName(QTN);
6209
6210 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6211 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006212 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6213 DependentTemplateName(NNS, Name);
Douglas Gregor7532dc62009-03-30 22:58:21 +00006214 } else {
6215 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smith2f47cab2012-08-16 01:19:31 +00006216 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6217 DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00006218 DependentTemplateName *CheckQTN =
6219 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6220 assert(!CheckQTN && "Dependent type name canonicalization broken");
6221 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00006222 }
6223
6224 DependentTemplateNames.InsertNode(QTN, InsertPos);
6225 return TemplateName(QTN);
6226}
6227
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006228/// \brief Retrieve the template name that represents a dependent
6229/// template name such as \c MetaFun::template operator+.
6230TemplateName
6231ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00006232 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006233 assert((!NNS || NNS->isDependent()) &&
6234 "Nested name specifier must be dependent");
6235
6236 llvm::FoldingSetNodeID ID;
6237 DependentTemplateName::Profile(ID, NNS, Operator);
6238
6239 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00006240 DependentTemplateName *QTN
6241 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006242
6243 if (QTN)
6244 return TemplateName(QTN);
6245
6246 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6247 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006248 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6249 DependentTemplateName(NNS, Operator);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006250 } else {
6251 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smith2f47cab2012-08-16 01:19:31 +00006252 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6253 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00006254
6255 DependentTemplateName *CheckQTN
6256 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6257 assert(!CheckQTN && "Dependent template name canonicalization broken");
6258 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006259 }
6260
6261 DependentTemplateNames.InsertNode(QTN, InsertPos);
6262 return TemplateName(QTN);
6263}
6264
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006265TemplateName
John McCall14606042011-06-30 08:33:18 +00006266ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6267 TemplateName replacement) const {
6268 llvm::FoldingSetNodeID ID;
6269 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6270
6271 void *insertPos = 0;
6272 SubstTemplateTemplateParmStorage *subst
6273 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6274
6275 if (!subst) {
6276 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6277 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6278 }
6279
6280 return TemplateName(subst);
6281}
6282
6283TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006284ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6285 const TemplateArgument &ArgPack) const {
6286 ASTContext &Self = const_cast<ASTContext &>(*this);
6287 llvm::FoldingSetNodeID ID;
6288 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6289
6290 void *InsertPos = 0;
6291 SubstTemplateTemplateParmPackStorage *Subst
6292 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6293
6294 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00006295 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006296 ArgPack.pack_size(),
6297 ArgPack.pack_begin());
6298 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6299 }
6300
6301 return TemplateName(Subst);
6302}
6303
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006304/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00006305/// TargetInfo, produce the corresponding type. The unsigned @p Type
6306/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00006307CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006308 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00006309 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006310 case TargetInfo::SignedShort: return ShortTy;
6311 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6312 case TargetInfo::SignedInt: return IntTy;
6313 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6314 case TargetInfo::SignedLong: return LongTy;
6315 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6316 case TargetInfo::SignedLongLong: return LongLongTy;
6317 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6318 }
6319
David Blaikieb219cfc2011-09-23 05:06:16 +00006320 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006321}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00006322
6323//===----------------------------------------------------------------------===//
6324// Type Predicates.
6325//===----------------------------------------------------------------------===//
6326
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006327/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6328/// garbage collection attribute.
6329///
John McCallae278a32011-01-12 00:34:59 +00006330Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006331 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00006332 return Qualifiers::GCNone;
6333
David Blaikie4e4d0842012-03-11 07:00:24 +00006334 assert(getLangOpts().ObjC1);
John McCallae278a32011-01-12 00:34:59 +00006335 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6336
6337 // Default behaviour under objective-C's gc is for ObjC pointers
6338 // (or pointers to them) be treated as though they were declared
6339 // as __strong.
6340 if (GCAttrs == Qualifiers::GCNone) {
6341 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6342 return Qualifiers::Strong;
6343 else if (Ty->isPointerType())
6344 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6345 } else {
6346 // It's not valid to set GC attributes on anything that isn't a
6347 // pointer.
6348#ifndef NDEBUG
6349 QualType CT = Ty->getCanonicalTypeInternal();
6350 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6351 CT = AT->getElementType();
6352 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6353#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006354 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00006355 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006356}
6357
Chris Lattner6ac46a42008-04-07 06:51:04 +00006358//===----------------------------------------------------------------------===//
6359// Type Compatibility Testing
6360//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00006361
Mike Stump1eb44332009-09-09 15:08:12 +00006362/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006363/// compatible.
6364static bool areCompatVectorTypes(const VectorType *LHS,
6365 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00006366 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00006367 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00006368 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00006369}
6370
Douglas Gregor255210e2010-08-06 10:14:59 +00006371bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6372 QualType SecondVec) {
6373 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6374 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6375
6376 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6377 return true;
6378
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006379 // Treat Neon vector types and most AltiVec vector types as if they are the
6380 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00006381 const VectorType *First = FirstVec->getAs<VectorType>();
6382 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006383 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00006384 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006385 First->getVectorKind() != VectorType::AltiVecPixel &&
6386 First->getVectorKind() != VectorType::AltiVecBool &&
6387 Second->getVectorKind() != VectorType::AltiVecPixel &&
6388 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00006389 return true;
6390
6391 return false;
6392}
6393
Steve Naroff4084c302009-07-23 01:01:38 +00006394//===----------------------------------------------------------------------===//
6395// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6396//===----------------------------------------------------------------------===//
6397
6398/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6399/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00006400bool
6401ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6402 ObjCProtocolDecl *rProto) const {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00006403 if (declaresSameEntity(lProto, rProto))
Steve Naroff4084c302009-07-23 01:01:38 +00006404 return true;
6405 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6406 E = rProto->protocol_end(); PI != E; ++PI)
6407 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6408 return true;
6409 return false;
6410}
6411
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00006412/// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
Steve Naroff4084c302009-07-23 01:01:38 +00006413/// return true if lhs's protocols conform to rhs's protocol; false
6414/// otherwise.
6415bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
6416 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
6417 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
6418 return false;
6419}
6420
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00006421/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6422/// Class<pr1, ...>.
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006423bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6424 QualType rhs) {
6425 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6426 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6427 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6428
6429 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6430 E = lhsQID->qual_end(); I != E; ++I) {
6431 bool match = false;
6432 ObjCProtocolDecl *lhsProto = *I;
6433 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6434 E = rhsOPT->qual_end(); J != E; ++J) {
6435 ObjCProtocolDecl *rhsProto = *J;
6436 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6437 match = true;
6438 break;
6439 }
6440 }
6441 if (!match)
6442 return false;
6443 }
6444 return true;
6445}
6446
Steve Naroff4084c302009-07-23 01:01:38 +00006447/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6448/// ObjCQualifiedIDType.
6449bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6450 bool compare) {
6451 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00006452 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006453 lhs->isObjCIdType() || lhs->isObjCClassType())
6454 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006455 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006456 rhs->isObjCIdType() || rhs->isObjCClassType())
6457 return true;
6458
6459 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00006460 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006461
Steve Naroff4084c302009-07-23 01:01:38 +00006462 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006463
Steve Naroff4084c302009-07-23 01:01:38 +00006464 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006465 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00006466 // make sure we check the class hierarchy.
6467 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6468 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6469 E = lhsQID->qual_end(); I != E; ++I) {
6470 // when comparing an id<P> on lhs with a static type on rhs,
6471 // see if static class implements all of id's protocols, directly or
6472 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006473 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00006474 return false;
6475 }
6476 }
6477 // If there are no qualifiers and no interface, we have an 'id'.
6478 return true;
6479 }
Mike Stump1eb44332009-09-09 15:08:12 +00006480 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006481 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6482 E = lhsQID->qual_end(); I != E; ++I) {
6483 ObjCProtocolDecl *lhsProto = *I;
6484 bool match = false;
6485
6486 // when comparing an id<P> on lhs with a static type on rhs,
6487 // see if static class implements all of id's protocols, directly or
6488 // through its super class and categories.
6489 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6490 E = rhsOPT->qual_end(); J != E; ++J) {
6491 ObjCProtocolDecl *rhsProto = *J;
6492 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6493 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6494 match = true;
6495 break;
6496 }
6497 }
Mike Stump1eb44332009-09-09 15:08:12 +00006498 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00006499 // make sure we check the class hierarchy.
6500 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6501 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6502 E = lhsQID->qual_end(); I != E; ++I) {
6503 // when comparing an id<P> on lhs with a static type on rhs,
6504 // see if static class implements all of id's protocols, directly or
6505 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006506 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00006507 match = true;
6508 break;
6509 }
6510 }
6511 }
6512 if (!match)
6513 return false;
6514 }
Mike Stump1eb44332009-09-09 15:08:12 +00006515
Steve Naroff4084c302009-07-23 01:01:38 +00006516 return true;
6517 }
Mike Stump1eb44332009-09-09 15:08:12 +00006518
Steve Naroff4084c302009-07-23 01:01:38 +00006519 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6520 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6521
Mike Stump1eb44332009-09-09 15:08:12 +00006522 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00006523 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006524 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006525 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6526 E = lhsOPT->qual_end(); I != E; ++I) {
6527 ObjCProtocolDecl *lhsProto = *I;
6528 bool match = false;
6529
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006530 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00006531 // see if static class implements all of id's protocols, directly or
6532 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006533 // First, lhs protocols in the qualifier list must be found, direct
6534 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00006535 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6536 E = rhsQID->qual_end(); J != E; ++J) {
6537 ObjCProtocolDecl *rhsProto = *J;
6538 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6539 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6540 match = true;
6541 break;
6542 }
6543 }
6544 if (!match)
6545 return false;
6546 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006547
6548 // Static class's protocols, or its super class or category protocols
6549 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6550 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6551 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6552 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6553 // This is rather dubious but matches gcc's behavior. If lhs has
6554 // no type qualifier and its class has no static protocol(s)
6555 // assume that it is mismatch.
6556 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6557 return false;
6558 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6559 LHSInheritedProtocols.begin(),
6560 E = LHSInheritedProtocols.end(); I != E; ++I) {
6561 bool match = false;
6562 ObjCProtocolDecl *lhsProto = (*I);
6563 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6564 E = rhsQID->qual_end(); J != E; ++J) {
6565 ObjCProtocolDecl *rhsProto = *J;
6566 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6567 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6568 match = true;
6569 break;
6570 }
6571 }
6572 if (!match)
6573 return false;
6574 }
6575 }
Steve Naroff4084c302009-07-23 01:01:38 +00006576 return true;
6577 }
6578 return false;
6579}
6580
Eli Friedman3d815e72008-08-22 00:56:42 +00006581/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006582/// compatible for assignment from RHS to LHS. This handles validation of any
6583/// protocol qualifiers on the LHS or RHS.
6584///
Steve Naroff14108da2009-07-10 23:34:53 +00006585bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6586 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00006587 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6588 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6589
Steve Naroffde2e22d2009-07-15 18:40:39 +00006590 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00006591 if (LHS->isObjCUnqualifiedIdOrClass() ||
6592 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00006593 return true;
6594
John McCallc12c5bb2010-05-15 11:32:37 +00006595 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00006596 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6597 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00006598 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006599
6600 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6601 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6602 QualType(RHSOPT,0));
6603
John McCallc12c5bb2010-05-15 11:32:37 +00006604 // If we have 2 user-defined types, fall into that path.
6605 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00006606 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006607
Steve Naroff4084c302009-07-23 01:01:38 +00006608 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006609}
6610
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006611/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00006612/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006613/// arguments in block literals. When passed as arguments, passing 'A*' where
6614/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6615/// not OK. For the return type, the opposite is not OK.
6616bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6617 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006618 const ObjCObjectPointerType *RHSOPT,
6619 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006620 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006621 return true;
6622
6623 if (LHSOPT->isObjCBuiltinType()) {
6624 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6625 }
6626
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006627 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006628 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6629 QualType(RHSOPT,0),
6630 false);
6631
6632 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6633 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6634 if (LHS && RHS) { // We have 2 user-defined types.
6635 if (LHS != RHS) {
6636 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006637 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006638 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006639 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006640 }
6641 else
6642 return true;
6643 }
6644 return false;
6645}
6646
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006647/// getIntersectionOfProtocols - This routine finds the intersection of set
6648/// of protocols inherited from two distinct objective-c pointer objects.
6649/// It is used to build composite qualifier list of the composite type of
6650/// the conditional expression involving two objective-c pointer objects.
6651static
6652void getIntersectionOfProtocols(ASTContext &Context,
6653 const ObjCObjectPointerType *LHSOPT,
6654 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006655 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006656
John McCallc12c5bb2010-05-15 11:32:37 +00006657 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6658 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6659 assert(LHS->getInterface() && "LHS must have an interface base");
6660 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006661
6662 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6663 unsigned LHSNumProtocols = LHS->getNumProtocols();
6664 if (LHSNumProtocols > 0)
6665 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6666 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006667 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006668 Context.CollectInheritedProtocols(LHS->getInterface(),
6669 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006670 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6671 LHSInheritedProtocols.end());
6672 }
6673
6674 unsigned RHSNumProtocols = RHS->getNumProtocols();
6675 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00006676 ObjCProtocolDecl **RHSProtocols =
6677 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006678 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6679 if (InheritedProtocolSet.count(RHSProtocols[i]))
6680 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00006681 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006682 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006683 Context.CollectInheritedProtocols(RHS->getInterface(),
6684 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006685 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6686 RHSInheritedProtocols.begin(),
6687 E = RHSInheritedProtocols.end(); I != E; ++I)
6688 if (InheritedProtocolSet.count((*I)))
6689 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006690 }
6691}
6692
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006693/// areCommonBaseCompatible - Returns common base class of the two classes if
6694/// one found. Note that this is O'2 algorithm. But it will be called as the
6695/// last type comparison in a ?-exp of ObjC pointer types before a
6696/// warning is issued. So, its invokation is extremely rare.
6697QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00006698 const ObjCObjectPointerType *Lptr,
6699 const ObjCObjectPointerType *Rptr) {
6700 const ObjCObjectType *LHS = Lptr->getObjectType();
6701 const ObjCObjectType *RHS = Rptr->getObjectType();
6702 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6703 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor60ef3082011-12-15 00:29:59 +00006704 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006705 return QualType();
6706
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006707 do {
John McCallc12c5bb2010-05-15 11:32:37 +00006708 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006709 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006710 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006711 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6712
6713 QualType Result = QualType(LHS, 0);
6714 if (!Protocols.empty())
6715 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6716 Result = getObjCObjectPointerType(Result);
6717 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006718 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006719 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006720
6721 return QualType();
6722}
6723
John McCallc12c5bb2010-05-15 11:32:37 +00006724bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6725 const ObjCObjectType *RHS) {
6726 assert(LHS->getInterface() && "LHS is not an interface type");
6727 assert(RHS->getInterface() && "RHS is not an interface type");
6728
Chris Lattner6ac46a42008-04-07 06:51:04 +00006729 // Verify that the base decls are compatible: the RHS must be a subclass of
6730 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00006731 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00006732 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006733
Chris Lattner6ac46a42008-04-07 06:51:04 +00006734 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6735 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00006736 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00006737 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006738
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006739 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6740 // more detailed analysis is required.
6741 if (RHS->getNumProtocols() == 0) {
6742 // OK, if LHS is a superclass of RHS *and*
6743 // this superclass is assignment compatible with LHS.
6744 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006745 bool IsSuperClass =
6746 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6747 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006748 // OK if conversion of LHS to SuperClass results in narrowing of types
6749 // ; i.e., SuperClass may implement at least one of the protocols
6750 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6751 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6752 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006753 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006754 // If super class has no protocols, it is not a match.
6755 if (SuperClassInheritedProtocols.empty())
6756 return false;
6757
6758 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6759 LHSPE = LHS->qual_end();
6760 LHSPI != LHSPE; LHSPI++) {
6761 bool SuperImplementsProtocol = false;
6762 ObjCProtocolDecl *LHSProto = (*LHSPI);
6763
6764 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6765 SuperClassInheritedProtocols.begin(),
6766 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6767 ObjCProtocolDecl *SuperClassProto = (*I);
6768 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6769 SuperImplementsProtocol = true;
6770 break;
6771 }
6772 }
6773 if (!SuperImplementsProtocol)
6774 return false;
6775 }
6776 return true;
6777 }
6778 return false;
6779 }
Mike Stump1eb44332009-09-09 15:08:12 +00006780
John McCallc12c5bb2010-05-15 11:32:37 +00006781 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6782 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006783 LHSPI != LHSPE; LHSPI++) {
6784 bool RHSImplementsProtocol = false;
6785
6786 // If the RHS doesn't implement the protocol on the left, the types
6787 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00006788 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6789 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00006790 RHSPI != RHSPE; RHSPI++) {
6791 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006792 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00006793 break;
6794 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006795 }
6796 // FIXME: For better diagnostics, consider passing back the protocol name.
6797 if (!RHSImplementsProtocol)
6798 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006799 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006800 // The RHS implements all protocols listed on the LHS.
6801 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006802}
6803
Steve Naroff389bf462009-02-12 17:52:19 +00006804bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6805 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00006806 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6807 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006808
Steve Naroff14108da2009-07-10 23:34:53 +00006809 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00006810 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006811
6812 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6813 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00006814}
6815
Douglas Gregor569c3162010-08-07 11:51:51 +00006816bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6817 return canAssignObjCInterfaces(
6818 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6819 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6820}
6821
Mike Stump1eb44332009-09-09 15:08:12 +00006822/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00006823/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00006824/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00006825/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00006826bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6827 bool CompareUnqualified) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006828 if (getLangOpts().CPlusPlus)
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006829 return hasSameType(LHS, RHS);
6830
Douglas Gregor447234d2010-07-29 15:18:02 +00006831 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00006832}
6833
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006834bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00006835 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006836}
6837
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006838bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6839 return !mergeTypes(LHS, RHS, true).isNull();
6840}
6841
Peter Collingbourne48466752010-10-24 18:30:18 +00006842/// mergeTransparentUnionType - if T is a transparent union type and a member
6843/// of T is compatible with SubType, return the merged type, else return
6844/// QualType()
6845QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6846 bool OfBlockPointer,
6847 bool Unqualified) {
6848 if (const RecordType *UT = T->getAsUnionType()) {
6849 RecordDecl *UD = UT->getDecl();
6850 if (UD->hasAttr<TransparentUnionAttr>()) {
6851 for (RecordDecl::field_iterator it = UD->field_begin(),
6852 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00006853 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006854 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6855 if (!MT.isNull())
6856 return MT;
6857 }
6858 }
6859 }
6860
6861 return QualType();
6862}
6863
6864/// mergeFunctionArgumentTypes - merge two types which appear as function
6865/// argument types
6866QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6867 bool OfBlockPointer,
6868 bool Unqualified) {
6869 // GNU extension: two types are compatible if they appear as a function
6870 // argument, one of the types is a transparent union type and the other
6871 // type is compatible with a union member
6872 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6873 Unqualified);
6874 if (!lmerge.isNull())
6875 return lmerge;
6876
6877 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6878 Unqualified);
6879 if (!rmerge.isNull())
6880 return rmerge;
6881
6882 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6883}
6884
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006885QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00006886 bool OfBlockPointer,
6887 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00006888 const FunctionType *lbase = lhs->getAs<FunctionType>();
6889 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00006890 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6891 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00006892 bool allLTypes = true;
6893 bool allRTypes = true;
6894
6895 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006896 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006897 if (OfBlockPointer) {
6898 QualType RHS = rbase->getResultType();
6899 QualType LHS = lbase->getResultType();
6900 bool UnqualifiedResult = Unqualified;
6901 if (!UnqualifiedResult)
6902 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006903 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006904 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006905 else
John McCall8cc246c2010-12-15 01:06:38 +00006906 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6907 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006908 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006909
6910 if (Unqualified)
6911 retType = retType.getUnqualifiedType();
6912
6913 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6914 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6915 if (Unqualified) {
6916 LRetType = LRetType.getUnqualifiedType();
6917 RRetType = RRetType.getUnqualifiedType();
6918 }
6919
6920 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006921 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00006922 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006923 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00006924
Daniel Dunbar6a15c852010-04-28 16:20:58 +00006925 // FIXME: double check this
6926 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6927 // rbase->getRegParmAttr() != 0 &&
6928 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00006929 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6930 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00006931
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006932 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00006933 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006934 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006935
John McCall8cc246c2010-12-15 01:06:38 +00006936 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00006937 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6938 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00006939 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6940 return QualType();
6941
John McCallf85e1932011-06-15 23:02:42 +00006942 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6943 return QualType();
6944
John McCall8cc246c2010-12-15 01:06:38 +00006945 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6946 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00006947
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00006948 if (lbaseInfo.getNoReturn() != NoReturn)
6949 allLTypes = false;
6950 if (rbaseInfo.getNoReturn() != NoReturn)
6951 allRTypes = false;
6952
John McCallf85e1932011-06-15 23:02:42 +00006953 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00006954
Eli Friedman3d815e72008-08-22 00:56:42 +00006955 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00006956 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6957 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006958 unsigned lproto_nargs = lproto->getNumArgs();
6959 unsigned rproto_nargs = rproto->getNumArgs();
6960
6961 // Compatible functions must have the same number of arguments
6962 if (lproto_nargs != rproto_nargs)
6963 return QualType();
6964
6965 // Variadic and non-variadic functions aren't compatible
6966 if (lproto->isVariadic() != rproto->isVariadic())
6967 return QualType();
6968
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00006969 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6970 return QualType();
6971
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006972 if (LangOpts.ObjCAutoRefCount &&
6973 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6974 return QualType();
6975
Eli Friedman3d815e72008-08-22 00:56:42 +00006976 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00006977 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00006978 for (unsigned i = 0; i < lproto_nargs; i++) {
6979 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6980 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006981 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6982 OfBlockPointer,
6983 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006984 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006985
6986 if (Unqualified)
6987 argtype = argtype.getUnqualifiedType();
6988
Eli Friedman3d815e72008-08-22 00:56:42 +00006989 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00006990 if (Unqualified) {
6991 largtype = largtype.getUnqualifiedType();
6992 rargtype = rargtype.getUnqualifiedType();
6993 }
6994
Chris Lattner61710852008-10-05 17:34:18 +00006995 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6996 allLTypes = false;
6997 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6998 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00006999 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00007000
Eli Friedman3d815e72008-08-22 00:56:42 +00007001 if (allLTypes) return lhs;
7002 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00007003
7004 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7005 EPI.ExtInfo = einfo;
Jordan Rosebea522f2013-03-08 21:51:21 +00007006 return getFunctionType(retType, types, EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00007007 }
7008
7009 if (lproto) allRTypes = false;
7010 if (rproto) allLTypes = false;
7011
Douglas Gregor72564e72009-02-26 23:50:07 +00007012 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00007013 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00007014 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00007015 if (proto->isVariadic()) return QualType();
7016 // Check that the types are compatible with the types that
7017 // would result from default argument promotions (C99 6.7.5.3p15).
7018 // The only types actually affected are promotable integer
7019 // types and floats, which would be passed as a different
7020 // type depending on whether the prototype is visible.
7021 unsigned proto_nargs = proto->getNumArgs();
7022 for (unsigned i = 0; i < proto_nargs; ++i) {
7023 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007024
Eli Friedmanc586d5d2012-08-30 00:44:15 +00007025 // Look at the converted type of enum types, since that is the type used
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007026 // to pass enum values.
Eli Friedmanc586d5d2012-08-30 00:44:15 +00007027 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
7028 argTy = Enum->getDecl()->getIntegerType();
7029 if (argTy.isNull())
7030 return QualType();
7031 }
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007032
Eli Friedman3d815e72008-08-22 00:56:42 +00007033 if (argTy->isPromotableIntegerType() ||
7034 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
7035 return QualType();
7036 }
7037
7038 if (allLTypes) return lhs;
7039 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00007040
7041 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7042 EPI.ExtInfo = einfo;
Jordan Rosebea522f2013-03-08 21:51:21 +00007043 return getFunctionType(retType,
7044 ArrayRef<QualType>(proto->arg_type_begin(),
7045 proto->getNumArgs()),
7046 EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00007047 }
7048
7049 if (allLTypes) return lhs;
7050 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00007051 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00007052}
7053
John McCallb9da7132013-03-21 00:10:07 +00007054/// Given that we have an enum type and a non-enum type, try to merge them.
7055static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7056 QualType other, bool isBlockReturnType) {
7057 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7058 // a signed integer type, or an unsigned integer type.
7059 // Compatibility is based on the underlying type, not the promotion
7060 // type.
7061 QualType underlyingType = ET->getDecl()->getIntegerType();
7062 if (underlyingType.isNull()) return QualType();
7063 if (Context.hasSameType(underlyingType, other))
7064 return other;
7065
7066 // In block return types, we're more permissive and accept any
7067 // integral type of the same size.
7068 if (isBlockReturnType && other->isIntegerType() &&
7069 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7070 return other;
7071
7072 return QualType();
7073}
7074
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007075QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00007076 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00007077 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00007078 // C++ [expr]: If an expression initially has the type "reference to T", the
7079 // type is adjusted to "T" prior to any further analysis, the expression
7080 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00007081 // expression is an lvalue unless the reference is an rvalue reference and
7082 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00007083 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7084 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00007085
7086 if (Unqualified) {
7087 LHS = LHS.getUnqualifiedType();
7088 RHS = RHS.getUnqualifiedType();
7089 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00007090
Eli Friedman3d815e72008-08-22 00:56:42 +00007091 QualType LHSCan = getCanonicalType(LHS),
7092 RHSCan = getCanonicalType(RHS);
7093
7094 // If two types are identical, they are compatible.
7095 if (LHSCan == RHSCan)
7096 return LHS;
7097
John McCall0953e762009-09-24 19:53:00 +00007098 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00007099 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7100 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00007101 if (LQuals != RQuals) {
7102 // If any of these qualifiers are different, we have a type
7103 // mismatch.
7104 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00007105 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7106 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00007107 return QualType();
7108
7109 // Exactly one GC qualifier difference is allowed: __strong is
7110 // okay if the other type has no GC qualifier but is an Objective
7111 // C object pointer (i.e. implicitly strong by default). We fix
7112 // this by pretending that the unqualified type was actually
7113 // qualified __strong.
7114 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7115 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7116 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7117
7118 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7119 return QualType();
7120
7121 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7122 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7123 }
7124 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7125 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7126 }
Eli Friedman3d815e72008-08-22 00:56:42 +00007127 return QualType();
John McCall0953e762009-09-24 19:53:00 +00007128 }
7129
7130 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00007131
Eli Friedman852d63b2009-06-01 01:22:52 +00007132 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7133 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00007134
Chris Lattner1adb8832008-01-14 05:45:46 +00007135 // We want to consider the two function types to be the same for these
7136 // comparisons, just force one to the other.
7137 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7138 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00007139
7140 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00007141 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7142 LHSClass = Type::ConstantArray;
7143 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7144 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00007145
John McCallc12c5bb2010-05-15 11:32:37 +00007146 // ObjCInterfaces are just specialized ObjCObjects.
7147 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7148 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7149
Nate Begeman213541a2008-04-18 23:10:10 +00007150 // Canonicalize ExtVector -> Vector.
7151 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7152 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00007153
Chris Lattnera36a61f2008-04-07 05:43:21 +00007154 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00007155 if (LHSClass != RHSClass) {
John McCallb9da7132013-03-21 00:10:07 +00007156 // Note that we only have special rules for turning block enum
7157 // returns into block int returns, not vice-versa.
John McCall183700f2009-09-21 23:43:11 +00007158 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCallb9da7132013-03-21 00:10:07 +00007159 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmanbab96962008-02-12 08:46:17 +00007160 }
John McCall183700f2009-09-21 23:43:11 +00007161 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCallb9da7132013-03-21 00:10:07 +00007162 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmanbab96962008-02-12 08:46:17 +00007163 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00007164 // allow block pointer type to match an 'id' type.
Fariborz Jahanian41963632012-01-26 17:08:50 +00007165 if (OfBlockPointer && !BlockReturnType) {
7166 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7167 return LHS;
7168 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7169 return RHS;
7170 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00007171
Eli Friedman3d815e72008-08-22 00:56:42 +00007172 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00007173 }
Eli Friedman3d815e72008-08-22 00:56:42 +00007174
Steve Naroff4a746782008-01-09 22:43:08 +00007175 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00007176 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00007177#define TYPE(Class, Base)
7178#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00007179#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00007180#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7181#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7182#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00007183 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00007184
Richard Smithdc7a4f52013-04-30 13:56:41 +00007185 case Type::Auto:
Sebastian Redl7c80bd62009-03-16 23:22:08 +00007186 case Type::LValueReference:
7187 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00007188 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00007189 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00007190
John McCallc12c5bb2010-05-15 11:32:37 +00007191 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00007192 case Type::IncompleteArray:
7193 case Type::VariableArray:
7194 case Type::FunctionProto:
7195 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00007196 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00007197
Chris Lattner1adb8832008-01-14 05:45:46 +00007198 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00007199 {
7200 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00007201 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7202 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007203 if (Unqualified) {
7204 LHSPointee = LHSPointee.getUnqualifiedType();
7205 RHSPointee = RHSPointee.getUnqualifiedType();
7206 }
7207 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7208 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00007209 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00007210 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00007211 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00007212 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00007213 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00007214 return getPointerType(ResultType);
7215 }
Steve Naroffc0febd52008-12-10 17:49:55 +00007216 case Type::BlockPointer:
7217 {
7218 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00007219 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7220 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007221 if (Unqualified) {
7222 LHSPointee = LHSPointee.getUnqualifiedType();
7223 RHSPointee = RHSPointee.getUnqualifiedType();
7224 }
7225 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7226 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00007227 if (ResultType.isNull()) return QualType();
7228 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7229 return LHS;
7230 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7231 return RHS;
7232 return getBlockPointerType(ResultType);
7233 }
Eli Friedmanb001de72011-10-06 23:00:33 +00007234 case Type::Atomic:
7235 {
7236 // Merge two pointer types, while trying to preserve typedef info
7237 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7238 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7239 if (Unqualified) {
7240 LHSValue = LHSValue.getUnqualifiedType();
7241 RHSValue = RHSValue.getUnqualifiedType();
7242 }
7243 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7244 Unqualified);
7245 if (ResultType.isNull()) return QualType();
7246 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7247 return LHS;
7248 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7249 return RHS;
7250 return getAtomicType(ResultType);
7251 }
Chris Lattner1adb8832008-01-14 05:45:46 +00007252 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00007253 {
7254 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7255 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7256 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7257 return QualType();
7258
7259 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7260 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007261 if (Unqualified) {
7262 LHSElem = LHSElem.getUnqualifiedType();
7263 RHSElem = RHSElem.getUnqualifiedType();
7264 }
7265
7266 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00007267 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00007268 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7269 return LHS;
7270 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7271 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00007272 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7273 ArrayType::ArraySizeModifier(), 0);
7274 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7275 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00007276 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7277 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00007278 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7279 return LHS;
7280 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7281 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00007282 if (LVAT) {
7283 // FIXME: This isn't correct! But tricky to implement because
7284 // the array's size has to be the size of LHS, but the type
7285 // has to be different.
7286 return LHS;
7287 }
7288 if (RVAT) {
7289 // FIXME: This isn't correct! But tricky to implement because
7290 // the array's size has to be the size of RHS, but the type
7291 // has to be different.
7292 return RHS;
7293 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00007294 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7295 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00007296 return getIncompleteArrayType(ResultType,
7297 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00007298 }
Chris Lattner1adb8832008-01-14 05:45:46 +00007299 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00007300 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00007301 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00007302 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00007303 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00007304 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00007305 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00007306 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00007307 case Type::Complex:
7308 // Distinct complex types are incompatible.
7309 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00007310 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00007311 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00007312 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7313 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00007314 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00007315 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00007316 case Type::ObjCObject: {
7317 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00007318 // FIXME: This should be type compatibility, e.g. whether
7319 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00007320 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7321 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7322 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00007323 return LHS;
7324
Eli Friedman3d815e72008-08-22 00:56:42 +00007325 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00007326 }
Steve Naroff14108da2009-07-10 23:34:53 +00007327 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007328 if (OfBlockPointer) {
7329 if (canAssignObjCInterfacesInBlockPointer(
7330 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00007331 RHS->getAs<ObjCObjectPointerType>(),
7332 BlockReturnType))
David Blaikie7530c032012-01-17 06:56:22 +00007333 return LHS;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007334 return QualType();
7335 }
John McCall183700f2009-09-21 23:43:11 +00007336 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7337 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00007338 return LHS;
7339
Steve Naroffbc76dd02008-12-10 22:14:21 +00007340 return QualType();
David Blaikie7530c032012-01-17 06:56:22 +00007341 }
Steve Naroffec0550f2007-10-15 20:41:53 +00007342 }
Douglas Gregor72564e72009-02-26 23:50:07 +00007343
David Blaikie7530c032012-01-17 06:56:22 +00007344 llvm_unreachable("Invalid Type::Class!");
Steve Naroffec0550f2007-10-15 20:41:53 +00007345}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00007346
Fariborz Jahanian78213e42011-09-28 21:52:05 +00007347bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7348 const FunctionProtoType *FromFunctionType,
7349 const FunctionProtoType *ToFunctionType) {
7350 if (FromFunctionType->hasAnyConsumedArgs() !=
7351 ToFunctionType->hasAnyConsumedArgs())
7352 return false;
7353 FunctionProtoType::ExtProtoInfo FromEPI =
7354 FromFunctionType->getExtProtoInfo();
7355 FunctionProtoType::ExtProtoInfo ToEPI =
7356 ToFunctionType->getExtProtoInfo();
7357 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
7358 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
7359 ArgIdx != NumArgs; ++ArgIdx) {
7360 if (FromEPI.ConsumedArguments[ArgIdx] !=
7361 ToEPI.ConsumedArguments[ArgIdx])
7362 return false;
7363 }
7364 return true;
7365}
7366
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007367/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7368/// 'RHS' attributes and returns the merged version; including for function
7369/// return types.
7370QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7371 QualType LHSCan = getCanonicalType(LHS),
7372 RHSCan = getCanonicalType(RHS);
7373 // If two types are identical, they are compatible.
7374 if (LHSCan == RHSCan)
7375 return LHS;
7376 if (RHSCan->isFunctionType()) {
7377 if (!LHSCan->isFunctionType())
7378 return QualType();
7379 QualType OldReturnType =
7380 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7381 QualType NewReturnType =
7382 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7383 QualType ResReturnType =
7384 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7385 if (ResReturnType.isNull())
7386 return QualType();
7387 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7388 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7389 // In either case, use OldReturnType to build the new function type.
7390 const FunctionType *F = LHS->getAs<FunctionType>();
7391 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00007392 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7393 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007394 QualType ResultType
Jordan Rosebea522f2013-03-08 21:51:21 +00007395 = getFunctionType(OldReturnType,
7396 ArrayRef<QualType>(FPT->arg_type_begin(),
7397 FPT->getNumArgs()),
7398 EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007399 return ResultType;
7400 }
7401 }
7402 return QualType();
7403 }
7404
7405 // If the qualifiers are different, the types can still be merged.
7406 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7407 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7408 if (LQuals != RQuals) {
7409 // If any of these qualifiers are different, we have a type mismatch.
7410 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7411 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7412 return QualType();
7413
7414 // Exactly one GC qualifier difference is allowed: __strong is
7415 // okay if the other type has no GC qualifier but is an Objective
7416 // C object pointer (i.e. implicitly strong by default). We fix
7417 // this by pretending that the unqualified type was actually
7418 // qualified __strong.
7419 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7420 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7421 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7422
7423 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7424 return QualType();
7425
7426 if (GC_L == Qualifiers::Strong)
7427 return LHS;
7428 if (GC_R == Qualifiers::Strong)
7429 return RHS;
7430 return QualType();
7431 }
7432
7433 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7434 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7435 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7436 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7437 if (ResQT == LHSBaseQT)
7438 return LHS;
7439 if (ResQT == RHSBaseQT)
7440 return RHS;
7441 }
7442 return QualType();
7443}
7444
Chris Lattner5426bf62008-04-07 07:01:58 +00007445//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00007446// Integer Predicates
7447//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00007448
Jay Foad4ba2a172011-01-12 09:06:06 +00007449unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00007450 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00007451 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007452 if (T->isBooleanType())
7453 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00007454 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00007455 return (unsigned)getTypeSize(T);
7456}
7457
Abramo Bagnara762f1592012-09-09 10:21:24 +00007458QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregorf6094622010-07-23 15:58:24 +00007459 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00007460
7461 // Turn <4 x signed int> -> <4 x unsigned int>
7462 if (const VectorType *VTy = T->getAs<VectorType>())
7463 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00007464 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00007465
7466 // For enums, we return the unsigned version of the base type.
7467 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00007468 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00007469
7470 const BuiltinType *BTy = T->getAs<BuiltinType>();
7471 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007472 switch (BTy->getKind()) {
7473 case BuiltinType::Char_S:
7474 case BuiltinType::SChar:
7475 return UnsignedCharTy;
7476 case BuiltinType::Short:
7477 return UnsignedShortTy;
7478 case BuiltinType::Int:
7479 return UnsignedIntTy;
7480 case BuiltinType::Long:
7481 return UnsignedLongTy;
7482 case BuiltinType::LongLong:
7483 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00007484 case BuiltinType::Int128:
7485 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00007486 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00007487 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007488 }
7489}
7490
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00007491ASTMutationListener::~ASTMutationListener() { }
7492
Richard Smith9dadfab2013-05-11 05:45:24 +00007493void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7494 QualType ReturnType) {}
Chris Lattner86df27b2009-06-14 00:45:47 +00007495
7496//===----------------------------------------------------------------------===//
7497// Builtin Type Computation
7498//===----------------------------------------------------------------------===//
7499
7500/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00007501/// pointer over the consumed characters. This returns the resultant type. If
7502/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7503/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7504/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00007505///
7506/// RequiresICE is filled in on return to indicate whether the value is required
7507/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00007508static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00007509 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00007510 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00007511 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00007512 // Modifiers.
7513 int HowLong = 0;
7514 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00007515 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007516
Chris Lattner33daae62010-10-01 22:42:38 +00007517 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00007518 bool Done = false;
7519 while (!Done) {
7520 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00007521 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007522 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00007523 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007524 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007525 case 'S':
7526 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7527 assert(!Signed && "Can't use 'S' modifier multiple times!");
7528 Signed = true;
7529 break;
7530 case 'U':
7531 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7532 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7533 Unsigned = true;
7534 break;
7535 case 'L':
7536 assert(HowLong <= 2 && "Can't have LLLL modifier");
7537 ++HowLong;
7538 break;
7539 }
7540 }
7541
7542 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00007543
Chris Lattner86df27b2009-06-14 00:45:47 +00007544 // Read the base type.
7545 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00007546 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00007547 case 'v':
7548 assert(HowLong == 0 && !Signed && !Unsigned &&
7549 "Bad modifiers used with 'v'!");
7550 Type = Context.VoidTy;
7551 break;
7552 case 'f':
7553 assert(HowLong == 0 && !Signed && !Unsigned &&
7554 "Bad modifiers used with 'f'!");
7555 Type = Context.FloatTy;
7556 break;
7557 case 'd':
7558 assert(HowLong < 2 && !Signed && !Unsigned &&
7559 "Bad modifiers used with 'd'!");
7560 if (HowLong)
7561 Type = Context.LongDoubleTy;
7562 else
7563 Type = Context.DoubleTy;
7564 break;
7565 case 's':
7566 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7567 if (Unsigned)
7568 Type = Context.UnsignedShortTy;
7569 else
7570 Type = Context.ShortTy;
7571 break;
7572 case 'i':
7573 if (HowLong == 3)
7574 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7575 else if (HowLong == 2)
7576 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7577 else if (HowLong == 1)
7578 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7579 else
7580 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7581 break;
7582 case 'c':
7583 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7584 if (Signed)
7585 Type = Context.SignedCharTy;
7586 else if (Unsigned)
7587 Type = Context.UnsignedCharTy;
7588 else
7589 Type = Context.CharTy;
7590 break;
7591 case 'b': // boolean
7592 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7593 Type = Context.BoolTy;
7594 break;
7595 case 'z': // size_t.
7596 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7597 Type = Context.getSizeType();
7598 break;
7599 case 'F':
7600 Type = Context.getCFConstantStringType();
7601 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00007602 case 'G':
7603 Type = Context.getObjCIdType();
7604 break;
7605 case 'H':
7606 Type = Context.getObjCSelType();
7607 break;
Fariborz Jahanianf7992132013-01-04 18:45:40 +00007608 case 'M':
7609 Type = Context.getObjCSuperType();
7610 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007611 case 'a':
7612 Type = Context.getBuiltinVaListType();
7613 assert(!Type.isNull() && "builtin va list type not initialized!");
7614 break;
7615 case 'A':
7616 // This is a "reference" to a va_list; however, what exactly
7617 // this means depends on how va_list is defined. There are two
7618 // different kinds of va_list: ones passed by value, and ones
7619 // passed by reference. An example of a by-value va_list is
7620 // x86, where va_list is a char*. An example of by-ref va_list
7621 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7622 // we want this argument to be a char*&; for x86-64, we want
7623 // it to be a __va_list_tag*.
7624 Type = Context.getBuiltinVaListType();
7625 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00007626 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00007627 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00007628 else
Chris Lattner86df27b2009-06-14 00:45:47 +00007629 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00007630 break;
7631 case 'V': {
7632 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00007633 unsigned NumElements = strtoul(Str, &End, 10);
7634 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00007635 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00007636
Chris Lattner14e0e742010-10-01 22:53:11 +00007637 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7638 RequiresICE, false);
7639 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00007640
7641 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00007642 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00007643 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00007644 break;
7645 }
Douglas Gregorb4bc99b2012-06-07 18:08:25 +00007646 case 'E': {
7647 char *End;
7648
7649 unsigned NumElements = strtoul(Str, &End, 10);
7650 assert(End != Str && "Missing vector size");
7651
7652 Str = End;
7653
7654 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7655 false);
7656 Type = Context.getExtVectorType(ElementType, NumElements);
7657 break;
7658 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00007659 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00007660 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7661 false);
7662 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00007663 Type = Context.getComplexType(ElementType);
7664 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00007665 }
7666 case 'Y' : {
7667 Type = Context.getPointerDiffType();
7668 break;
7669 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007670 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00007671 Type = Context.getFILEType();
7672 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007673 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00007674 return QualType();
7675 }
Mike Stumpfd612db2009-07-28 23:47:15 +00007676 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007677 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00007678 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00007679 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00007680 else
7681 Type = Context.getjmp_bufType();
7682
Mike Stumpfd612db2009-07-28 23:47:15 +00007683 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007684 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00007685 return QualType();
7686 }
7687 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00007688 case 'K':
7689 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7690 Type = Context.getucontext_tType();
7691
7692 if (Type.isNull()) {
7693 Error = ASTContext::GE_Missing_ucontext;
7694 return QualType();
7695 }
7696 break;
Eli Friedman6902e412012-11-27 02:58:24 +00007697 case 'p':
7698 Type = Context.getProcessIDType();
7699 break;
Mike Stump782fa302009-07-28 02:25:19 +00007700 }
Mike Stump1eb44332009-09-09 15:08:12 +00007701
Chris Lattner33daae62010-10-01 22:42:38 +00007702 // If there are modifiers and if we're allowed to parse them, go for it.
7703 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00007704 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00007705 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00007706 default: Done = true; --Str; break;
7707 case '*':
7708 case '&': {
7709 // Both pointers and references can have their pointee types
7710 // qualified with an address space.
7711 char *End;
7712 unsigned AddrSpace = strtoul(Str, &End, 10);
7713 if (End != Str && AddrSpace != 0) {
7714 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7715 Str = End;
7716 }
7717 if (c == '*')
7718 Type = Context.getPointerType(Type);
7719 else
7720 Type = Context.getLValueReferenceType(Type);
7721 break;
7722 }
7723 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7724 case 'C':
7725 Type = Type.withConst();
7726 break;
7727 case 'D':
7728 Type = Context.getVolatileType(Type);
7729 break;
Ted Kremenek18932a02012-01-20 21:40:12 +00007730 case 'R':
7731 Type = Type.withRestrict();
7732 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007733 }
7734 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00007735
Chris Lattner14e0e742010-10-01 22:53:11 +00007736 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00007737 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00007738
Chris Lattner86df27b2009-06-14 00:45:47 +00007739 return Type;
7740}
7741
7742/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00007743QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00007744 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00007745 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00007746 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00007747
Chris Lattner5f9e2722011-07-23 10:55:15 +00007748 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00007749
Chris Lattner14e0e742010-10-01 22:53:11 +00007750 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00007751 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00007752 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7753 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007754 if (Error != GE_None)
7755 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00007756
7757 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7758
Chris Lattner86df27b2009-06-14 00:45:47 +00007759 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00007760 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007761 if (Error != GE_None)
7762 return QualType();
7763
Chris Lattner14e0e742010-10-01 22:53:11 +00007764 // If this argument is required to be an IntegerConstantExpression and the
7765 // caller cares, fill in the bitmask we return.
7766 if (RequiresICE && IntegerConstantArgs)
7767 *IntegerConstantArgs |= 1 << ArgTypes.size();
7768
Chris Lattner86df27b2009-06-14 00:45:47 +00007769 // Do array -> pointer decay. The builtin should use the decayed type.
7770 if (Ty->isArrayType())
7771 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00007772
Chris Lattner86df27b2009-06-14 00:45:47 +00007773 ArgTypes.push_back(Ty);
7774 }
7775
7776 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7777 "'.' should only occur at end of builtin type list!");
7778
John McCall00ccbef2010-12-21 00:44:39 +00007779 FunctionType::ExtInfo EI;
7780 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7781
7782 bool Variadic = (TypeStr[0] == '.');
7783
7784 // We really shouldn't be making a no-proto type here, especially in C++.
7785 if (ArgTypes.empty() && Variadic)
7786 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00007787
John McCalle23cf432010-12-14 08:05:40 +00007788 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00007789 EPI.ExtInfo = EI;
7790 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00007791
Jordan Rosebea522f2013-03-08 21:51:21 +00007792 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00007793}
Eli Friedmana95d7572009-08-19 07:44:53 +00007794
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007795GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007796 if (!FD->isExternallyVisible())
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007797 return GVA_Internal;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007798
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007799 GVALinkage External = GVA_StrongExternal;
7800 switch (FD->getTemplateSpecializationKind()) {
7801 case TSK_Undeclared:
7802 case TSK_ExplicitSpecialization:
7803 External = GVA_StrongExternal;
7804 break;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007805
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007806 case TSK_ExplicitInstantiationDefinition:
7807 return GVA_ExplicitTemplateInstantiation;
7808
7809 case TSK_ExplicitInstantiationDeclaration:
7810 case TSK_ImplicitInstantiation:
7811 External = GVA_TemplateInstantiation;
7812 break;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007813 }
7814
7815 if (!FD->isInlined())
7816 return External;
7817
David Blaikie4e4d0842012-03-11 07:00:24 +00007818 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007819 // GNU or C99 inline semantics. Determine whether this symbol should be
7820 // externally visible.
7821 if (FD->isInlineDefinitionExternallyVisible())
7822 return External;
7823
7824 // C99 inline semantics, where the symbol is not externally visible.
7825 return GVA_C99Inline;
7826 }
7827
7828 // C++0x [temp.explicit]p9:
7829 // [ Note: The intent is that an inline function that is the subject of
7830 // an explicit instantiation declaration will still be implicitly
7831 // instantiated when used so that the body can be considered for
7832 // inlining, but that no out-of-line copy of the inline function would be
7833 // generated in the translation unit. -- end note ]
7834 if (FD->getTemplateSpecializationKind()
7835 == TSK_ExplicitInstantiationDeclaration)
7836 return GVA_C99Inline;
7837
7838 return GVA_CXXInline;
7839}
7840
7841GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007842 if (!VD->isExternallyVisible())
7843 return GVA_Internal;
7844
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007845 // If this is a static data member, compute the kind of template
7846 // specialization. Otherwise, this variable is not part of a
7847 // template.
7848 TemplateSpecializationKind TSK = TSK_Undeclared;
7849 if (VD->isStaticDataMember())
7850 TSK = VD->getTemplateSpecializationKind();
7851
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007852 switch (TSK) {
7853 case TSK_Undeclared:
7854 case TSK_ExplicitSpecialization:
7855 return GVA_StrongExternal;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007856
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007857 case TSK_ExplicitInstantiationDeclaration:
7858 llvm_unreachable("Variable should not be instantiated");
7859 // Fall through to treat this like any other instantiation.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007860
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007861 case TSK_ExplicitInstantiationDefinition:
7862 return GVA_ExplicitTemplateInstantiation;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007863
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007864 case TSK_ImplicitInstantiation:
7865 return GVA_TemplateInstantiation;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007866 }
Rafael Espindola77b50252013-05-13 14:05:53 +00007867
7868 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007869}
7870
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00007871bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007872 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7873 if (!VD->isFileVarDecl())
7874 return false;
Richard Smithf396ad92013-04-01 20:22:16 +00007875 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7876 // We never need to emit an uninstantiated function template.
7877 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7878 return false;
7879 } else
7880 return false;
7881
7882 // If this is a member of a class template, we do not need to emit it.
7883 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007884 return false;
7885
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007886 // Weak references don't produce any output by themselves.
7887 if (D->hasAttr<WeakRefAttr>())
7888 return false;
7889
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007890 // Aliases and used decls are required.
7891 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7892 return true;
7893
7894 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7895 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00007896 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00007897 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007898
7899 // Constructors and destructors are required.
7900 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7901 return true;
7902
John McCalld5617ee2013-01-25 22:31:03 +00007903 // The key function for a class is required. This rule only comes
7904 // into play when inline functions can be key functions, though.
7905 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7906 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7907 const CXXRecordDecl *RD = MD->getParent();
7908 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7909 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7910 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7911 return true;
7912 }
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007913 }
7914 }
7915
7916 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7917
7918 // static, static inline, always_inline, and extern inline functions can
7919 // always be deferred. Normal inline functions can be deferred in C99/C++.
7920 // Implicit template instantiations can also be deferred in C++.
7921 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev3a5aca82012-02-02 06:06:34 +00007922 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007923 return false;
7924 return true;
7925 }
Douglas Gregor94da1582011-09-10 00:22:34 +00007926
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007927 const VarDecl *VD = cast<VarDecl>(D);
7928 assert(VD->isFileVarDecl() && "Expected file scoped var");
7929
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007930 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7931 return false;
7932
Richard Smith5f9a7e32012-11-12 21:38:00 +00007933 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007934 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smith5f9a7e32012-11-12 21:38:00 +00007935 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7936 return true;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007937
Richard Smith5f9a7e32012-11-12 21:38:00 +00007938 // Variables that have destruction with side-effects are required.
7939 if (VD->getType().isDestructedType())
7940 return true;
7941
7942 // Variables that have initialization with side-effects are required.
7943 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7944 return true;
7945
7946 return false;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007947}
Charles Davis071cc7d2010-08-16 03:33:14 +00007948
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007949CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davisee743f92010-11-09 18:04:24 +00007950 // Pass through to the C++ ABI object
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007951 return ABI->getDefaultMethodCallConv(isVariadic);
7952}
7953
7954CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
John McCallb8b2c9d2013-01-25 22:30:49 +00007955 if (CC == CC_C && !LangOpts.MRTD &&
7956 getTargetInfo().getCXXABI().isMemberFunctionCCDefault())
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007957 return CC_Default;
7958 return CC;
Charles Davisee743f92010-11-09 18:04:24 +00007959}
7960
Jay Foad4ba2a172011-01-12 09:06:06 +00007961bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00007962 // Pass through to the C++ ABI object
7963 return ABI->isNearlyEmpty(RD);
7964}
7965
Peter Collingbourne14110472011-01-13 18:57:25 +00007966MangleContext *ASTContext::createMangleContext() {
John McCallb8b2c9d2013-01-25 22:30:49 +00007967 switch (Target->getCXXABI().getKind()) {
Tim Northoverc264e162013-01-31 12:13:10 +00007968 case TargetCXXABI::GenericAArch64:
John McCallb8b2c9d2013-01-25 22:30:49 +00007969 case TargetCXXABI::GenericItanium:
7970 case TargetCXXABI::GenericARM:
7971 case TargetCXXABI::iOS:
Peter Collingbourne14110472011-01-13 18:57:25 +00007972 return createItaniumMangleContext(*this, getDiagnostics());
John McCallb8b2c9d2013-01-25 22:30:49 +00007973 case TargetCXXABI::Microsoft:
Peter Collingbourne14110472011-01-13 18:57:25 +00007974 return createMicrosoftMangleContext(*this, getDiagnostics());
7975 }
David Blaikieb219cfc2011-09-23 05:06:16 +00007976 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00007977}
7978
Charles Davis071cc7d2010-08-16 03:33:14 +00007979CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00007980
7981size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00007982 return ASTRecordLayouts.getMemorySize()
7983 + llvm::capacity_in_bytes(ObjCLayouts)
7984 + llvm::capacity_in_bytes(KeyFunctions)
7985 + llvm::capacity_in_bytes(ObjCImpls)
7986 + llvm::capacity_in_bytes(BlockVarCopyInits)
7987 + llvm::capacity_in_bytes(DeclAttrs)
7988 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7989 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7990 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7991 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7992 + llvm::capacity_in_bytes(OverriddenMethods)
7993 + llvm::capacity_in_bytes(Types)
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007994 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet0d95f0d2011-08-14 14:28:49 +00007995 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00007996}
Ted Kremenekd211cb72011-10-06 05:00:56 +00007997
David Blaikie66cff722012-11-14 01:52:05 +00007998void ASTContext::addUnnamedTag(const TagDecl *Tag) {
7999 // FIXME: This mangling should be applied to function local classes too
8000 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl() ||
Rafael Espindola5bbb0582013-05-28 14:09:46 +00008001 !isa<CXXRecordDecl>(Tag->getParent()))
David Blaikie66cff722012-11-14 01:52:05 +00008002 return;
8003
8004 std::pair<llvm::DenseMap<const DeclContext *, unsigned>::iterator, bool> P =
8005 UnnamedMangleContexts.insert(std::make_pair(Tag->getParent(), 0));
8006 UnnamedMangleNumbers.insert(std::make_pair(Tag, P.first->second++));
8007}
8008
8009int ASTContext::getUnnamedTagManglingNumber(const TagDecl *Tag) const {
8010 llvm::DenseMap<const TagDecl *, unsigned>::const_iterator I =
8011 UnnamedMangleNumbers.find(Tag);
8012 return I != UnnamedMangleNumbers.end() ? I->second : -1;
8013}
8014
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00008015unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
8016 CXXRecordDecl *Lambda = CallOperator->getParent();
8017 return LambdaMangleContexts[Lambda->getDeclContext()]
8018 .getManglingNumber(CallOperator);
8019}
8020
8021
Ted Kremenekd211cb72011-10-06 05:00:56 +00008022void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8023 ParamIndices[D] = index;
8024}
8025
8026unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8027 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8028 assert(I != ParamIndices.end() &&
8029 "ParmIndices lacks entry set by ParmVarDecl");
8030 return I->second;
8031}
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00008032
8033bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8034 const llvm::Triple &T = getTargetInfo().getTriple();
8035 if (!T.isOSDarwin())
8036 return false;
8037
8038 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8039 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8040 uint64_t Size = sizeChars.getQuantity();
8041 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8042 unsigned Align = alignChars.getQuantity();
8043 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8044 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8045}