blob: 79b8770e0b7b6c5f2ae643eb226b90eee964e830 [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CXXABI.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000018#include "clang/AST/CharUnits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000019#include "clang/AST/Comment.h"
Dmitri Gribenkoca7f80a2012-08-09 00:03:17 +000020#include "clang/AST/CommentCommandTraits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000021#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000022#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000023#include "clang/AST/DeclTemplate.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000024#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000026#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000027#include "clang/AST/Mangle.h"
Reid Klecknerd8110b62013-09-10 20:14:30 +000028#include "clang/AST/MangleNumberingContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000029#include "clang/AST/RecordLayout.h"
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000030#include "clang/AST/RecursiveASTVisitor.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000031#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000032#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000033#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000034#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000035#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000036#include "llvm/ADT/StringExtras.h"
Robert Lyttoneaf6f362013-11-12 10:09:34 +000037#include "llvm/ADT/Triple.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000038#include "llvm/Support/Capacity.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000039#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000040#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000041#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000042
Chris Lattnerddc135e2006-11-10 06:34:16 +000043using namespace clang;
44
Douglas Gregor9672f922010-07-03 00:47:00 +000045unsigned ASTContext::NumImplicitDefaultConstructors;
46unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000047unsigned ASTContext::NumImplicitCopyConstructors;
48unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000049unsigned ASTContext::NumImplicitMoveConstructors;
50unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000051unsigned ASTContext::NumImplicitCopyAssignmentOperators;
52unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000053unsigned ASTContext::NumImplicitMoveAssignmentOperators;
54unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000055unsigned ASTContext::NumImplicitDestructors;
56unsigned ASTContext::NumImplicitDestructorsDeclared;
57
Steve Naroff0af91202007-04-27 21:51:21 +000058enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000059 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000060};
61
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000062RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000063 if (!CommentsLoaded && ExternalSource) {
64 ExternalSource->ReadComments();
65 CommentsLoaded = true;
66 }
67
68 assert(D);
69
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000070 // User can not attach documentation to implicit declarations.
71 if (D->isImplicit())
72 return NULL;
73
Dmitri Gribenkob2610882012-08-14 17:17:18 +000074 // User can not attach documentation to implicit instantiations.
75 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
76 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
77 return NULL;
78 }
79
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000080 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
81 if (VD->isStaticDataMember() &&
82 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
83 return NULL;
84 }
85
86 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
87 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
88 return NULL;
89 }
90
Dmitri Gribenko01b06512013-01-27 21:18:39 +000091 if (const ClassTemplateSpecializationDecl *CTSD =
92 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
93 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
94 if (TSK == TSK_ImplicitInstantiation ||
95 TSK == TSK_Undeclared)
96 return NULL;
97 }
98
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000099 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
100 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
101 return NULL;
102 }
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000103 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
104 // When tag declaration (but not definition!) is part of the
105 // decl-specifier-seq of some other declaration, it doesn't get comment
106 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
107 return NULL;
108 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000109 // TODO: handle comments for function parameters properly.
110 if (isa<ParmVarDecl>(D))
111 return NULL;
112
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000113 // TODO: we could look up template parameter documentation in the template
114 // documentation.
115 if (isa<TemplateTypeParmDecl>(D) ||
116 isa<NonTypeTemplateParmDecl>(D) ||
117 isa<TemplateTemplateParmDecl>(D))
118 return NULL;
119
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000120 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000121
122 // If there are no comments anywhere, we won't find anything.
123 if (RawComments.empty())
124 return NULL;
125
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000126 // Find declaration location.
127 // For Objective-C declarations we generally don't expect to have multiple
128 // declarators, thus use declaration starting location as the "declaration
129 // location".
130 // For all other declarations multiple declarators are used quite frequently,
131 // so we use the location of the identifier as the "declaration location".
132 SourceLocation DeclLoc;
133 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000134 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000135 isa<RedeclarableTemplateDecl>(D) ||
136 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000137 DeclLoc = D->getLocStart();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000138 else {
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000139 DeclLoc = D->getLocation();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000140 // If location of the typedef name is in a macro, it is because being
141 // declared via a macro. Try using declaration's starting location
142 // as the "declaration location".
143 if (DeclLoc.isMacroID() && isa<TypedefDecl>(D))
144 DeclLoc = D->getLocStart();
145 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000146
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000147 // If the declaration doesn't map directly to a location in a file, we
148 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000149 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
150 return NULL;
151
152 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000153 ArrayRef<RawComment *>::iterator Comment;
154 {
155 // When searching for comments during parsing, the comment we are looking
156 // for is usually among the last two comments we parsed -- check them
157 // first.
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000158 RawComment CommentAtDeclLoc(
159 SourceMgr, SourceRange(DeclLoc), false,
160 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000161 BeforeThanCompare<RawComment> Compare(SourceMgr);
162 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
163 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
164 if (!Found && RawComments.size() >= 2) {
165 MaybeBeforeDecl--;
166 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
167 }
168
169 if (Found) {
170 Comment = MaybeBeforeDecl + 1;
171 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
172 &CommentAtDeclLoc, Compare));
173 } else {
174 // Slow path.
175 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
176 &CommentAtDeclLoc, Compare);
177 }
178 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000179
180 // Decompose the location for the declaration and find the beginning of the
181 // file buffer.
182 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
183
184 // First check whether we have a trailing comment.
185 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000186 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Fariborz Jahanianfad28542013-08-06 23:29:00 +0000187 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian3ab62222013-08-07 16:40:29 +0000188 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000189 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000190 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000191 // Check that Doxygen trailing comment comes after the declaration, starts
192 // on the same line and in the same file as the declaration.
193 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
194 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
195 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
196 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000197 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000198 }
199 }
200
201 // The comment just after the declaration was not a trailing comment.
202 // Let's look at the previous comment.
203 if (Comment == RawComments.begin())
204 return NULL;
205 --Comment;
206
207 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000208 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000209 return NULL;
210
211 // Decompose the end of the comment.
212 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000213 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000214
215 // If the comment and the declaration aren't in the same file, then they
216 // aren't related.
217 if (DeclLocDecomp.first != CommentEndDecomp.first)
218 return NULL;
219
220 // Get the corresponding buffer.
221 bool Invalid = false;
222 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
223 &Invalid).data();
224 if (Invalid)
225 return NULL;
226
227 // Extract text between the comment and declaration.
228 StringRef Text(Buffer + CommentEndDecomp.second,
229 DeclLocDecomp.second - CommentEndDecomp.second);
230
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000231 // There should be no other declarations or preprocessor directives between
232 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000233 if (Text.find_first_of(";{}#@") != StringRef::npos)
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000234 return NULL;
235
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000236 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000237}
238
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000239namespace {
240/// If we have a 'templated' declaration for a template, adjust 'D' to
241/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000242/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000243const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000244 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000245 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000246 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000247 return FTD;
248
249 // Nothing to do if function is not an implicit instantiation.
250 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
251 return D;
252
253 // Function is an implicit instantiation of a function template?
254 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
255 return FTD;
256
257 // Function is instantiated from a member definition of a class template?
258 if (const FunctionDecl *MemberDecl =
259 FD->getInstantiatedFromMemberFunction())
260 return MemberDecl;
261
262 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000263 }
Dmitri Gribenko90631802012-08-22 17:44:32 +0000264 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
265 // Static data member is instantiated from a member definition of a class
266 // template?
267 if (VD->isStaticDataMember())
268 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
269 return MemberDecl;
270
271 return D;
272 }
273 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
274 // Is this class declaration part of a class template?
275 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
276 return CTD;
277
278 // Class is an implicit instantiation of a class template or partial
279 // specialization?
280 if (const ClassTemplateSpecializationDecl *CTSD =
281 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
282 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
283 return D;
284 llvm::PointerUnion<ClassTemplateDecl *,
285 ClassTemplatePartialSpecializationDecl *>
286 PU = CTSD->getSpecializedTemplateOrPartial();
287 return PU.is<ClassTemplateDecl*>() ?
288 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
289 static_cast<const Decl*>(
290 PU.get<ClassTemplatePartialSpecializationDecl *>());
291 }
292
293 // Class is instantiated from a member definition of a class template?
294 if (const MemberSpecializationInfo *Info =
295 CRD->getMemberSpecializationInfo())
296 return Info->getInstantiatedFrom();
297
298 return D;
299 }
300 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
301 // Enum is instantiated from a member definition of a class template?
302 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
303 return MemberDecl;
304
305 return D;
306 }
307 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000308 return D;
309}
310} // unnamed namespace
311
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000312const RawComment *ASTContext::getRawCommentForAnyRedecl(
313 const Decl *D,
314 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000315 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000316
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000317 // Check whether we have cached a comment for this declaration already.
318 {
319 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
320 RedeclComments.find(D);
321 if (Pos != RedeclComments.end()) {
322 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000323 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
324 if (OriginalDecl)
325 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000326 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000327 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000328 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000329 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000330
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000331 // Search for comments attached to declarations in the redeclaration chain.
332 const RawComment *RC = NULL;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000333 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000334 for (Decl::redecl_iterator I = D->redecls_begin(),
335 E = D->redecls_end();
336 I != E; ++I) {
337 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
338 RedeclComments.find(*I);
339 if (Pos != RedeclComments.end()) {
340 const RawCommentAndCacheFlags &Raw = Pos->second;
341 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
342 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000343 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000344 break;
345 }
346 } else {
347 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000348 OriginalDeclForRC = *I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000349 RawCommentAndCacheFlags Raw;
350 if (RC) {
351 Raw.setRaw(RC);
352 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
353 } else
354 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000355 Raw.setOriginalDecl(*I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000356 RedeclComments[*I] = Raw;
357 if (RC)
358 break;
359 }
360 }
361
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000362 // If we found a comment, it should be a documentation comment.
363 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000364
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000365 if (OriginalDecl)
366 *OriginalDecl = OriginalDeclForRC;
367
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000368 // Update cache for every declaration in the redeclaration chain.
369 RawCommentAndCacheFlags Raw;
370 Raw.setRaw(RC);
371 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000372 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000373
374 for (Decl::redecl_iterator I = D->redecls_begin(),
375 E = D->redecls_end();
376 I != E; ++I) {
377 RawCommentAndCacheFlags &R = RedeclComments[*I];
378 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
379 R = Raw;
380 }
381
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000382 return RC;
383}
384
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000385static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
386 SmallVectorImpl<const NamedDecl *> &Redeclared) {
387 const DeclContext *DC = ObjCMethod->getDeclContext();
388 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
389 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
390 if (!ID)
391 return;
392 // Add redeclared method here.
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000393 for (ObjCInterfaceDecl::known_extensions_iterator
394 Ext = ID->known_extensions_begin(),
395 ExtEnd = ID->known_extensions_end();
396 Ext != ExtEnd; ++Ext) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000397 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000398 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000399 ObjCMethod->isInstanceMethod()))
400 Redeclared.push_back(RedeclaredMethod);
401 }
402 }
403}
404
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000405comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
406 const Decl *D) const {
407 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
408 ThisDeclInfo->CommentDecl = D;
409 ThisDeclInfo->IsFilled = false;
410 ThisDeclInfo->fill();
411 ThisDeclInfo->CommentDecl = FC->getDecl();
412 comments::FullComment *CFC =
413 new (*this) comments::FullComment(FC->getBlocks(),
414 ThisDeclInfo);
415 return CFC;
416
417}
418
Richard Smithb39b9d52013-05-21 05:24:00 +0000419comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
420 const RawComment *RC = getRawCommentForDeclNoCache(D);
421 return RC ? RC->parse(*this, 0, D) : 0;
422}
423
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000424comments::FullComment *ASTContext::getCommentForDecl(
425 const Decl *D,
426 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000427 if (D->isInvalidDecl())
428 return NULL;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000429 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000430
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000431 const Decl *Canonical = D->getCanonicalDecl();
432 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
433 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000434
435 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000436 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000437 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000438 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000439 return CFC;
440 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000441 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000442 }
443
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000444 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000445
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000446 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000447 if (!RC) {
448 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000449 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000450 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000451 if (OMD && OMD->isPropertyAccessor())
452 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
453 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
454 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000455 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000456 addRedeclaredMethods(OMD, Overridden);
457 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000458 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
459 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
460 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000461 }
Fariborz Jahanian6384fbb2013-05-02 15:44:16 +0000462 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000463 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000464 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000465 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000466 if (const TagType *TT = QT->getAs<TagType>())
467 if (const Decl *TD = TT->getDecl())
468 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000469 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000470 }
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000471 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
472 while (IC->getSuperClass()) {
473 IC = IC->getSuperClass();
474 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
475 return cloneFullComment(FC, D);
476 }
477 }
478 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
479 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
480 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
481 return cloneFullComment(FC, D);
482 }
483 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
484 if (!(RD = RD->getDefinition()))
485 return NULL;
486 // Check non-virtual bases.
487 for (CXXRecordDecl::base_class_const_iterator I =
488 RD->bases_begin(), E = RD->bases_end(); I != E; ++I) {
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000489 if (I->isVirtual() || (I->getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000490 continue;
491 QualType Ty = I->getType();
492 if (Ty.isNull())
493 continue;
494 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
495 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
496 continue;
497
498 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
499 return cloneFullComment(FC, D);
500 }
501 }
502 // Check virtual bases.
503 for (CXXRecordDecl::base_class_const_iterator I =
504 RD->vbases_begin(), E = RD->vbases_end(); I != E; ++I) {
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000505 if (I->getAccessSpecifier() != AS_public)
506 continue;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000507 QualType Ty = I->getType();
508 if (Ty.isNull())
509 continue;
510 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
511 if (!(VirtualBase= VirtualBase->getDefinition()))
512 continue;
513 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
514 return cloneFullComment(FC, D);
515 }
516 }
517 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000518 return NULL;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000519 }
520
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000521 // If the RawComment was attached to other redeclaration of this Decl, we
522 // should parse the comment in context of that other Decl. This is important
523 // because comments can contain references to parameter names which can be
524 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000525 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000526 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000527
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000528 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000529 ParsedComments[Canonical] = FC;
530 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000531}
532
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000533void
534ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
535 TemplateTemplateParmDecl *Parm) {
536 ID.AddInteger(Parm->getDepth());
537 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000538 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000539
540 TemplateParameterList *Params = Parm->getTemplateParameters();
541 ID.AddInteger(Params->size());
542 for (TemplateParameterList::const_iterator P = Params->begin(),
543 PEnd = Params->end();
544 P != PEnd; ++P) {
545 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
546 ID.AddInteger(0);
547 ID.AddBoolean(TTP->isParameterPack());
548 continue;
549 }
550
551 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
552 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000553 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000554 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000555 if (NTTP->isExpandedParameterPack()) {
556 ID.AddBoolean(true);
557 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000558 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
559 QualType T = NTTP->getExpansionType(I);
560 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
561 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000562 } else
563 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000564 continue;
565 }
566
567 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
568 ID.AddInteger(2);
569 Profile(ID, TTP);
570 }
571}
572
573TemplateTemplateParmDecl *
574ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000575 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000576 // Check if we already have a canonical template template parameter.
577 llvm::FoldingSetNodeID ID;
578 CanonicalTemplateTemplateParm::Profile(ID, TTP);
579 void *InsertPos = 0;
580 CanonicalTemplateTemplateParm *Canonical
581 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
582 if (Canonical)
583 return Canonical->getParam();
584
585 // Build a canonical template parameter list.
586 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000587 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000588 CanonParams.reserve(Params->size());
589 for (TemplateParameterList::const_iterator P = Params->begin(),
590 PEnd = Params->end();
591 P != PEnd; ++P) {
592 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
593 CanonParams.push_back(
594 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000595 SourceLocation(),
596 SourceLocation(),
597 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000598 TTP->getIndex(), 0, false,
599 TTP->isParameterPack()));
600 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000601 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
602 QualType T = getCanonicalType(NTTP->getType());
603 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
604 NonTypeTemplateParmDecl *Param;
605 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000606 SmallVector<QualType, 2> ExpandedTypes;
607 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000608 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
609 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
610 ExpandedTInfos.push_back(
611 getTrivialTypeSourceInfo(ExpandedTypes.back()));
612 }
613
614 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000615 SourceLocation(),
616 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000617 NTTP->getDepth(),
618 NTTP->getPosition(), 0,
619 T,
620 TInfo,
621 ExpandedTypes.data(),
622 ExpandedTypes.size(),
623 ExpandedTInfos.data());
624 } else {
625 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000626 SourceLocation(),
627 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000628 NTTP->getDepth(),
629 NTTP->getPosition(), 0,
630 T,
631 NTTP->isParameterPack(),
632 TInfo);
633 }
634 CanonParams.push_back(Param);
635
636 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000637 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
638 cast<TemplateTemplateParmDecl>(*P)));
639 }
640
641 TemplateTemplateParmDecl *CanonTTP
642 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
643 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000644 TTP->getPosition(),
645 TTP->isParameterPack(),
646 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000647 TemplateParameterList::Create(*this, SourceLocation(),
648 SourceLocation(),
649 CanonParams.data(),
650 CanonParams.size(),
651 SourceLocation()));
652
653 // Get the new insert position for the node we care about.
654 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
655 assert(Canonical == 0 && "Shouldn't be in the map!");
656 (void)Canonical;
657
658 // Create the canonical template template parameter entry.
659 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
660 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
661 return CanonTTP;
662}
663
Charles Davis53c59df2010-08-16 03:33:14 +0000664CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000665 if (!LangOpts.CPlusPlus) return 0;
666
John McCall359b8852013-01-25 22:30:49 +0000667 switch (T.getCXXABI().getKind()) {
668 case TargetCXXABI::GenericARM:
669 case TargetCXXABI::iOS:
John McCall86353412010-08-21 22:46:04 +0000670 return CreateARMCXXABI(*this);
Tim Northover9bb857a2013-01-31 12:13:10 +0000671 case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000672 case TargetCXXABI::GenericItanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000673 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000674 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000675 return CreateMicrosoftCXXABI(*this);
676 }
David Blaikie8a40f702012-01-17 06:56:22 +0000677 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000678}
679
Douglas Gregore8bbc122011-09-02 00:18:52 +0000680static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000681 const LangOptions &LOpts) {
682 if (LOpts.FakeAddressSpaceMap) {
683 // The fake address space map must have a distinct entry for each
684 // language-specific address space.
685 static const unsigned FakeAddrSpaceMap[] = {
686 1, // opencl_global
687 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000688 3, // opencl_constant
689 4, // cuda_device
690 5, // cuda_constant
691 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000692 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000693 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000694 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000695 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000696 }
697}
698
David Tweed31d09b02013-09-13 12:04:22 +0000699static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
700 const LangOptions &LangOpts) {
701 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000702 case LangOptions::ASMM_Target:
703 return TI.useAddressSpaceMapMangling();
704 case LangOptions::ASMM_On:
705 return true;
706 case LangOptions::ASMM_Off:
707 return false;
708 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000709 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000710}
711
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000712ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000713 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000714 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000715 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000716 unsigned size_reserve,
717 bool DelayInitialization)
718 : FunctionProtoTypes(this_()),
719 TemplateSpecializationTypes(this_()),
720 DependentTemplateSpecializationTypes(this_()),
721 SubstTemplateTemplateParmPacks(this_()),
722 GlobalNestedNameSpecifier(0),
Nico Webere1687c52013-06-20 21:44:55 +0000723 Int128Decl(0), UInt128Decl(0), Float128StubDecl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000724 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000725 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanianf2578572012-08-30 18:49:41 +0000726 BOOLDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000727 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000728 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000729 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
730 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
731 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000732 NullTypeSourceInfo(QualType()),
733 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000734 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000735 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000736 Idents(idents), Selectors(sels),
737 BuiltinInfo(builtins),
738 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000739 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000740 Comments(SM), CommentsLoaded(false),
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000741 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
Rafael Espindolace2168f2013-05-29 19:51:12 +0000742 LastSDM(0, 0)
Douglas Gregore8bbc122011-09-02 00:18:52 +0000743{
Mike Stump11289f42009-09-09 15:08:12 +0000744 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000745 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000746
747 if (!DelayInitialization) {
748 assert(t && "No target supplied for ASTContext initialization");
749 InitBuiltinTypes(*t);
750 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000751}
752
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000753ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000754 // Release the DenseMaps associated with DeclContext objects.
755 // FIXME: Is this the ideal solution?
756 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000757
Manuel Klimeka7328992013-06-03 13:51:33 +0000758 // Call all of the deallocation functions on all of their targets.
759 for (DeallocationMap::const_iterator I = Deallocations.begin(),
760 E = Deallocations.end(); I != E; ++I)
761 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
762 (I->first)((I->second)[J]);
763
Ted Kremenek076baeb2010-06-08 23:00:58 +0000764 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000765 // because they can contain DenseMaps.
766 for (llvm::DenseMap<const ObjCContainerDecl*,
767 const ASTRecordLayout*>::iterator
768 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
769 // Increment in loop to prevent using deallocated memory.
770 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
771 R->Destroy(*this);
772
Ted Kremenek076baeb2010-06-08 23:00:58 +0000773 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
774 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
775 // Increment in loop to prevent using deallocated memory.
776 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
777 R->Destroy(*this);
778 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000779
780 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
781 AEnd = DeclAttrs.end();
782 A != AEnd; ++A)
783 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000784
785 for (llvm::DenseMap<const DeclContext *, MangleNumberingContext *>::iterator
786 I = MangleNumberingContexts.begin(),
787 E = MangleNumberingContexts.end();
788 I != E; ++I)
789 delete I->second;
Douglas Gregor561eceb2010-08-30 16:49:28 +0000790}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000791
Douglas Gregor1a809332010-05-23 18:26:36 +0000792void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimeka7328992013-06-03 13:51:33 +0000793 Deallocations[Callback].push_back(Data);
Douglas Gregor1a809332010-05-23 18:26:36 +0000794}
795
Mike Stump11289f42009-09-09 15:08:12 +0000796void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000797ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000798 ExternalSource.reset(Source.take());
799}
800
Chris Lattner4eb445d2007-01-26 01:27:23 +0000801void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000802 llvm::errs() << "\n*** AST Context Stats:\n";
803 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000804
Douglas Gregora30d0462009-05-26 14:40:08 +0000805 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000806#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000807#define ABSTRACT_TYPE(Name, Parent)
808#include "clang/AST/TypeNodes.def"
809 0 // Extra
810 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000811
Chris Lattner4eb445d2007-01-26 01:27:23 +0000812 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
813 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000814 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000815 }
816
Douglas Gregora30d0462009-05-26 14:40:08 +0000817 unsigned Idx = 0;
818 unsigned TotalBytes = 0;
819#define TYPE(Name, Parent) \
820 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000821 llvm::errs() << " " << counts[Idx] << " " << #Name \
822 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000823 TotalBytes += counts[Idx] * sizeof(Name##Type); \
824 ++Idx;
825#define ABSTRACT_TYPE(Name, Parent)
826#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000827
Chandler Carruth3c147a72011-07-04 05:32:14 +0000828 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
829
Douglas Gregor7454c562010-07-02 20:37:36 +0000830 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000831 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
832 << NumImplicitDefaultConstructors
833 << " implicit default constructors created\n";
834 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
835 << NumImplicitCopyConstructors
836 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000837 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000838 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
839 << NumImplicitMoveConstructors
840 << " implicit move constructors created\n";
841 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
842 << NumImplicitCopyAssignmentOperators
843 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000844 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000845 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
846 << NumImplicitMoveAssignmentOperators
847 << " implicit move assignment operators created\n";
848 llvm::errs() << NumImplicitDestructorsDeclared << "/"
849 << NumImplicitDestructors
850 << " implicit destructors created\n";
851
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000852 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000853 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000854 ExternalSource->PrintStats();
855 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000856
Douglas Gregor5b11d492010-07-25 17:53:33 +0000857 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000858}
859
Douglas Gregor801c99d2011-08-12 06:49:56 +0000860TypedefDecl *ASTContext::getInt128Decl() const {
861 if (!Int128Decl) {
862 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
863 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
864 getTranslationUnitDecl(),
865 SourceLocation(),
866 SourceLocation(),
867 &Idents.get("__int128_t"),
868 TInfo);
869 }
870
871 return Int128Decl;
872}
873
874TypedefDecl *ASTContext::getUInt128Decl() const {
875 if (!UInt128Decl) {
876 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
877 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
878 getTranslationUnitDecl(),
879 SourceLocation(),
880 SourceLocation(),
881 &Idents.get("__uint128_t"),
882 TInfo);
883 }
884
885 return UInt128Decl;
886}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000887
Nico Webere1687c52013-06-20 21:44:55 +0000888TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber5b0b46f2013-06-21 01:29:36 +0000889 assert(LangOpts.CPlusPlus && "should only be called for c++");
Nico Webere1687c52013-06-20 21:44:55 +0000890 if (!Float128StubDecl) {
Nico Weber95296d42013-06-20 23:30:30 +0000891 Float128StubDecl = CXXRecordDecl::Create(const_cast<ASTContext &>(*this),
892 TTK_Struct,
893 getTranslationUnitDecl(),
894 SourceLocation(),
895 SourceLocation(),
896 &Idents.get("__float128"));
Nico Webere1687c52013-06-20 21:44:55 +0000897 }
898
899 return Float128StubDecl;
900}
901
John McCall48f2d582009-10-23 23:03:21 +0000902void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000903 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000904 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000905 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000906}
907
Douglas Gregore8bbc122011-09-02 00:18:52 +0000908void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
909 assert((!this->Target || this->Target == &Target) &&
910 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000911 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000912
Douglas Gregore8bbc122011-09-02 00:18:52 +0000913 this->Target = &Target;
914
915 ABI.reset(createCXXABI(Target));
916 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +0000917 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000918
Chris Lattner970e54e2006-11-12 00:37:36 +0000919 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000920 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000921
Chris Lattner970e54e2006-11-12 00:37:36 +0000922 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000923 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000924 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000925 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000926 InitBuiltinType(CharTy, BuiltinType::Char_S);
927 else
928 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000929 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000930 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
931 InitBuiltinType(ShortTy, BuiltinType::Short);
932 InitBuiltinType(IntTy, BuiltinType::Int);
933 InitBuiltinType(LongTy, BuiltinType::Long);
934 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000935
Chris Lattner970e54e2006-11-12 00:37:36 +0000936 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000937 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
938 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
939 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
940 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
941 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000942
Chris Lattner970e54e2006-11-12 00:37:36 +0000943 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000944 InitBuiltinType(FloatTy, BuiltinType::Float);
945 InitBuiltinType(DoubleTy, BuiltinType::Double);
946 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000947
Chris Lattnerf122cef2009-04-30 02:43:43 +0000948 // GNU extension, 128-bit integers.
949 InitBuiltinType(Int128Ty, BuiltinType::Int128);
950 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
951
Hans Wennborg0d81e012013-05-10 10:08:40 +0000952 // C++ 3.9.1p5
953 if (TargetInfo::isTypeSigned(Target.getWCharType()))
954 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
955 else // -fshort-wchar makes wchar_t be unsigned.
956 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
957 if (LangOpts.CPlusPlus && LangOpts.WChar)
958 WideCharTy = WCharTy;
959 else {
960 // C99 (or C++ using -fno-wchar).
961 WideCharTy = getFromTargetType(Target.getWCharType());
962 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000963
James Molloy36365542012-05-04 10:55:22 +0000964 WIntTy = getFromTargetType(Target.getWIntType());
965
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000966 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
967 InitBuiltinType(Char16Ty, BuiltinType::Char16);
968 else // C99
969 Char16Ty = getFromTargetType(Target.getChar16Type());
970
971 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
972 InitBuiltinType(Char32Ty, BuiltinType::Char32);
973 else // C99
974 Char32Ty = getFromTargetType(Target.getChar32Type());
975
Douglas Gregor4619e432008-12-05 23:32:09 +0000976 // Placeholder type for type-dependent expressions whose type is
977 // completely unknown. No code should ever check a type against
978 // DependentTy and users should never see it; however, it is here to
979 // help diagnose failures to properly check for type-dependent
980 // expressions.
981 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000982
John McCall36e7fe32010-10-12 00:20:44 +0000983 // Placeholder type for functions.
984 InitBuiltinType(OverloadTy, BuiltinType::Overload);
985
John McCall0009fcc2011-04-26 20:42:42 +0000986 // Placeholder type for bound members.
987 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
988
John McCall526ab472011-10-25 17:37:35 +0000989 // Placeholder type for pseudo-objects.
990 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
991
John McCall31996342011-04-07 08:22:57 +0000992 // "any" type; useful for debugger-like clients.
993 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
994
John McCall8a6b59a2011-10-17 18:09:15 +0000995 // Placeholder type for unbridged ARC casts.
996 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
997
Eli Friedman34866c72012-08-31 00:14:07 +0000998 // Placeholder type for builtin functions.
999 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1000
Chris Lattner970e54e2006-11-12 00:37:36 +00001001 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001002 FloatComplexTy = getComplexType(FloatTy);
1003 DoubleComplexTy = getComplexType(DoubleTy);
1004 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001005
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001006 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001007 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1008 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001009 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001010
1011 if (LangOpts.OpenCL) {
1012 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1013 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1014 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1015 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1016 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
1017 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001018
Guy Benyei61054192013-02-07 10:55:47 +00001019 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001020 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001021 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001022
1023 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001024 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1025 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001026
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001027 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001028
1029 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001030
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001031 // void * type
1032 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001033
1034 // nullptr type (C++0x 2.14.7)
1035 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001036
1037 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1038 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001039
1040 // Builtin type used to help define __builtin_va_list.
1041 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +00001042}
1043
David Blaikie9c902b52011-09-25 23:23:43 +00001044DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001045 return SourceMgr.getDiagnostics();
1046}
1047
Douglas Gregor561eceb2010-08-30 16:49:28 +00001048AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1049 AttrVec *&Result = DeclAttrs[D];
1050 if (!Result) {
1051 void *Mem = Allocate(sizeof(AttrVec));
1052 Result = new (Mem) AttrVec;
1053 }
1054
1055 return *Result;
1056}
1057
1058/// \brief Erase the attributes corresponding to the given declaration.
1059void ASTContext::eraseDeclAttrs(const Decl *D) {
1060 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1061 if (Pos != DeclAttrs.end()) {
1062 Pos->second->~AttrVec();
1063 DeclAttrs.erase(Pos);
1064 }
1065}
1066
Larisse Voufo39a1e502013-08-06 01:03:05 +00001067// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001068MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001069ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001070 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001071 return getTemplateOrSpecializationInfo(Var)
1072 .dyn_cast<MemberSpecializationInfo *>();
1073}
1074
1075ASTContext::TemplateOrSpecializationInfo
1076ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1077 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1078 TemplateOrInstantiation.find(Var);
1079 if (Pos == TemplateOrInstantiation.end())
1080 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001081
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001082 return Pos->second;
1083}
1084
Mike Stump11289f42009-09-09 15:08:12 +00001085void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001086ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001087 TemplateSpecializationKind TSK,
1088 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001089 assert(Inst->isStaticDataMember() && "Not a static data member");
1090 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001091 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1092 Tmpl, TSK, PointOfInstantiation));
1093}
1094
1095void
1096ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1097 TemplateOrSpecializationInfo TSI) {
1098 assert(!TemplateOrInstantiation[Inst] &&
1099 "Already noted what the variable was instantiated from");
1100 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001101}
1102
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001103FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1104 const FunctionDecl *FD){
1105 assert(FD && "Specialization is 0");
1106 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001107 = ClassScopeSpecializationPattern.find(FD);
1108 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001109 return 0;
1110
1111 return Pos->second;
1112}
1113
1114void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1115 FunctionDecl *Pattern) {
1116 assert(FD && "Specialization is 0");
1117 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001118 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001119}
1120
John McCalle61f2ba2009-11-18 02:36:19 +00001121NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001122ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001123 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001124 = InstantiatedFromUsingDecl.find(UUD);
1125 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001126 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001127
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001128 return Pos->second;
1129}
1130
1131void
John McCallb96ec562009-12-04 22:46:56 +00001132ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1133 assert((isa<UsingDecl>(Pattern) ||
1134 isa<UnresolvedUsingValueDecl>(Pattern) ||
1135 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1136 "pattern decl is not a using decl");
1137 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1138 InstantiatedFromUsingDecl[Inst] = Pattern;
1139}
1140
1141UsingShadowDecl *
1142ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1143 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1144 = InstantiatedFromUsingShadowDecl.find(Inst);
1145 if (Pos == InstantiatedFromUsingShadowDecl.end())
1146 return 0;
1147
1148 return Pos->second;
1149}
1150
1151void
1152ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1153 UsingShadowDecl *Pattern) {
1154 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1155 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001156}
1157
Anders Carlsson5da84842009-09-01 04:26:58 +00001158FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1159 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1160 = InstantiatedFromUnnamedFieldDecl.find(Field);
1161 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1162 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001163
Anders Carlsson5da84842009-09-01 04:26:58 +00001164 return Pos->second;
1165}
1166
1167void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1168 FieldDecl *Tmpl) {
1169 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1170 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1171 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1172 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001173
Anders Carlsson5da84842009-09-01 04:26:58 +00001174 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1175}
1176
Douglas Gregor832940b2010-03-02 23:58:15 +00001177ASTContext::overridden_cxx_method_iterator
1178ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1179 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001180 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001181 if (Pos == OverriddenMethods.end())
1182 return 0;
1183
1184 return Pos->second.begin();
1185}
1186
1187ASTContext::overridden_cxx_method_iterator
1188ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1189 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001190 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001191 if (Pos == OverriddenMethods.end())
1192 return 0;
1193
1194 return Pos->second.end();
1195}
1196
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001197unsigned
1198ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1199 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001200 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001201 if (Pos == OverriddenMethods.end())
1202 return 0;
1203
1204 return Pos->second.size();
1205}
1206
Douglas Gregor832940b2010-03-02 23:58:15 +00001207void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1208 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001209 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001210 OverriddenMethods[Method].push_back(Overridden);
1211}
1212
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001213void ASTContext::getOverriddenMethods(
1214 const NamedDecl *D,
1215 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001216 assert(D);
1217
1218 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001219 Overridden.append(overridden_methods_begin(CXXMethod),
1220 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001221 return;
1222 }
1223
1224 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1225 if (!Method)
1226 return;
1227
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001228 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1229 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001230 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001231}
1232
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001233void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1234 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1235 assert(!Import->isFromASTFile() && "Non-local import declaration");
1236 if (!FirstLocalImport) {
1237 FirstLocalImport = Import;
1238 LastLocalImport = Import;
1239 return;
1240 }
1241
1242 LastLocalImport->NextLocalImport = Import;
1243 LastLocalImport = Import;
1244}
1245
Chris Lattner53cfe802007-07-18 17:52:12 +00001246//===----------------------------------------------------------------------===//
1247// Type Sizing and Analysis
1248//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001249
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001250/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1251/// scalar floating point type.
1252const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001253 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001254 assert(BT && "Not a floating point type!");
1255 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001256 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001257 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001258 case BuiltinType::Float: return Target->getFloatFormat();
1259 case BuiltinType::Double: return Target->getDoubleFormat();
1260 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001261 }
1262}
1263
Rafael Espindola71eccb32013-08-08 19:53:46 +00001264CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001265 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001266
John McCall94268702010-10-08 18:24:19 +00001267 bool UseAlignAttrOnly = false;
1268 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1269 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001270
John McCall94268702010-10-08 18:24:19 +00001271 // __attribute__((aligned)) can increase or decrease alignment
1272 // *except* on a struct or struct member, where it only increases
1273 // alignment unless 'packed' is also specified.
1274 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001275 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001276 // ignore that possibility; Sema should diagnose it.
1277 if (isa<FieldDecl>(D)) {
1278 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1279 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1280 } else {
1281 UseAlignAttrOnly = true;
1282 }
1283 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001284 else if (isa<FieldDecl>(D))
1285 UseAlignAttrOnly =
1286 D->hasAttr<PackedAttr>() ||
1287 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001288
John McCall4e819612011-01-20 07:57:12 +00001289 // If we're using the align attribute only, just ignore everything
1290 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001291 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001292 // do nothing
1293
John McCall94268702010-10-08 18:24:19 +00001294 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001295 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001296 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001297 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001298 T = RT->getPointeeType();
1299 else
1300 T = getPointerType(RT->getPointeeType());
1301 }
1302 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001303 // Adjust alignments of declarations with array type by the
1304 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001305 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001306 unsigned MinWidth = Target->getLargeArrayMinWidth();
1307 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001308 if (isa<VariableArrayType>(arrayType))
1309 Align = std::max(Align, Target->getLargeArrayAlign());
1310 else if (isa<ConstantArrayType>(arrayType) &&
1311 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1312 Align = std::max(Align, Target->getLargeArrayAlign());
1313 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001314
John McCall33ddac02011-01-19 10:06:00 +00001315 // Walk through any array types while we're at it.
1316 T = getBaseElementType(arrayType);
1317 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001318 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001319 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1320 if (VD->hasGlobalStorage())
1321 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1322 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001323 }
John McCall4e819612011-01-20 07:57:12 +00001324
1325 // Fields can be subject to extra alignment constraints, like if
1326 // the field is packed, the struct is packed, or the struct has a
1327 // a max-field-alignment constraint (#pragma pack). So calculate
1328 // the actual alignment of the field within the struct, and then
1329 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001330 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1331 const RecordDecl *Parent = Field->getParent();
1332 // We can only produce a sensible answer if the record is valid.
1333 if (!Parent->isInvalidDecl()) {
1334 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001335
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001336 // Start with the record's overall alignment.
1337 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001338
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001339 // Use the GCD of that and the offset within the record.
1340 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1341 if (Offset > 0) {
1342 // Alignment is always a power of 2, so the GCD will be a power of 2,
1343 // which means we get to do this crazy thing instead of Euclid's.
1344 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1345 if (LowBitOfOffset < FieldAlign)
1346 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1347 }
1348
1349 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001350 }
Charles Davis3fc51072010-02-23 04:52:00 +00001351 }
Chris Lattner68061312009-01-24 21:53:27 +00001352 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001353
Ken Dyckcc56c542011-01-15 18:38:59 +00001354 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001355}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001356
John McCallf1249922012-08-21 04:10:00 +00001357// getTypeInfoDataSizeInChars - Return the size of a type, in
1358// chars. If the type is a record, its data size is returned. This is
1359// the size of the memcpy that's performed when assigning this type
1360// using a trivial copy/move assignment operator.
1361std::pair<CharUnits, CharUnits>
1362ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1363 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1364
1365 // In C++, objects can sometimes be allocated into the tail padding
1366 // of a base-class subobject. We decide whether that's possible
1367 // during class layout, so here we can just trust the layout results.
1368 if (getLangOpts().CPlusPlus) {
1369 if (const RecordType *RT = T->getAs<RecordType>()) {
1370 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1371 sizeAndAlign.first = layout.getDataSize();
1372 }
1373 }
1374
1375 return sizeAndAlign;
1376}
1377
Richard Trieu04d2d942013-05-14 21:59:17 +00001378/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1379/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1380std::pair<CharUnits, CharUnits>
1381static getConstantArrayInfoInChars(const ASTContext &Context,
1382 const ConstantArrayType *CAT) {
1383 std::pair<CharUnits, CharUnits> EltInfo =
1384 Context.getTypeInfoInChars(CAT->getElementType());
1385 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001386 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1387 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001388 "Overflow in array type char size evaluation");
1389 uint64_t Width = EltInfo.first.getQuantity() * Size;
1390 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001391 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1392 Context.getTargetInfo().getPointerWidth(0) == 64)
1393 Width = llvm::RoundUpToAlignment(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001394 return std::make_pair(CharUnits::fromQuantity(Width),
1395 CharUnits::fromQuantity(Align));
1396}
1397
John McCall87fe5d52010-05-20 01:18:31 +00001398std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001399ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001400 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1401 return getConstantArrayInfoInChars(*this, CAT);
John McCall87fe5d52010-05-20 01:18:31 +00001402 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +00001403 return std::make_pair(toCharUnitsFromBits(Info.first),
1404 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +00001405}
1406
1407std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001408ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001409 return getTypeInfoInChars(T.getTypePtr());
1410}
1411
Daniel Dunbarc6475872012-03-09 04:12:54 +00001412std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1413 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1414 if (it != MemoizedTypeInfo.end())
1415 return it->second;
1416
1417 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1418 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1419 return Info;
1420}
1421
1422/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1423/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001424///
1425/// FIXME: Pointers into different addr spaces could have different sizes and
1426/// alignment requirements: getPointerInfo should take an AddrSpace, this
1427/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001428std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001429ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001430 uint64_t Width=0;
1431 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001432 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001433#define TYPE(Class, Base)
1434#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001435#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001436#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001437#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1438 case Type::Class: \
1439 assert(!T->isDependentType() && "should not see dependent types here"); \
1440 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001441#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001442 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001443
Chris Lattner355332d2007-07-13 22:27:08 +00001444 case Type::FunctionNoProto:
1445 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001446 // GCC extension: alignof(function) = 32 bits
1447 Width = 0;
1448 Align = 32;
1449 break;
1450
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001451 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001452 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001453 Width = 0;
1454 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1455 break;
1456
Steve Naroff5c131802007-08-30 01:06:46 +00001457 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001458 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001459
Chris Lattner37e05872008-03-05 18:54:05 +00001460 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001461 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001462 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1463 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001464 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001465 Align = EltInfo.second;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001466 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1467 getTargetInfo().getPointerWidth(0) == 64)
1468 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001469 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001470 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001471 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001472 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001473 const VectorType *VT = cast<VectorType>(T);
1474 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1475 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001476 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001477 // If the alignment is not a power of 2, round up to the next power of 2.
1478 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001479 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001480 Align = llvm::NextPowerOf2(Align);
1481 Width = llvm::RoundUpToAlignment(Width, Align);
1482 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001483 // Adjust the alignment based on the target max.
1484 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1485 if (TargetVectorAlign && TargetVectorAlign < Align)
1486 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001487 break;
1488 }
Chris Lattner647fb222007-07-18 18:26:58 +00001489
Chris Lattner7570e9c2008-03-08 08:52:55 +00001490 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001491 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001492 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001493 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001494 // GCC extension: alignof(void) = 8 bits.
1495 Width = 0;
1496 Align = 8;
1497 break;
1498
Chris Lattner6a4f7452007-12-19 19:23:28 +00001499 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001500 Width = Target->getBoolWidth();
1501 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001502 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001503 case BuiltinType::Char_S:
1504 case BuiltinType::Char_U:
1505 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001506 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001507 Width = Target->getCharWidth();
1508 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001509 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001510 case BuiltinType::WChar_S:
1511 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001512 Width = Target->getWCharWidth();
1513 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001514 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001515 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001516 Width = Target->getChar16Width();
1517 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001518 break;
1519 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001520 Width = Target->getChar32Width();
1521 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001522 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001523 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001524 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001525 Width = Target->getShortWidth();
1526 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001527 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001528 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001529 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001530 Width = Target->getIntWidth();
1531 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001532 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001533 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001534 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001535 Width = Target->getLongWidth();
1536 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001537 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001538 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001539 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001540 Width = Target->getLongLongWidth();
1541 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001542 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001543 case BuiltinType::Int128:
1544 case BuiltinType::UInt128:
1545 Width = 128;
1546 Align = 128; // int128_t is 128-bit aligned on all targets.
1547 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001548 case BuiltinType::Half:
1549 Width = Target->getHalfWidth();
1550 Align = Target->getHalfAlign();
1551 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001552 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001553 Width = Target->getFloatWidth();
1554 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001555 break;
1556 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001557 Width = Target->getDoubleWidth();
1558 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001559 break;
1560 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001561 Width = Target->getLongDoubleWidth();
1562 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001563 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001564 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001565 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1566 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001567 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001568 case BuiltinType::ObjCId:
1569 case BuiltinType::ObjCClass:
1570 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001571 Width = Target->getPointerWidth(0);
1572 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001573 break;
Guy Benyei61054192013-02-07 10:55:47 +00001574 case BuiltinType::OCLSampler:
1575 // Samplers are modeled as integers.
1576 Width = Target->getIntWidth();
1577 Align = Target->getIntAlign();
1578 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001579 case BuiltinType::OCLEvent:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001580 case BuiltinType::OCLImage1d:
1581 case BuiltinType::OCLImage1dArray:
1582 case BuiltinType::OCLImage1dBuffer:
1583 case BuiltinType::OCLImage2d:
1584 case BuiltinType::OCLImage2dArray:
1585 case BuiltinType::OCLImage3d:
1586 // Currently these types are pointers to opaque types.
1587 Width = Target->getPointerWidth(0);
1588 Align = Target->getPointerAlign(0);
1589 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001590 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001591 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001592 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001593 Width = Target->getPointerWidth(0);
1594 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001595 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001596 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001597 unsigned AS = getTargetAddressSpace(
1598 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001599 Width = Target->getPointerWidth(AS);
1600 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001601 break;
1602 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001603 case Type::LValueReference:
1604 case Type::RValueReference: {
1605 // alignof and sizeof should never enter this code path here, so we go
1606 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001607 unsigned AS = getTargetAddressSpace(
1608 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001609 Width = Target->getPointerWidth(AS);
1610 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001611 break;
1612 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001613 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001614 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001615 Width = Target->getPointerWidth(AS);
1616 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001617 break;
1618 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001619 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001620 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Reid Kleckner3a52abf2013-03-28 20:02:56 +00001621 llvm::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001622 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001623 }
Chris Lattner647fb222007-07-18 18:26:58 +00001624 case Type::Complex: {
1625 // Complex types have the same alignment as their elements, but twice the
1626 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001627 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001628 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001629 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001630 Align = EltInfo.second;
1631 break;
1632 }
John McCall8b07ec22010-05-15 11:32:37 +00001633 case Type::ObjCObject:
1634 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001635 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001636 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001637 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001638 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001639 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001640 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001641 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001642 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001643 break;
1644 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001645 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001646 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001647 const TagType *TT = cast<TagType>(T);
1648
1649 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001650 Width = 8;
1651 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001652 break;
1653 }
Mike Stump11289f42009-09-09 15:08:12 +00001654
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001655 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001656 return getTypeInfo(ET->getDecl()->getIntegerType());
1657
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001658 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001659 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001660 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001661 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001662 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001663 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001664
Chris Lattner63d2b362009-10-22 05:17:15 +00001665 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001666 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1667 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001668
Richard Smith30482bc2011-02-20 03:19:35 +00001669 case Type::Auto: {
1670 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001671 assert(!A->getDeducedType().isNull() &&
1672 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001673 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001674 }
1675
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001676 case Type::Paren:
1677 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1678
Douglas Gregoref462e62009-04-30 17:32:17 +00001679 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001680 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001681 std::pair<uint64_t, unsigned> Info
1682 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001683 // If the typedef has an aligned attribute on it, it overrides any computed
1684 // alignment we have. This violates the GCC documentation (which says that
1685 // attribute(aligned) can only round up) but matches its implementation.
1686 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1687 Align = AttrAlign;
1688 else
1689 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001690 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001691 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001692 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001693
Abramo Bagnara6150c882010-05-11 21:36:43 +00001694 case Type::Elaborated:
1695 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001696
John McCall81904512011-01-06 01:58:22 +00001697 case Type::Attributed:
1698 return getTypeInfo(
1699 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1700
Eli Friedman0dfb8892011-10-06 23:00:33 +00001701 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001702 // Start with the base type information.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001703 std::pair<uint64_t, unsigned> Info
1704 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1705 Width = Info.first;
1706 Align = Info.second;
John McCalla8ec7eb2013-03-07 21:37:17 +00001707
1708 // If the size of the type doesn't exceed the platform's max
1709 // atomic promotion width, make the size and alignment more
1710 // favorable to atomic operations:
1711 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1712 // Round the size up to a power of 2.
1713 if (!llvm::isPowerOf2_64(Width))
1714 Width = llvm::NextPowerOf2(Width);
1715
1716 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001717 Align = static_cast<unsigned>(Width);
1718 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001719 }
1720
Douglas Gregoref462e62009-04-30 17:32:17 +00001721 }
Mike Stump11289f42009-09-09 15:08:12 +00001722
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001723 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001724 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001725}
1726
Ken Dyckcc56c542011-01-15 18:38:59 +00001727/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1728CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1729 return CharUnits::fromQuantity(BitSize / getCharWidth());
1730}
1731
Ken Dyckb0fcc592011-02-11 01:54:29 +00001732/// toBits - Convert a size in characters to a size in characters.
1733int64_t ASTContext::toBits(CharUnits CharSize) const {
1734 return CharSize.getQuantity() * getCharWidth();
1735}
1736
Ken Dyck8c89d592009-12-22 14:23:30 +00001737/// getTypeSizeInChars - Return the size of the specified type, in characters.
1738/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001739CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001740 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001741}
Jay Foad39c79802011-01-12 09:06:06 +00001742CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001743 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001744}
1745
Ken Dycka6046ab2010-01-26 17:25:18 +00001746/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001747/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001748CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001749 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001750}
Jay Foad39c79802011-01-12 09:06:06 +00001751CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001752 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001753}
1754
Chris Lattnera3402cd2009-01-27 18:08:34 +00001755/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1756/// type for the current target in bits. This can be different than the ABI
1757/// alignment in cases where it is beneficial for performance to overalign
1758/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001759unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001760 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001761
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001762 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1763 return ABIAlign; // Never overalign on XCore.
1764
Eli Friedman7ab09572009-05-25 21:27:19 +00001765 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001766 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001767 T = CT->getElementType().getTypePtr();
1768 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001769 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1770 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001771 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1772
Chris Lattnera3402cd2009-01-27 18:08:34 +00001773 return ABIAlign;
1774}
1775
Ulrich Weigandfa806422013-05-06 16:23:57 +00001776/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1777/// to a global variable of the specified type.
1778unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1779 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1780}
1781
1782/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1783/// should be given to a global variable of the specified type.
1784CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1785 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1786}
1787
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001788/// DeepCollectObjCIvars -
1789/// This routine first collects all declared, but not synthesized, ivars in
1790/// super class and then collects all ivars, including those synthesized for
1791/// current class. This routine is used for implementation of current class
1792/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001793///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001794void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1795 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001796 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001797 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1798 DeepCollectObjCIvars(SuperClass, false, Ivars);
1799 if (!leafClass) {
1800 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1801 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001802 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001803 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001804 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001805 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001806 Iv= Iv->getNextIvar())
1807 Ivars.push_back(Iv);
1808 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001809}
1810
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001811/// CollectInheritedProtocols - Collect all protocols in current class and
1812/// those inherited by it.
1813void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001814 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001815 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001816 // We can use protocol_iterator here instead of
1817 // all_referenced_protocol_iterator since we are walking all categories.
1818 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1819 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001820 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001821 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001822 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001823 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001824 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001825 CollectInheritedProtocols(*P, Protocols);
1826 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001827 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001828
1829 // Categories of this Interface.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001830 for (ObjCInterfaceDecl::visible_categories_iterator
1831 Cat = OI->visible_categories_begin(),
1832 CatEnd = OI->visible_categories_end();
1833 Cat != CatEnd; ++Cat) {
1834 CollectInheritedProtocols(*Cat, Protocols);
1835 }
1836
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001837 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1838 while (SD) {
1839 CollectInheritedProtocols(SD, Protocols);
1840 SD = SD->getSuperClass();
1841 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001842 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001843 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001844 PE = OC->protocol_end(); P != PE; ++P) {
1845 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001846 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001847 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1848 PE = Proto->protocol_end(); P != PE; ++P)
1849 CollectInheritedProtocols(*P, Protocols);
1850 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001851 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001852 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1853 PE = OP->protocol_end(); P != PE; ++P) {
1854 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001855 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001856 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1857 PE = Proto->protocol_end(); P != PE; ++P)
1858 CollectInheritedProtocols(*P, Protocols);
1859 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001860 }
1861}
1862
Jay Foad39c79802011-01-12 09:06:06 +00001863unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001864 unsigned count = 0;
1865 // Count ivars declared in class extension.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001866 for (ObjCInterfaceDecl::known_extensions_iterator
1867 Ext = OI->known_extensions_begin(),
1868 ExtEnd = OI->known_extensions_end();
1869 Ext != ExtEnd; ++Ext) {
1870 count += Ext->ivar_size();
1871 }
1872
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001873 // Count ivar defined in this class's implementation. This
1874 // includes synthesized ivars.
1875 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001876 count += ImplDecl->ivar_size();
1877
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001878 return count;
1879}
1880
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001881bool ASTContext::isSentinelNullExpr(const Expr *E) {
1882 if (!E)
1883 return false;
1884
1885 // nullptr_t is always treated as null.
1886 if (E->getType()->isNullPtrType()) return true;
1887
1888 if (E->getType()->isAnyPointerType() &&
1889 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1890 Expr::NPC_ValueDependentIsNull))
1891 return true;
1892
1893 // Unfortunately, __null has type 'int'.
1894 if (isa<GNUNullExpr>(E)) return true;
1895
1896 return false;
1897}
1898
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001899/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1900ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1901 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1902 I = ObjCImpls.find(D);
1903 if (I != ObjCImpls.end())
1904 return cast<ObjCImplementationDecl>(I->second);
1905 return 0;
1906}
1907/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1908ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1909 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1910 I = ObjCImpls.find(D);
1911 if (I != ObjCImpls.end())
1912 return cast<ObjCCategoryImplDecl>(I->second);
1913 return 0;
1914}
1915
1916/// \brief Set the implementation of ObjCInterfaceDecl.
1917void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1918 ObjCImplementationDecl *ImplD) {
1919 assert(IFaceD && ImplD && "Passed null params");
1920 ObjCImpls[IFaceD] = ImplD;
1921}
1922/// \brief Set the implementation of ObjCCategoryDecl.
1923void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1924 ObjCCategoryImplDecl *ImplD) {
1925 assert(CatD && ImplD && "Passed null params");
1926 ObjCImpls[CatD] = ImplD;
1927}
1928
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001929const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1930 const NamedDecl *ND) const {
1931 if (const ObjCInterfaceDecl *ID =
1932 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001933 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001934 if (const ObjCCategoryDecl *CD =
1935 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001936 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001937 if (const ObjCImplDecl *IMD =
1938 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001939 return IMD->getClassInterface();
1940
1941 return 0;
1942}
1943
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001944/// \brief Get the copy initialization expression of VarDecl,or NULL if
1945/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001946Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001947 assert(VD && "Passed null params");
1948 assert(VD->hasAttr<BlocksAttr>() &&
1949 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001950 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001951 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001952 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1953}
1954
1955/// \brief Set the copy inialization expression of a block var decl.
1956void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1957 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001958 assert(VD->hasAttr<BlocksAttr>() &&
1959 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001960 BlockVarCopyInits[VD] = Init;
1961}
1962
John McCallbcd03502009-12-07 02:54:59 +00001963TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001964 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001965 if (!DataSize)
1966 DataSize = TypeLoc::getFullDataSizeForType(T);
1967 else
1968 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001969 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001970
John McCallbcd03502009-12-07 02:54:59 +00001971 TypeSourceInfo *TInfo =
1972 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1973 new (TInfo) TypeSourceInfo(T);
1974 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001975}
1976
John McCallbcd03502009-12-07 02:54:59 +00001977TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001978 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001979 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001980 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001981 return DI;
1982}
1983
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001984const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001985ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001986 return getObjCLayout(D, 0);
1987}
1988
1989const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001990ASTContext::getASTObjCImplementationLayout(
1991 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001992 return getObjCLayout(D->getClassInterface(), D);
1993}
1994
Chris Lattner983a8bb2007-07-13 22:13:22 +00001995//===----------------------------------------------------------------------===//
1996// Type creation/memoization methods
1997//===----------------------------------------------------------------------===//
1998
Jay Foad39c79802011-01-12 09:06:06 +00001999QualType
John McCall33ddac02011-01-19 10:06:00 +00002000ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2001 unsigned fastQuals = quals.getFastQualifiers();
2002 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002003
2004 // Check if we've already instantiated this type.
2005 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002006 ExtQuals::Profile(ID, baseType, quals);
2007 void *insertPos = 0;
2008 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2009 assert(eq->getQualifiers() == quals);
2010 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002011 }
2012
John McCall33ddac02011-01-19 10:06:00 +00002013 // If the base type is not canonical, make the appropriate canonical type.
2014 QualType canon;
2015 if (!baseType->isCanonicalUnqualified()) {
2016 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002017 canonSplit.Quals.addConsistentQualifiers(quals);
2018 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002019
2020 // Re-find the insert position.
2021 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2022 }
2023
2024 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2025 ExtQualNodes.InsertNode(eq, insertPos);
2026 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002027}
2028
Jay Foad39c79802011-01-12 09:06:06 +00002029QualType
2030ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002031 QualType CanT = getCanonicalType(T);
2032 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002033 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002034
John McCall8ccfcb52009-09-24 19:53:00 +00002035 // If we are composing extended qualifiers together, merge together
2036 // into one ExtQuals node.
2037 QualifierCollector Quals;
2038 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002039
John McCall8ccfcb52009-09-24 19:53:00 +00002040 // If this type already has an address space specified, it cannot get
2041 // another one.
2042 assert(!Quals.hasAddressSpace() &&
2043 "Type cannot be in multiple addr spaces!");
2044 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002045
John McCall8ccfcb52009-09-24 19:53:00 +00002046 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002047}
2048
Chris Lattnerd60183d2009-02-18 22:53:11 +00002049QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002050 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002051 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002052 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002053 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002054
John McCall53fa7142010-12-24 02:08:15 +00002055 if (const PointerType *ptr = T->getAs<PointerType>()) {
2056 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002057 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002058 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2059 return getPointerType(ResultType);
2060 }
2061 }
Mike Stump11289f42009-09-09 15:08:12 +00002062
John McCall8ccfcb52009-09-24 19:53:00 +00002063 // If we are composing extended qualifiers together, merge together
2064 // into one ExtQuals node.
2065 QualifierCollector Quals;
2066 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002067
John McCall8ccfcb52009-09-24 19:53:00 +00002068 // If this type already has an ObjCGC specified, it cannot get
2069 // another one.
2070 assert(!Quals.hasObjCGCAttr() &&
2071 "Type cannot have multiple ObjCGCs!");
2072 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002073
John McCall8ccfcb52009-09-24 19:53:00 +00002074 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002075}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002076
John McCall4f5019e2010-12-19 02:44:49 +00002077const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2078 FunctionType::ExtInfo Info) {
2079 if (T->getExtInfo() == Info)
2080 return T;
2081
2082 QualType Result;
2083 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2084 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
2085 } else {
2086 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2087 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2088 EPI.ExtInfo = Info;
Reid Kleckner896b32f2013-06-10 20:51:09 +00002089 Result = getFunctionType(FPT->getResultType(), FPT->getArgTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002090 }
2091
2092 return cast<FunctionType>(Result.getTypePtr());
2093}
2094
Richard Smith2a7d4812013-05-04 07:00:32 +00002095void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2096 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002097 FD = FD->getMostRecentDecl();
2098 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002099 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2100 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2101 FD->setType(getFunctionType(ResultType, FPT->getArgTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002102 if (FunctionDecl *Next = FD->getPreviousDecl())
2103 FD = Next;
2104 else
2105 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002106 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002107 if (ASTMutationListener *L = getASTMutationListener())
2108 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002109}
2110
Chris Lattnerc6395932007-06-22 20:56:16 +00002111/// getComplexType - Return the uniqued reference to the type for a complex
2112/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002113QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002114 // Unique pointers, to guarantee there is only one pointer of a particular
2115 // structure.
2116 llvm::FoldingSetNodeID ID;
2117 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002118
Chris Lattnerc6395932007-06-22 20:56:16 +00002119 void *InsertPos = 0;
2120 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2121 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002122
Chris Lattnerc6395932007-06-22 20:56:16 +00002123 // If the pointee type isn't canonical, this won't be a canonical type either,
2124 // so fill in the canonical type field.
2125 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002126 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002127 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002128
Chris Lattnerc6395932007-06-22 20:56:16 +00002129 // Get the new insert position for the node we care about.
2130 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002131 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002132 }
John McCall90d1c2d2009-09-24 23:30:46 +00002133 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002134 Types.push_back(New);
2135 ComplexTypes.InsertNode(New, InsertPos);
2136 return QualType(New, 0);
2137}
2138
Chris Lattner970e54e2006-11-12 00:37:36 +00002139/// getPointerType - Return the uniqued reference to the type for a pointer to
2140/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002141QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002142 // Unique pointers, to guarantee there is only one pointer of a particular
2143 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002144 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002145 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002146
Chris Lattner67521df2007-01-27 01:29:36 +00002147 void *InsertPos = 0;
2148 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002149 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002150
Chris Lattner7ccecb92006-11-12 08:50:50 +00002151 // If the pointee type isn't canonical, this won't be a canonical type either,
2152 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002153 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002154 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002155 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002156
Bob Wilsonc8541f22013-03-15 17:12:43 +00002157 // Get the new insert position for the node we care about.
2158 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2159 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2160 }
John McCall90d1c2d2009-09-24 23:30:46 +00002161 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002162 Types.push_back(New);
2163 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002164 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002165}
2166
Reid Kleckner0503a872013-12-05 01:23:43 +00002167QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2168 llvm::FoldingSetNodeID ID;
2169 AdjustedType::Profile(ID, Orig, New);
2170 void *InsertPos = 0;
2171 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2172 if (AT)
2173 return QualType(AT, 0);
2174
2175 QualType Canonical = getCanonicalType(New);
2176
2177 // Get the new insert position for the node we care about.
2178 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2179 assert(AT == 0 && "Shouldn't be in the map!");
2180
2181 AT = new (*this, TypeAlignment)
2182 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2183 Types.push_back(AT);
2184 AdjustedTypes.InsertNode(AT, InsertPos);
2185 return QualType(AT, 0);
2186}
2187
Reid Kleckner8a365022013-06-24 17:51:48 +00002188QualType ASTContext::getDecayedType(QualType T) const {
2189 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2190
Reid Kleckner8a365022013-06-24 17:51:48 +00002191 QualType Decayed;
2192
2193 // C99 6.7.5.3p7:
2194 // A declaration of a parameter as "array of type" shall be
2195 // adjusted to "qualified pointer to type", where the type
2196 // qualifiers (if any) are those specified within the [ and ] of
2197 // the array type derivation.
2198 if (T->isArrayType())
2199 Decayed = getArrayDecayedType(T);
2200
2201 // C99 6.7.5.3p8:
2202 // A declaration of a parameter as "function returning type"
2203 // shall be adjusted to "pointer to function returning type", as
2204 // in 6.3.2.1.
2205 if (T->isFunctionType())
2206 Decayed = getPointerType(T);
2207
Reid Kleckner0503a872013-12-05 01:23:43 +00002208 llvm::FoldingSetNodeID ID;
2209 AdjustedType::Profile(ID, T, Decayed);
2210 void *InsertPos = 0;
2211 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2212 if (AT)
2213 return QualType(AT, 0);
2214
Reid Kleckner8a365022013-06-24 17:51:48 +00002215 QualType Canonical = getCanonicalType(Decayed);
2216
2217 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002218 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2219 assert(AT == 0 && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002220
Reid Kleckner0503a872013-12-05 01:23:43 +00002221 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2222 Types.push_back(AT);
2223 AdjustedTypes.InsertNode(AT, InsertPos);
2224 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002225}
2226
Mike Stump11289f42009-09-09 15:08:12 +00002227/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002228/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002229QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002230 assert(T->isFunctionType() && "block of function types only");
2231 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002232 // structure.
2233 llvm::FoldingSetNodeID ID;
2234 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002235
Steve Naroffec33ed92008-08-27 16:04:49 +00002236 void *InsertPos = 0;
2237 if (BlockPointerType *PT =
2238 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2239 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002240
2241 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002242 // type either so fill in the canonical type field.
2243 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002244 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002245 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002246
Steve Naroffec33ed92008-08-27 16:04:49 +00002247 // Get the new insert position for the node we care about.
2248 BlockPointerType *NewIP =
2249 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002250 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002251 }
John McCall90d1c2d2009-09-24 23:30:46 +00002252 BlockPointerType *New
2253 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002254 Types.push_back(New);
2255 BlockPointerTypes.InsertNode(New, InsertPos);
2256 return QualType(New, 0);
2257}
2258
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002259/// getLValueReferenceType - Return the uniqued reference to the type for an
2260/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002261QualType
2262ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002263 assert(getCanonicalType(T) != OverloadTy &&
2264 "Unresolved overloaded function type");
2265
Bill Wendling3708c182007-05-27 10:15:43 +00002266 // Unique pointers, to guarantee there is only one pointer of a particular
2267 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002268 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002269 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002270
2271 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002272 if (LValueReferenceType *RT =
2273 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002274 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002275
John McCallfc93cf92009-10-22 22:37:11 +00002276 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2277
Bill Wendling3708c182007-05-27 10:15:43 +00002278 // If the referencee type isn't canonical, this won't be a canonical type
2279 // either, so fill in the canonical type field.
2280 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002281 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2282 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2283 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002284
Bill Wendling3708c182007-05-27 10:15:43 +00002285 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002286 LValueReferenceType *NewIP =
2287 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002288 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002289 }
2290
John McCall90d1c2d2009-09-24 23:30:46 +00002291 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002292 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2293 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002294 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002295 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002296
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002297 return QualType(New, 0);
2298}
2299
2300/// getRValueReferenceType - Return the uniqued reference to the type for an
2301/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002302QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002303 // Unique pointers, to guarantee there is only one pointer of a particular
2304 // structure.
2305 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002306 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002307
2308 void *InsertPos = 0;
2309 if (RValueReferenceType *RT =
2310 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2311 return QualType(RT, 0);
2312
John McCallfc93cf92009-10-22 22:37:11 +00002313 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2314
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002315 // If the referencee type isn't canonical, this won't be a canonical type
2316 // either, so fill in the canonical type field.
2317 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002318 if (InnerRef || !T.isCanonical()) {
2319 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2320 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002321
2322 // Get the new insert position for the node we care about.
2323 RValueReferenceType *NewIP =
2324 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002325 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002326 }
2327
John McCall90d1c2d2009-09-24 23:30:46 +00002328 RValueReferenceType *New
2329 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002330 Types.push_back(New);
2331 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002332 return QualType(New, 0);
2333}
2334
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002335/// getMemberPointerType - Return the uniqued reference to the type for a
2336/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002337QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002338 // Unique pointers, to guarantee there is only one pointer of a particular
2339 // structure.
2340 llvm::FoldingSetNodeID ID;
2341 MemberPointerType::Profile(ID, T, Cls);
2342
2343 void *InsertPos = 0;
2344 if (MemberPointerType *PT =
2345 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2346 return QualType(PT, 0);
2347
2348 // If the pointee or class type isn't canonical, this won't be a canonical
2349 // type either, so fill in the canonical type field.
2350 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002351 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002352 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2353
2354 // Get the new insert position for the node we care about.
2355 MemberPointerType *NewIP =
2356 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002357 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002358 }
John McCall90d1c2d2009-09-24 23:30:46 +00002359 MemberPointerType *New
2360 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002361 Types.push_back(New);
2362 MemberPointerTypes.InsertNode(New, InsertPos);
2363 return QualType(New, 0);
2364}
2365
Mike Stump11289f42009-09-09 15:08:12 +00002366/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002367/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002368QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002369 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002370 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002371 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002372 assert((EltTy->isDependentType() ||
2373 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002374 "Constant array of VLAs is illegal!");
2375
Chris Lattnere2df3f92009-05-13 04:12:56 +00002376 // Convert the array size into a canonical width matching the pointer size for
2377 // the target.
2378 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002379 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002380 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002381
Chris Lattner23b7eb62007-06-15 23:05:46 +00002382 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002383 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002384
Chris Lattner36f8e652007-01-27 08:31:04 +00002385 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002386 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002387 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002388 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002389
John McCall33ddac02011-01-19 10:06:00 +00002390 // If the element type isn't canonical or has qualifiers, this won't
2391 // be a canonical type either, so fill in the canonical type field.
2392 QualType Canon;
2393 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2394 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002395 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002396 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002397 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002398
Chris Lattner36f8e652007-01-27 08:31:04 +00002399 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002400 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002401 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002402 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002403 }
Mike Stump11289f42009-09-09 15:08:12 +00002404
John McCall90d1c2d2009-09-24 23:30:46 +00002405 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002406 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002407 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002408 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002409 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002410}
2411
John McCall06549462011-01-18 08:40:38 +00002412/// getVariableArrayDecayedType - Turns the given type, which may be
2413/// variably-modified, into the corresponding type with all the known
2414/// sizes replaced with [*].
2415QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2416 // Vastly most common case.
2417 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002418
John McCall06549462011-01-18 08:40:38 +00002419 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002420
John McCall06549462011-01-18 08:40:38 +00002421 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002422 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002423 switch (ty->getTypeClass()) {
2424#define TYPE(Class, Base)
2425#define ABSTRACT_TYPE(Class, Base)
2426#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2427#include "clang/AST/TypeNodes.def"
2428 llvm_unreachable("didn't desugar past all non-canonical types?");
2429
2430 // These types should never be variably-modified.
2431 case Type::Builtin:
2432 case Type::Complex:
2433 case Type::Vector:
2434 case Type::ExtVector:
2435 case Type::DependentSizedExtVector:
2436 case Type::ObjCObject:
2437 case Type::ObjCInterface:
2438 case Type::ObjCObjectPointer:
2439 case Type::Record:
2440 case Type::Enum:
2441 case Type::UnresolvedUsing:
2442 case Type::TypeOfExpr:
2443 case Type::TypeOf:
2444 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002445 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002446 case Type::DependentName:
2447 case Type::InjectedClassName:
2448 case Type::TemplateSpecialization:
2449 case Type::DependentTemplateSpecialization:
2450 case Type::TemplateTypeParm:
2451 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002452 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002453 case Type::PackExpansion:
2454 llvm_unreachable("type should never be variably-modified");
2455
2456 // These types can be variably-modified but should never need to
2457 // further decay.
2458 case Type::FunctionNoProto:
2459 case Type::FunctionProto:
2460 case Type::BlockPointer:
2461 case Type::MemberPointer:
2462 return type;
2463
2464 // These types can be variably-modified. All these modifications
2465 // preserve structure except as noted by comments.
2466 // TODO: if we ever care about optimizing VLAs, there are no-op
2467 // optimizations available here.
2468 case Type::Pointer:
2469 result = getPointerType(getVariableArrayDecayedType(
2470 cast<PointerType>(ty)->getPointeeType()));
2471 break;
2472
2473 case Type::LValueReference: {
2474 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2475 result = getLValueReferenceType(
2476 getVariableArrayDecayedType(lv->getPointeeType()),
2477 lv->isSpelledAsLValue());
2478 break;
2479 }
2480
2481 case Type::RValueReference: {
2482 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2483 result = getRValueReferenceType(
2484 getVariableArrayDecayedType(lv->getPointeeType()));
2485 break;
2486 }
2487
Eli Friedman0dfb8892011-10-06 23:00:33 +00002488 case Type::Atomic: {
2489 const AtomicType *at = cast<AtomicType>(ty);
2490 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2491 break;
2492 }
2493
John McCall06549462011-01-18 08:40:38 +00002494 case Type::ConstantArray: {
2495 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2496 result = getConstantArrayType(
2497 getVariableArrayDecayedType(cat->getElementType()),
2498 cat->getSize(),
2499 cat->getSizeModifier(),
2500 cat->getIndexTypeCVRQualifiers());
2501 break;
2502 }
2503
2504 case Type::DependentSizedArray: {
2505 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2506 result = getDependentSizedArrayType(
2507 getVariableArrayDecayedType(dat->getElementType()),
2508 dat->getSizeExpr(),
2509 dat->getSizeModifier(),
2510 dat->getIndexTypeCVRQualifiers(),
2511 dat->getBracketsRange());
2512 break;
2513 }
2514
2515 // Turn incomplete types into [*] types.
2516 case Type::IncompleteArray: {
2517 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2518 result = getVariableArrayType(
2519 getVariableArrayDecayedType(iat->getElementType()),
2520 /*size*/ 0,
2521 ArrayType::Normal,
2522 iat->getIndexTypeCVRQualifiers(),
2523 SourceRange());
2524 break;
2525 }
2526
2527 // Turn VLA types into [*] types.
2528 case Type::VariableArray: {
2529 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2530 result = getVariableArrayType(
2531 getVariableArrayDecayedType(vat->getElementType()),
2532 /*size*/ 0,
2533 ArrayType::Star,
2534 vat->getIndexTypeCVRQualifiers(),
2535 vat->getBracketsRange());
2536 break;
2537 }
2538 }
2539
2540 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002541 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002542}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002543
Steve Naroffcadebd02007-08-30 18:14:25 +00002544/// getVariableArrayType - Returns a non-unique reference to the type for a
2545/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002546QualType ASTContext::getVariableArrayType(QualType EltTy,
2547 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002548 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002549 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002550 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002551 // Since we don't unique expressions, it isn't possible to unique VLA's
2552 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002553 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002554
John McCall33ddac02011-01-19 10:06:00 +00002555 // Be sure to pull qualifiers off the element type.
2556 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2557 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002558 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002559 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002560 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002561 }
2562
John McCall90d1c2d2009-09-24 23:30:46 +00002563 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002564 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002565
2566 VariableArrayTypes.push_back(New);
2567 Types.push_back(New);
2568 return QualType(New, 0);
2569}
2570
Douglas Gregor4619e432008-12-05 23:32:09 +00002571/// getDependentSizedArrayType - Returns a non-unique reference to
2572/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002573/// type.
John McCall33ddac02011-01-19 10:06:00 +00002574QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2575 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002576 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002577 unsigned elementTypeQuals,
2578 SourceRange brackets) const {
2579 assert((!numElements || numElements->isTypeDependent() ||
2580 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002581 "Size must be type- or value-dependent!");
2582
John McCall33ddac02011-01-19 10:06:00 +00002583 // Dependently-sized array types that do not have a specified number
2584 // of elements will have their sizes deduced from a dependent
2585 // initializer. We do no canonicalization here at all, which is okay
2586 // because they can't be used in most locations.
2587 if (!numElements) {
2588 DependentSizedArrayType *newType
2589 = new (*this, TypeAlignment)
2590 DependentSizedArrayType(*this, elementType, QualType(),
2591 numElements, ASM, elementTypeQuals,
2592 brackets);
2593 Types.push_back(newType);
2594 return QualType(newType, 0);
2595 }
2596
2597 // Otherwise, we actually build a new type every time, but we
2598 // also build a canonical type.
2599
2600 SplitQualType canonElementType = getCanonicalType(elementType).split();
2601
2602 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002603 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002604 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002605 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002606 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002607
John McCall33ddac02011-01-19 10:06:00 +00002608 // Look for an existing type with these properties.
2609 DependentSizedArrayType *canonTy =
2610 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002611
John McCall33ddac02011-01-19 10:06:00 +00002612 // If we don't have one, build one.
2613 if (!canonTy) {
2614 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002615 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002616 QualType(), numElements, ASM, elementTypeQuals,
2617 brackets);
2618 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2619 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002620 }
2621
John McCall33ddac02011-01-19 10:06:00 +00002622 // Apply qualifiers from the element type to the array.
2623 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002624 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002625
John McCall33ddac02011-01-19 10:06:00 +00002626 // If we didn't need extra canonicalization for the element type,
2627 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002628 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002629 return canon;
2630
2631 // Otherwise, we need to build a type which follows the spelling
2632 // of the element type.
2633 DependentSizedArrayType *sugaredType
2634 = new (*this, TypeAlignment)
2635 DependentSizedArrayType(*this, elementType, canon, numElements,
2636 ASM, elementTypeQuals, brackets);
2637 Types.push_back(sugaredType);
2638 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002639}
2640
John McCall33ddac02011-01-19 10:06:00 +00002641QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002642 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002643 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002644 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002645 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002646
John McCall33ddac02011-01-19 10:06:00 +00002647 void *insertPos = 0;
2648 if (IncompleteArrayType *iat =
2649 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2650 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002651
2652 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002653 // either, so fill in the canonical type field. We also have to pull
2654 // qualifiers off the element type.
2655 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002656
John McCall33ddac02011-01-19 10:06:00 +00002657 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2658 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002659 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002660 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002661 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002662
2663 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002664 IncompleteArrayType *existing =
2665 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2666 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002667 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002668
John McCall33ddac02011-01-19 10:06:00 +00002669 IncompleteArrayType *newType = new (*this, TypeAlignment)
2670 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002671
John McCall33ddac02011-01-19 10:06:00 +00002672 IncompleteArrayTypes.InsertNode(newType, insertPos);
2673 Types.push_back(newType);
2674 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002675}
2676
Steve Naroff91fcddb2007-07-18 18:00:27 +00002677/// getVectorType - Return the unique reference to a vector type of
2678/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002679QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002680 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002681 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002682
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002683 // Check if we've already instantiated a vector of this type.
2684 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002685 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002686
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002687 void *InsertPos = 0;
2688 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2689 return QualType(VTP, 0);
2690
2691 // If the element type isn't canonical, this won't be a canonical type either,
2692 // so fill in the canonical type field.
2693 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002694 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002695 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002696
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002697 // Get the new insert position for the node we care about.
2698 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002699 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002700 }
John McCall90d1c2d2009-09-24 23:30:46 +00002701 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002702 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002703 VectorTypes.InsertNode(New, InsertPos);
2704 Types.push_back(New);
2705 return QualType(New, 0);
2706}
2707
Nate Begemance4d7fc2008-04-18 23:10:10 +00002708/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002709/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002710QualType
2711ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002712 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002713
Steve Naroff91fcddb2007-07-18 18:00:27 +00002714 // Check if we've already instantiated a vector of this type.
2715 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002716 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002717 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002718 void *InsertPos = 0;
2719 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2720 return QualType(VTP, 0);
2721
2722 // If the element type isn't canonical, this won't be a canonical type either,
2723 // so fill in the canonical type field.
2724 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002725 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002726 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002727
Steve Naroff91fcddb2007-07-18 18:00:27 +00002728 // Get the new insert position for the node we care about.
2729 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002730 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002731 }
John McCall90d1c2d2009-09-24 23:30:46 +00002732 ExtVectorType *New = new (*this, TypeAlignment)
2733 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002734 VectorTypes.InsertNode(New, InsertPos);
2735 Types.push_back(New);
2736 return QualType(New, 0);
2737}
2738
Jay Foad39c79802011-01-12 09:06:06 +00002739QualType
2740ASTContext::getDependentSizedExtVectorType(QualType vecType,
2741 Expr *SizeExpr,
2742 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002743 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002744 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002745 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002746
Douglas Gregor352169a2009-07-31 03:54:25 +00002747 void *InsertPos = 0;
2748 DependentSizedExtVectorType *Canon
2749 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2750 DependentSizedExtVectorType *New;
2751 if (Canon) {
2752 // We already have a canonical version of this array type; use it as
2753 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002754 New = new (*this, TypeAlignment)
2755 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2756 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002757 } else {
2758 QualType CanonVecTy = getCanonicalType(vecType);
2759 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002760 New = new (*this, TypeAlignment)
2761 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2762 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002763
2764 DependentSizedExtVectorType *CanonCheck
2765 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2766 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2767 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002768 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2769 } else {
2770 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2771 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002772 New = new (*this, TypeAlignment)
2773 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002774 }
2775 }
Mike Stump11289f42009-09-09 15:08:12 +00002776
Douglas Gregor758a8692009-06-17 21:51:59 +00002777 Types.push_back(New);
2778 return QualType(New, 0);
2779}
2780
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002781/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002782///
Jay Foad39c79802011-01-12 09:06:06 +00002783QualType
2784ASTContext::getFunctionNoProtoType(QualType ResultTy,
2785 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002786 const CallingConv CallConv = Info.getCC();
2787
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002788 // Unique functions, to guarantee there is only one function of a particular
2789 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002790 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002791 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002792
Chris Lattner47955de2007-01-27 08:37:20 +00002793 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002794 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002795 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002796 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002797
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002798 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002799 if (!ResultTy.isCanonical()) {
2800 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002801
Chris Lattner47955de2007-01-27 08:37:20 +00002802 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002803 FunctionNoProtoType *NewIP =
2804 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002805 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002806 }
Mike Stump11289f42009-09-09 15:08:12 +00002807
Roman Divacky65b88cd2011-03-01 17:40:53 +00002808 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002809 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002810 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002811 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002812 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002813 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002814}
2815
Douglas Gregorcd780372013-01-17 23:36:45 +00002816/// \brief Determine whether \p T is canonical as the result type of a function.
2817static bool isCanonicalResultType(QualType T) {
2818 return T.isCanonical() &&
2819 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2820 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2821}
2822
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002823/// getFunctionType - Return a normal function type with a typed argument
2824/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002825QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002826ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002827 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002828 size_t NumArgs = ArgArray.size();
2829
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002830 // Unique functions, to guarantee there is only one function of a particular
2831 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002832 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002833 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2834 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002835
2836 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002837 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002838 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002839 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002840
2841 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002842 bool isCanonical =
Douglas Gregorcd780372013-01-17 23:36:45 +00002843 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002844 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002845 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002846 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002847 isCanonical = false;
2848
2849 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002850 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002851 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002852 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002853 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002854 CanonicalArgs.reserve(NumArgs);
2855 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002856 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002857
John McCalldb40c7f2010-12-14 08:05:40 +00002858 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002859 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002860 CanonicalEPI.ExceptionSpecType = EST_None;
2861 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002862
Douglas Gregorcd780372013-01-17 23:36:45 +00002863 // Result types do not have ARC lifetime qualifiers.
2864 QualType CanResultTy = getCanonicalType(ResultTy);
2865 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2866 Qualifiers Qs = CanResultTy.getQualifiers();
2867 Qs.removeObjCLifetime();
2868 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2869 }
2870
Jordan Rose5c382722013-03-08 21:51:21 +00002871 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002872
Chris Lattnerfd4de792007-01-27 01:15:32 +00002873 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002874 FunctionProtoType *NewIP =
2875 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002876 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002877 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002878
John McCall31168b02011-06-15 23:02:42 +00002879 // FunctionProtoType objects are allocated with extra bytes after
2880 // them for three variable size arrays at the end:
2881 // - parameter types
2882 // - exception types
2883 // - consumed-arguments flags
2884 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002885 // expression, or information used to resolve the exception
2886 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002887 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002888 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002889 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002890 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002891 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002892 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002893 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002894 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002895 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2896 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002897 }
John McCall31168b02011-06-15 23:02:42 +00002898 if (EPI.ConsumedArguments)
2899 Size += NumArgs * sizeof(bool);
2900
John McCalldb40c7f2010-12-14 08:05:40 +00002901 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002902 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00002903 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002904 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002905 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002906 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002907}
Chris Lattneref51c202006-11-10 07:17:23 +00002908
John McCalle78aac42010-03-10 03:28:59 +00002909#ifndef NDEBUG
2910static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2911 if (!isa<CXXRecordDecl>(D)) return false;
2912 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2913 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2914 return true;
2915 if (RD->getDescribedClassTemplate() &&
2916 !isa<ClassTemplateSpecializationDecl>(RD))
2917 return true;
2918 return false;
2919}
2920#endif
2921
2922/// getInjectedClassNameType - Return the unique reference to the
2923/// injected class name type for the specified templated declaration.
2924QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002925 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002926 assert(NeedsInjectedClassNameType(Decl));
2927 if (Decl->TypeForDecl) {
2928 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002929 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002930 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2931 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2932 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2933 } else {
John McCall424cec92011-01-19 06:33:43 +00002934 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002935 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002936 Decl->TypeForDecl = newType;
2937 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002938 }
2939 return QualType(Decl->TypeForDecl, 0);
2940}
2941
Douglas Gregor83a586e2008-04-13 21:07:44 +00002942/// getTypeDeclType - Return the unique reference to the type for the
2943/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002944QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002945 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002946 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002947
Richard Smithdda56e42011-04-15 14:24:37 +00002948 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002949 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002950
John McCall96f0b5f2010-03-10 06:48:02 +00002951 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2952 "Template type parameter types are always available.");
2953
John McCall81e38502010-02-16 03:57:14 +00002954 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00002955 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00002956 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002957 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002958 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00002959 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002960 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002961 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002962 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002963 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2964 Decl->TypeForDecl = newType;
2965 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002966 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002967 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002968
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002969 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002970}
2971
Chris Lattner32d920b2007-01-26 02:01:53 +00002972/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002973/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002974QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002975ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2976 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002977 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002978
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002979 if (Canonical.isNull())
2980 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002981 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002982 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002983 Decl->TypeForDecl = newType;
2984 Types.push_back(newType);
2985 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002986}
2987
Jay Foad39c79802011-01-12 09:06:06 +00002988QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002989 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2990
Douglas Gregorec9fd132012-01-14 16:38:05 +00002991 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002992 if (PrevDecl->TypeForDecl)
2993 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2994
John McCall424cec92011-01-19 06:33:43 +00002995 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2996 Decl->TypeForDecl = newType;
2997 Types.push_back(newType);
2998 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002999}
3000
Jay Foad39c79802011-01-12 09:06:06 +00003001QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003002 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3003
Douglas Gregorec9fd132012-01-14 16:38:05 +00003004 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003005 if (PrevDecl->TypeForDecl)
3006 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3007
John McCall424cec92011-01-19 06:33:43 +00003008 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3009 Decl->TypeForDecl = newType;
3010 Types.push_back(newType);
3011 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003012}
3013
John McCall81904512011-01-06 01:58:22 +00003014QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3015 QualType modifiedType,
3016 QualType equivalentType) {
3017 llvm::FoldingSetNodeID id;
3018 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3019
3020 void *insertPos = 0;
3021 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3022 if (type) return QualType(type, 0);
3023
3024 QualType canon = getCanonicalType(equivalentType);
3025 type = new (*this, TypeAlignment)
3026 AttributedType(canon, attrKind, modifiedType, equivalentType);
3027
3028 Types.push_back(type);
3029 AttributedTypes.InsertNode(type, insertPos);
3030
3031 return QualType(type, 0);
3032}
3033
3034
John McCallcebee162009-10-18 09:09:24 +00003035/// \brief Retrieve a substitution-result type.
3036QualType
3037ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003038 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003039 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003040 && "replacement types must always be canonical");
3041
3042 llvm::FoldingSetNodeID ID;
3043 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3044 void *InsertPos = 0;
3045 SubstTemplateTypeParmType *SubstParm
3046 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3047
3048 if (!SubstParm) {
3049 SubstParm = new (*this, TypeAlignment)
3050 SubstTemplateTypeParmType(Parm, Replacement);
3051 Types.push_back(SubstParm);
3052 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3053 }
3054
3055 return QualType(SubstParm, 0);
3056}
3057
Douglas Gregorada4b792011-01-14 02:55:32 +00003058/// \brief Retrieve a
3059QualType ASTContext::getSubstTemplateTypeParmPackType(
3060 const TemplateTypeParmType *Parm,
3061 const TemplateArgument &ArgPack) {
3062#ifndef NDEBUG
3063 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
3064 PEnd = ArgPack.pack_end();
3065 P != PEnd; ++P) {
3066 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3067 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
3068 }
3069#endif
3070
3071 llvm::FoldingSetNodeID ID;
3072 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3073 void *InsertPos = 0;
3074 if (SubstTemplateTypeParmPackType *SubstParm
3075 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3076 return QualType(SubstParm, 0);
3077
3078 QualType Canon;
3079 if (!Parm->isCanonicalUnqualified()) {
3080 Canon = getCanonicalType(QualType(Parm, 0));
3081 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3082 ArgPack);
3083 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3084 }
3085
3086 SubstTemplateTypeParmPackType *SubstParm
3087 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3088 ArgPack);
3089 Types.push_back(SubstParm);
3090 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3091 return QualType(SubstParm, 0);
3092}
3093
Douglas Gregoreff93e02009-02-05 23:33:38 +00003094/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003095/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003096/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003097QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003098 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003099 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003100 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003101 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003102 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003103 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003104 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3105
3106 if (TypeParm)
3107 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003108
Chandler Carruth08836322011-05-01 00:51:33 +00003109 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003110 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003111 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003112
3113 TemplateTypeParmType *TypeCheck
3114 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3115 assert(!TypeCheck && "Template type parameter canonical type broken");
3116 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003117 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003118 TypeParm = new (*this, TypeAlignment)
3119 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003120
3121 Types.push_back(TypeParm);
3122 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3123
3124 return QualType(TypeParm, 0);
3125}
3126
John McCalle78aac42010-03-10 03:28:59 +00003127TypeSourceInfo *
3128ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3129 SourceLocation NameLoc,
3130 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003131 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003132 assert(!Name.getAsDependentTemplateName() &&
3133 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003134 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003135
3136 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003137 TemplateSpecializationTypeLoc TL =
3138 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003139 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003140 TL.setTemplateNameLoc(NameLoc);
3141 TL.setLAngleLoc(Args.getLAngleLoc());
3142 TL.setRAngleLoc(Args.getRAngleLoc());
3143 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3144 TL.setArgLocInfo(i, Args[i].getLocInfo());
3145 return DI;
3146}
3147
Mike Stump11289f42009-09-09 15:08:12 +00003148QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003149ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003150 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003151 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003152 assert(!Template.getAsDependentTemplateName() &&
3153 "No dependent template names here!");
3154
John McCall6b51f282009-11-23 01:53:49 +00003155 unsigned NumArgs = Args.size();
3156
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003157 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003158 ArgVec.reserve(NumArgs);
3159 for (unsigned i = 0; i != NumArgs; ++i)
3160 ArgVec.push_back(Args[i].getArgument());
3161
John McCall2408e322010-04-27 00:57:59 +00003162 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003163 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003164}
3165
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003166#ifndef NDEBUG
3167static bool hasAnyPackExpansions(const TemplateArgument *Args,
3168 unsigned NumArgs) {
3169 for (unsigned I = 0; I != NumArgs; ++I)
3170 if (Args[I].isPackExpansion())
3171 return true;
3172
3173 return true;
3174}
3175#endif
3176
John McCall0ad16662009-10-29 08:12:44 +00003177QualType
3178ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003179 const TemplateArgument *Args,
3180 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003181 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003182 assert(!Template.getAsDependentTemplateName() &&
3183 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003184 // Look through qualified template names.
3185 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3186 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003187
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003188 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003189 Template.getAsTemplateDecl() &&
3190 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003191 QualType CanonType;
3192 if (!Underlying.isNull())
3193 CanonType = getCanonicalType(Underlying);
3194 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003195 // We can get here with an alias template when the specialization contains
3196 // a pack expansion that does not match up with a parameter pack.
3197 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3198 "Caller must compute aliased type");
3199 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003200 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3201 NumArgs);
3202 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003203
Douglas Gregora8e02e72009-07-28 23:00:59 +00003204 // Allocate the (non-canonical) template specialization type, but don't
3205 // try to unique it: these types typically have location information that
3206 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003207 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3208 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003209 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003210 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003211 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003212 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3213 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003214
Douglas Gregor8bf42052009-02-09 18:46:07 +00003215 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003216 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003217}
3218
Mike Stump11289f42009-09-09 15:08:12 +00003219QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003220ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3221 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003222 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003223 assert(!Template.getAsDependentTemplateName() &&
3224 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003225
Douglas Gregore29139c2011-03-03 17:04:51 +00003226 // Look through qualified template names.
3227 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3228 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003229
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003230 // Build the canonical template specialization type.
3231 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003232 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003233 CanonArgs.reserve(NumArgs);
3234 for (unsigned I = 0; I != NumArgs; ++I)
3235 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3236
3237 // Determine whether this canonical template specialization type already
3238 // exists.
3239 llvm::FoldingSetNodeID ID;
3240 TemplateSpecializationType::Profile(ID, CanonTemplate,
3241 CanonArgs.data(), NumArgs, *this);
3242
3243 void *InsertPos = 0;
3244 TemplateSpecializationType *Spec
3245 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3246
3247 if (!Spec) {
3248 // Allocate a new canonical template specialization type.
3249 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3250 sizeof(TemplateArgument) * NumArgs),
3251 TypeAlignment);
3252 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3253 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003254 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003255 Types.push_back(Spec);
3256 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3257 }
3258
3259 assert(Spec->isDependentType() &&
3260 "Non-dependent template-id type must have a canonical type");
3261 return QualType(Spec, 0);
3262}
3263
3264QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003265ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3266 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003267 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003268 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003269 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003270
3271 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003272 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003273 if (T)
3274 return QualType(T, 0);
3275
Douglas Gregorc42075a2010-02-04 18:10:26 +00003276 QualType Canon = NamedType;
3277 if (!Canon.isCanonical()) {
3278 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003279 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3280 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003281 (void)CheckT;
3282 }
3283
Abramo Bagnara6150c882010-05-11 21:36:43 +00003284 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003285 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003286 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003287 return QualType(T, 0);
3288}
3289
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003290QualType
Jay Foad39c79802011-01-12 09:06:06 +00003291ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003292 llvm::FoldingSetNodeID ID;
3293 ParenType::Profile(ID, InnerType);
3294
3295 void *InsertPos = 0;
3296 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3297 if (T)
3298 return QualType(T, 0);
3299
3300 QualType Canon = InnerType;
3301 if (!Canon.isCanonical()) {
3302 Canon = getCanonicalType(InnerType);
3303 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3304 assert(!CheckT && "Paren canonical type broken");
3305 (void)CheckT;
3306 }
3307
3308 T = new (*this) ParenType(InnerType, Canon);
3309 Types.push_back(T);
3310 ParenTypes.InsertNode(T, InsertPos);
3311 return QualType(T, 0);
3312}
3313
Douglas Gregor02085352010-03-31 20:19:30 +00003314QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3315 NestedNameSpecifier *NNS,
3316 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003317 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003318 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3319
3320 if (Canon.isNull()) {
3321 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003322 ElaboratedTypeKeyword CanonKeyword = Keyword;
3323 if (Keyword == ETK_None)
3324 CanonKeyword = ETK_Typename;
3325
3326 if (CanonNNS != NNS || CanonKeyword != Keyword)
3327 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003328 }
3329
3330 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003331 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003332
3333 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003334 DependentNameType *T
3335 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003336 if (T)
3337 return QualType(T, 0);
3338
Douglas Gregor02085352010-03-31 20:19:30 +00003339 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003340 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003341 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003342 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003343}
3344
Mike Stump11289f42009-09-09 15:08:12 +00003345QualType
John McCallc392f372010-06-11 00:33:02 +00003346ASTContext::getDependentTemplateSpecializationType(
3347 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003348 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003349 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003350 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003351 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003352 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003353 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3354 ArgCopy.push_back(Args[I].getArgument());
3355 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3356 ArgCopy.size(),
3357 ArgCopy.data());
3358}
3359
3360QualType
3361ASTContext::getDependentTemplateSpecializationType(
3362 ElaboratedTypeKeyword Keyword,
3363 NestedNameSpecifier *NNS,
3364 const IdentifierInfo *Name,
3365 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003366 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003367 assert((!NNS || NNS->isDependent()) &&
3368 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003369
Douglas Gregorc42075a2010-02-04 18:10:26 +00003370 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003371 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3372 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003373
3374 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00003375 DependentTemplateSpecializationType *T
3376 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003377 if (T)
3378 return QualType(T, 0);
3379
John McCallc392f372010-06-11 00:33:02 +00003380 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003381
John McCallc392f372010-06-11 00:33:02 +00003382 ElaboratedTypeKeyword CanonKeyword = Keyword;
3383 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3384
3385 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003386 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003387 for (unsigned I = 0; I != NumArgs; ++I) {
3388 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3389 if (!CanonArgs[I].structurallyEquals(Args[I]))
3390 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003391 }
3392
John McCallc392f372010-06-11 00:33:02 +00003393 QualType Canon;
3394 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3395 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3396 Name, NumArgs,
3397 CanonArgs.data());
3398
3399 // Find the insert position again.
3400 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3401 }
3402
3403 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3404 sizeof(TemplateArgument) * NumArgs),
3405 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003406 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003407 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003408 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003409 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003410 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003411}
3412
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003413QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003414 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003415 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003416 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003417
3418 assert(Pattern->containsUnexpandedParameterPack() &&
3419 "Pack expansions must expand one or more parameter packs");
3420 void *InsertPos = 0;
3421 PackExpansionType *T
3422 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3423 if (T)
3424 return QualType(T, 0);
3425
3426 QualType Canon;
3427 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003428 Canon = getCanonicalType(Pattern);
3429 // The canonical type might not contain an unexpanded parameter pack, if it
3430 // contains an alias template specialization which ignores one of its
3431 // parameters.
3432 if (Canon->containsUnexpandedParameterPack()) {
3433 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003434
Richard Smith68eea502012-07-16 00:20:35 +00003435 // Find the insert position again, in case we inserted an element into
3436 // PackExpansionTypes and invalidated our insert position.
3437 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3438 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003439 }
3440
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003441 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003442 Types.push_back(T);
3443 PackExpansionTypes.InsertNode(T, InsertPos);
3444 return QualType(T, 0);
3445}
3446
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003447/// CmpProtocolNames - Comparison predicate for sorting protocols
3448/// alphabetically.
3449static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3450 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003451 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003452}
3453
John McCall8b07ec22010-05-15 11:32:37 +00003454static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003455 unsigned NumProtocols) {
3456 if (NumProtocols == 0) return true;
3457
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003458 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3459 return false;
3460
John McCallfc93cf92009-10-22 22:37:11 +00003461 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003462 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3463 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003464 return false;
3465 return true;
3466}
3467
3468static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003469 unsigned &NumProtocols) {
3470 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003471
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003472 // Sort protocols, keyed by name.
3473 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3474
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003475 // Canonicalize.
3476 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3477 Protocols[I] = Protocols[I]->getCanonicalDecl();
3478
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003479 // Remove duplicates.
3480 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3481 NumProtocols = ProtocolsEnd-Protocols;
3482}
3483
John McCall8b07ec22010-05-15 11:32:37 +00003484QualType ASTContext::getObjCObjectType(QualType BaseType,
3485 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003486 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003487 // If the base type is an interface and there aren't any protocols
3488 // to add, then the interface type will do just fine.
3489 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3490 return BaseType;
3491
3492 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003493 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003494 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003495 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003496 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3497 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003498
John McCall8b07ec22010-05-15 11:32:37 +00003499 // Build the canonical type, which has the canonical base type and
3500 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003501 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003502 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3503 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3504 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003505 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003506 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003507 unsigned UniqueCount = NumProtocols;
3508
John McCallfc93cf92009-10-22 22:37:11 +00003509 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003510 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3511 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003512 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003513 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3514 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003515 }
3516
3517 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003518 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3519 }
3520
3521 unsigned Size = sizeof(ObjCObjectTypeImpl);
3522 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3523 void *Mem = Allocate(Size, TypeAlignment);
3524 ObjCObjectTypeImpl *T =
3525 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3526
3527 Types.push_back(T);
3528 ObjCObjectTypes.InsertNode(T, InsertPos);
3529 return QualType(T, 0);
3530}
3531
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003532/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3533/// protocol list adopt all protocols in QT's qualified-id protocol
3534/// list.
3535bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3536 ObjCInterfaceDecl *IC) {
3537 if (!QT->isObjCQualifiedIdType())
3538 return false;
3539
3540 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3541 // If both the right and left sides have qualifiers.
3542 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3543 E = OPT->qual_end(); I != E; ++I) {
3544 ObjCProtocolDecl *Proto = *I;
3545 if (!IC->ClassImplementsProtocol(Proto, false))
3546 return false;
3547 }
3548 return true;
3549 }
3550 return false;
3551}
3552
3553/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3554/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3555/// of protocols.
3556bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3557 ObjCInterfaceDecl *IDecl) {
3558 if (!QT->isObjCQualifiedIdType())
3559 return false;
3560 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3561 if (!OPT)
3562 return false;
3563 if (!IDecl->hasDefinition())
3564 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003565 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3566 CollectInheritedProtocols(IDecl, InheritedProtocols);
3567 if (InheritedProtocols.empty())
3568 return false;
3569
3570 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator PI =
3571 InheritedProtocols.begin(),
3572 E = InheritedProtocols.end(); PI != E; ++PI) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003573 // If both the right and left sides have qualifiers.
3574 bool Adopts = false;
3575 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3576 E = OPT->qual_end(); I != E; ++I) {
3577 ObjCProtocolDecl *Proto = *I;
3578 // return 'true' if '*PI' is in the inheritance hierarchy of Proto
3579 if ((Adopts = ProtocolCompatibleWithProtocol(*PI, Proto)))
3580 break;
3581 }
3582 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003583 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003584 }
3585 return true;
3586}
3587
John McCall8b07ec22010-05-15 11:32:37 +00003588/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3589/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003590QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003591 llvm::FoldingSetNodeID ID;
3592 ObjCObjectPointerType::Profile(ID, ObjectT);
3593
3594 void *InsertPos = 0;
3595 if (ObjCObjectPointerType *QT =
3596 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3597 return QualType(QT, 0);
3598
3599 // Find the canonical object type.
3600 QualType Canonical;
3601 if (!ObjectT.isCanonical()) {
3602 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3603
3604 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003605 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3606 }
3607
Douglas Gregorf85bee62010-02-08 22:59:26 +00003608 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003609 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3610 ObjCObjectPointerType *QType =
3611 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003612
Steve Narofffb4330f2009-06-17 22:40:22 +00003613 Types.push_back(QType);
3614 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003615 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003616}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003617
Douglas Gregor1c283312010-08-11 12:19:30 +00003618/// getObjCInterfaceType - Return the unique reference to the type for the
3619/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003620QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3621 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003622 if (Decl->TypeForDecl)
3623 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003624
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003625 if (PrevDecl) {
3626 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3627 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3628 return QualType(PrevDecl->TypeForDecl, 0);
3629 }
3630
Douglas Gregor7671e532011-12-16 16:34:57 +00003631 // Prefer the definition, if there is one.
3632 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3633 Decl = Def;
3634
Douglas Gregor1c283312010-08-11 12:19:30 +00003635 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3636 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3637 Decl->TypeForDecl = T;
3638 Types.push_back(T);
3639 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003640}
3641
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003642/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3643/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003644/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003645/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003646/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003647QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003648 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003649 if (tofExpr->isTypeDependent()) {
3650 llvm::FoldingSetNodeID ID;
3651 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003652
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003653 void *InsertPos = 0;
3654 DependentTypeOfExprType *Canon
3655 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3656 if (Canon) {
3657 // We already have a "canonical" version of an identical, dependent
3658 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003659 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003660 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003661 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003662 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003663 Canon
3664 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003665 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3666 toe = Canon;
3667 }
3668 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003669 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003670 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003671 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003672 Types.push_back(toe);
3673 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003674}
3675
Steve Naroffa773cd52007-08-01 18:02:17 +00003676/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3677/// TypeOfType AST's. The only motivation to unique these nodes would be
3678/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003679/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003680/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003681QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003682 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003683 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003684 Types.push_back(tot);
3685 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003686}
3687
Anders Carlssonad6bd352009-06-24 21:24:56 +00003688
Anders Carlsson81df7b82009-06-24 19:06:50 +00003689/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3690/// DecltypeType AST's. The only motivation to unique these nodes would be
3691/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003692/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003693/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003694QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003695 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003696
3697 // C++0x [temp.type]p2:
3698 // If an expression e involves a template parameter, decltype(e) denotes a
3699 // unique dependent type. Two such decltype-specifiers refer to the same
3700 // type only if their expressions are equivalent (14.5.6.1).
3701 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003702 llvm::FoldingSetNodeID ID;
3703 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003704
Douglas Gregora21f6c32009-07-30 23:36:40 +00003705 void *InsertPos = 0;
3706 DependentDecltypeType *Canon
3707 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3708 if (Canon) {
3709 // We already have a "canonical" version of an equivalent, dependent
3710 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003711 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003712 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003713 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003714 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003715 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003716 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3717 dt = Canon;
3718 }
3719 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003720 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3721 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003722 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003723 Types.push_back(dt);
3724 return QualType(dt, 0);
3725}
3726
Alexis Hunte852b102011-05-24 22:41:36 +00003727/// getUnaryTransformationType - We don't unique these, since the memory
3728/// savings are minimal and these are rare.
3729QualType ASTContext::getUnaryTransformType(QualType BaseType,
3730 QualType UnderlyingType,
3731 UnaryTransformType::UTTKind Kind)
3732 const {
3733 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003734 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3735 Kind,
3736 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003737 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003738 Types.push_back(Ty);
3739 return QualType(Ty, 0);
3740}
3741
Richard Smith2a7d4812013-05-04 07:00:32 +00003742/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3743/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3744/// canonical deduced-but-dependent 'auto' type.
3745QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003746 bool IsDependent) const {
3747 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003748 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003749
Richard Smith2a7d4812013-05-04 07:00:32 +00003750 // Look in the folding set for an existing type.
Richard Smithb2bc2e62011-02-21 20:05:19 +00003751 void *InsertPos = 0;
Richard Smith2a7d4812013-05-04 07:00:32 +00003752 llvm::FoldingSetNodeID ID;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003753 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003754 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3755 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003756
Richard Smith74aeef52013-04-26 16:15:35 +00003757 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003758 IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003759 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003760 Types.push_back(AT);
3761 if (InsertPos)
3762 AutoTypes.InsertNode(AT, InsertPos);
3763 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003764}
3765
Eli Friedman0dfb8892011-10-06 23:00:33 +00003766/// getAtomicType - Return the uniqued reference to the atomic type for
3767/// the given value type.
3768QualType ASTContext::getAtomicType(QualType T) const {
3769 // Unique pointers, to guarantee there is only one pointer of a particular
3770 // structure.
3771 llvm::FoldingSetNodeID ID;
3772 AtomicType::Profile(ID, T);
3773
3774 void *InsertPos = 0;
3775 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3776 return QualType(AT, 0);
3777
3778 // If the atomic value type isn't canonical, this won't be a canonical type
3779 // either, so fill in the canonical type field.
3780 QualType Canonical;
3781 if (!T.isCanonical()) {
3782 Canonical = getAtomicType(getCanonicalType(T));
3783
3784 // Get the new insert position for the node we care about.
3785 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3786 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3787 }
3788 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3789 Types.push_back(New);
3790 AtomicTypes.InsertNode(New, InsertPos);
3791 return QualType(New, 0);
3792}
3793
Richard Smith02e85f32011-04-14 22:09:26 +00003794/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3795QualType ASTContext::getAutoDeductType() const {
3796 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00003797 AutoDeductTy = QualType(
3798 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003799 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00003800 0);
Richard Smith02e85f32011-04-14 22:09:26 +00003801 return AutoDeductTy;
3802}
3803
3804/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3805QualType ASTContext::getAutoRRefDeductType() const {
3806 if (AutoRRefDeductTy.isNull())
3807 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3808 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3809 return AutoRRefDeductTy;
3810}
3811
Chris Lattnerfb072462007-01-23 05:45:31 +00003812/// getTagDeclType - Return the unique reference to the type for the
3813/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003814QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003815 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003816 // FIXME: What is the design on getTagDeclType when it requires casting
3817 // away const? mutable?
3818 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003819}
3820
Mike Stump11289f42009-09-09 15:08:12 +00003821/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3822/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3823/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003824CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003825 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003826}
Chris Lattnerfb072462007-01-23 05:45:31 +00003827
Hans Wennborg27541db2011-10-27 08:29:09 +00003828/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3829CanQualType ASTContext::getIntMaxType() const {
3830 return getFromTargetType(Target->getIntMaxType());
3831}
3832
3833/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3834CanQualType ASTContext::getUIntMaxType() const {
3835 return getFromTargetType(Target->getUIntMaxType());
3836}
3837
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003838/// getSignedWCharType - Return the type of "signed wchar_t".
3839/// Used when in C++, as a GCC extension.
3840QualType ASTContext::getSignedWCharType() const {
3841 // FIXME: derive from "Target" ?
3842 return WCharTy;
3843}
3844
3845/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3846/// Used when in C++, as a GCC extension.
3847QualType ASTContext::getUnsignedWCharType() const {
3848 // FIXME: derive from "Target" ?
3849 return UnsignedIntTy;
3850}
3851
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00003852QualType ASTContext::getIntPtrType() const {
3853 return getFromTargetType(Target->getIntPtrType());
3854}
3855
3856QualType ASTContext::getUIntPtrType() const {
3857 return getCorrespondingUnsignedType(getIntPtrType());
3858}
3859
Hans Wennborg27541db2011-10-27 08:29:09 +00003860/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003861/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3862QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003863 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003864}
3865
Eli Friedman4e91899e2012-11-27 02:58:24 +00003866/// \brief Return the unique type for "pid_t" defined in
3867/// <sys/types.h>. We need this to compute the correct type for vfork().
3868QualType ASTContext::getProcessIDType() const {
3869 return getFromTargetType(Target->getProcessIDType());
3870}
3871
Chris Lattnera21ad802008-04-02 05:18:44 +00003872//===----------------------------------------------------------------------===//
3873// Type Operators
3874//===----------------------------------------------------------------------===//
3875
Jay Foad39c79802011-01-12 09:06:06 +00003876CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003877 // Push qualifiers into arrays, and then discard any remaining
3878 // qualifiers.
3879 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003880 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003881 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003882 QualType Result;
3883 if (isa<ArrayType>(Ty)) {
3884 Result = getArrayDecayedType(QualType(Ty,0));
3885 } else if (isa<FunctionType>(Ty)) {
3886 Result = getPointerType(QualType(Ty, 0));
3887 } else {
3888 Result = QualType(Ty, 0);
3889 }
3890
3891 return CanQualType::CreateUnsafe(Result);
3892}
3893
John McCall6c9dd522011-01-18 07:41:22 +00003894QualType ASTContext::getUnqualifiedArrayType(QualType type,
3895 Qualifiers &quals) {
3896 SplitQualType splitType = type.getSplitUnqualifiedType();
3897
3898 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3899 // the unqualified desugared type and then drops it on the floor.
3900 // We then have to strip that sugar back off with
3901 // getUnqualifiedDesugaredType(), which is silly.
3902 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003903 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003904
3905 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003906 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003907 quals = splitType.Quals;
3908 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003909 }
3910
John McCall6c9dd522011-01-18 07:41:22 +00003911 // Otherwise, recurse on the array's element type.
3912 QualType elementType = AT->getElementType();
3913 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3914
3915 // If that didn't change the element type, AT has no qualifiers, so we
3916 // can just use the results in splitType.
3917 if (elementType == unqualElementType) {
3918 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003919 quals = splitType.Quals;
3920 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003921 }
3922
3923 // Otherwise, add in the qualifiers from the outermost type, then
3924 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003925 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003926
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003927 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003928 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003929 CAT->getSizeModifier(), 0);
3930 }
3931
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003932 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003933 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003934 }
3935
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003936 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003937 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003938 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003939 VAT->getSizeModifier(),
3940 VAT->getIndexTypeCVRQualifiers(),
3941 VAT->getBracketsRange());
3942 }
3943
3944 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003945 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003946 DSAT->getSizeModifier(), 0,
3947 SourceRange());
3948}
3949
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003950/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3951/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3952/// they point to and return true. If T1 and T2 aren't pointer types
3953/// or pointer-to-member types, or if they are not similar at this
3954/// level, returns false and leaves T1 and T2 unchanged. Top-level
3955/// qualifiers on T1 and T2 are ignored. This function will typically
3956/// be called in a loop that successively "unwraps" pointer and
3957/// pointer-to-member types to compare them at each level.
3958bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3959 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3960 *T2PtrType = T2->getAs<PointerType>();
3961 if (T1PtrType && T2PtrType) {
3962 T1 = T1PtrType->getPointeeType();
3963 T2 = T2PtrType->getPointeeType();
3964 return true;
3965 }
3966
3967 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3968 *T2MPType = T2->getAs<MemberPointerType>();
3969 if (T1MPType && T2MPType &&
3970 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3971 QualType(T2MPType->getClass(), 0))) {
3972 T1 = T1MPType->getPointeeType();
3973 T2 = T2MPType->getPointeeType();
3974 return true;
3975 }
3976
David Blaikiebbafb8a2012-03-11 07:00:24 +00003977 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003978 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3979 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3980 if (T1OPType && T2OPType) {
3981 T1 = T1OPType->getPointeeType();
3982 T2 = T2OPType->getPointeeType();
3983 return true;
3984 }
3985 }
3986
3987 // FIXME: Block pointers, too?
3988
3989 return false;
3990}
3991
Jay Foad39c79802011-01-12 09:06:06 +00003992DeclarationNameInfo
3993ASTContext::getNameForTemplate(TemplateName Name,
3994 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003995 switch (Name.getKind()) {
3996 case TemplateName::QualifiedTemplate:
3997 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003998 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003999 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4000 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004001
John McCalld9dfe3a2011-06-30 08:33:18 +00004002 case TemplateName::OverloadedTemplate: {
4003 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4004 // DNInfo work in progress: CHECKME: what about DNLoc?
4005 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4006 }
4007
4008 case TemplateName::DependentTemplate: {
4009 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004010 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004011 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004012 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4013 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004014 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004015 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4016 // DNInfo work in progress: FIXME: source locations?
4017 DeclarationNameLoc DNLoc;
4018 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4019 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4020 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004021 }
4022 }
4023
John McCalld9dfe3a2011-06-30 08:33:18 +00004024 case TemplateName::SubstTemplateTemplateParm: {
4025 SubstTemplateTemplateParmStorage *subst
4026 = Name.getAsSubstTemplateTemplateParm();
4027 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4028 NameLoc);
4029 }
4030
4031 case TemplateName::SubstTemplateTemplateParmPack: {
4032 SubstTemplateTemplateParmPackStorage *subst
4033 = Name.getAsSubstTemplateTemplateParmPack();
4034 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4035 NameLoc);
4036 }
4037 }
4038
4039 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004040}
4041
Jay Foad39c79802011-01-12 09:06:06 +00004042TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004043 switch (Name.getKind()) {
4044 case TemplateName::QualifiedTemplate:
4045 case TemplateName::Template: {
4046 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004047 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004048 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004049 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4050
4051 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004052 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004053 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004054
John McCalld9dfe3a2011-06-30 08:33:18 +00004055 case TemplateName::OverloadedTemplate:
4056 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004057
John McCalld9dfe3a2011-06-30 08:33:18 +00004058 case TemplateName::DependentTemplate: {
4059 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4060 assert(DTN && "Non-dependent template names must refer to template decls.");
4061 return DTN->CanonicalTemplateName;
4062 }
4063
4064 case TemplateName::SubstTemplateTemplateParm: {
4065 SubstTemplateTemplateParmStorage *subst
4066 = Name.getAsSubstTemplateTemplateParm();
4067 return getCanonicalTemplateName(subst->getReplacement());
4068 }
4069
4070 case TemplateName::SubstTemplateTemplateParmPack: {
4071 SubstTemplateTemplateParmPackStorage *subst
4072 = Name.getAsSubstTemplateTemplateParmPack();
4073 TemplateTemplateParmDecl *canonParameter
4074 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4075 TemplateArgument canonArgPack
4076 = getCanonicalTemplateArgument(subst->getArgumentPack());
4077 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4078 }
4079 }
4080
4081 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004082}
4083
Douglas Gregoradee3e32009-11-11 23:06:43 +00004084bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4085 X = getCanonicalTemplateName(X);
4086 Y = getCanonicalTemplateName(Y);
4087 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4088}
4089
Mike Stump11289f42009-09-09 15:08:12 +00004090TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004091ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004092 switch (Arg.getKind()) {
4093 case TemplateArgument::Null:
4094 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004095
Douglas Gregora8e02e72009-07-28 23:00:59 +00004096 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004097 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004098
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004099 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004100 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4101 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004102 }
Mike Stump11289f42009-09-09 15:08:12 +00004103
Eli Friedmanb826a002012-09-26 02:36:12 +00004104 case TemplateArgument::NullPtr:
4105 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4106 /*isNullPtr*/true);
4107
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004108 case TemplateArgument::Template:
4109 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004110
4111 case TemplateArgument::TemplateExpansion:
4112 return TemplateArgument(getCanonicalTemplateName(
4113 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004114 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004115
Douglas Gregora8e02e72009-07-28 23:00:59 +00004116 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004117 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004118
Douglas Gregora8e02e72009-07-28 23:00:59 +00004119 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004120 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004121
Douglas Gregora8e02e72009-07-28 23:00:59 +00004122 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004123 if (Arg.pack_size() == 0)
4124 return Arg;
4125
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004126 TemplateArgument *CanonArgs
4127 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004128 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004129 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004130 AEnd = Arg.pack_end();
4131 A != AEnd; (void)++A, ++Idx)
4132 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004133
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004134 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00004135 }
4136 }
4137
4138 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004139 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004140}
4141
Douglas Gregor333489b2009-03-27 23:10:48 +00004142NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004143ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004144 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00004145 return 0;
4146
4147 switch (NNS->getKind()) {
4148 case NestedNameSpecifier::Identifier:
4149 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004150 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004151 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4152 NNS->getAsIdentifier());
4153
4154 case NestedNameSpecifier::Namespace:
4155 // A namespace is canonical; build a nested-name-specifier with
4156 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004157 return NestedNameSpecifier::Create(*this, 0,
4158 NNS->getAsNamespace()->getOriginalNamespace());
4159
4160 case NestedNameSpecifier::NamespaceAlias:
4161 // A namespace is canonical; build a nested-name-specifier with
4162 // this namespace and no prefix.
4163 return NestedNameSpecifier::Create(*this, 0,
4164 NNS->getAsNamespaceAlias()->getNamespace()
4165 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004166
4167 case NestedNameSpecifier::TypeSpec:
4168 case NestedNameSpecifier::TypeSpecWithTemplate: {
4169 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004170
4171 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4172 // break it apart into its prefix and identifier, then reconsititute those
4173 // as the canonical nested-name-specifier. This is required to canonicalize
4174 // a dependent nested-name-specifier involving typedefs of dependent-name
4175 // types, e.g.,
4176 // typedef typename T::type T1;
4177 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004178 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4179 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004180 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004181
Eli Friedman5358a0a2012-03-03 04:09:56 +00004182 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4183 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4184 // first place?
John McCall33ddac02011-01-19 10:06:00 +00004185 return NestedNameSpecifier::Create(*this, 0, false,
4186 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004187 }
4188
4189 case NestedNameSpecifier::Global:
4190 // The global specifier is canonical and unique.
4191 return NNS;
4192 }
4193
David Blaikie8a40f702012-01-17 06:56:22 +00004194 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004195}
4196
Chris Lattner7adf0762008-08-04 07:31:14 +00004197
Jay Foad39c79802011-01-12 09:06:06 +00004198const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004199 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004200 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004201 // Handle the common positive case fast.
4202 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4203 return AT;
4204 }
Mike Stump11289f42009-09-09 15:08:12 +00004205
John McCall8ccfcb52009-09-24 19:53:00 +00004206 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004207 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00004208 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004209
John McCall8ccfcb52009-09-24 19:53:00 +00004210 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004211 // implements C99 6.7.3p8: "If the specification of an array type includes
4212 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004213
Chris Lattner7adf0762008-08-04 07:31:14 +00004214 // If we get here, we either have type qualifiers on the type, or we have
4215 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004216 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004217
John McCall33ddac02011-01-19 10:06:00 +00004218 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004219 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004220
Chris Lattner7adf0762008-08-04 07:31:14 +00004221 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004222 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00004223 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004224 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004225
Chris Lattner7adf0762008-08-04 07:31:14 +00004226 // Otherwise, we have an array and we have qualifiers on it. Push the
4227 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004228 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004229
Chris Lattner7adf0762008-08-04 07:31:14 +00004230 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4231 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4232 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004233 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004234 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4235 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4236 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004237 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004238
Mike Stump11289f42009-09-09 15:08:12 +00004239 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004240 = dyn_cast<DependentSizedArrayType>(ATy))
4241 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004242 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004243 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004244 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004245 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004246 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004247
Chris Lattner7adf0762008-08-04 07:31:14 +00004248 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004249 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004250 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004251 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004252 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004253 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004254}
4255
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004256QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004257 if (T->isArrayType() || T->isFunctionType())
4258 return getDecayedType(T);
4259 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004260}
4261
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004262QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004263 T = getVariableArrayDecayedType(T);
4264 T = getAdjustedParameterType(T);
4265 return T.getUnqualifiedType();
4266}
4267
Chris Lattnera21ad802008-04-02 05:18:44 +00004268/// getArrayDecayedType - Return the properly qualified result of decaying the
4269/// specified array type to a pointer. This operation is non-trivial when
4270/// handling typedefs etc. The canonical type of "T" must be an array type,
4271/// this returns a pointer to a properly qualified element of the array.
4272///
4273/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004274QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004275 // Get the element type with 'getAsArrayType' so that we don't lose any
4276 // typedefs in the element type of the array. This also handles propagation
4277 // of type qualifiers from the array type into the element type if present
4278 // (C99 6.7.3p8).
4279 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4280 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004281
Chris Lattner7adf0762008-08-04 07:31:14 +00004282 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004283
4284 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004285 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004286}
4287
John McCall33ddac02011-01-19 10:06:00 +00004288QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4289 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004290}
4291
John McCall33ddac02011-01-19 10:06:00 +00004292QualType ASTContext::getBaseElementType(QualType type) const {
4293 Qualifiers qs;
4294 while (true) {
4295 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004296 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004297 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004298
John McCall33ddac02011-01-19 10:06:00 +00004299 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004300 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004301 }
Mike Stump11289f42009-09-09 15:08:12 +00004302
John McCall33ddac02011-01-19 10:06:00 +00004303 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004304}
4305
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004306/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004307uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004308ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4309 uint64_t ElementCount = 1;
4310 do {
4311 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004312 CA = dyn_cast_or_null<ConstantArrayType>(
4313 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004314 } while (CA);
4315 return ElementCount;
4316}
4317
Steve Naroff0af91202007-04-27 21:51:21 +00004318/// getFloatingRank - Return a relative rank for floating point types.
4319/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004320static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004321 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004322 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004323
John McCall9dd450b2009-09-21 23:43:11 +00004324 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4325 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004326 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004327 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004328 case BuiltinType::Float: return FloatRank;
4329 case BuiltinType::Double: return DoubleRank;
4330 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004331 }
4332}
4333
Mike Stump11289f42009-09-09 15:08:12 +00004334/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4335/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004336/// 'typeDomain' is a real floating point or complex type.
4337/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004338QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4339 QualType Domain) const {
4340 FloatingRank EltRank = getFloatingRank(Size);
4341 if (Domain->isComplexType()) {
4342 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004343 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004344 case FloatRank: return FloatComplexTy;
4345 case DoubleRank: return DoubleComplexTy;
4346 case LongDoubleRank: return LongDoubleComplexTy;
4347 }
Steve Naroff0af91202007-04-27 21:51:21 +00004348 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004349
4350 assert(Domain->isRealFloatingType() && "Unknown domain!");
4351 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004352 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004353 case FloatRank: return FloatTy;
4354 case DoubleRank: return DoubleTy;
4355 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004356 }
David Blaikief47fa302012-01-17 02:30:50 +00004357 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004358}
4359
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004360/// getFloatingTypeOrder - Compare the rank of the two specified floating
4361/// point types, ignoring the domain of the type (i.e. 'double' ==
4362/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004363/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004364int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004365 FloatingRank LHSR = getFloatingRank(LHS);
4366 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004367
Chris Lattnerb90739d2008-04-06 23:38:49 +00004368 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004369 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004370 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004371 return 1;
4372 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004373}
4374
Chris Lattner76a00cf2008-04-06 22:59:24 +00004375/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4376/// routine will assert if passed a built-in type that isn't an integer or enum,
4377/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004378unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004379 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004380
Chris Lattner76a00cf2008-04-06 22:59:24 +00004381 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004382 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004383 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004384 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004385 case BuiltinType::Char_S:
4386 case BuiltinType::Char_U:
4387 case BuiltinType::SChar:
4388 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004389 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004390 case BuiltinType::Short:
4391 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004392 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004393 case BuiltinType::Int:
4394 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004395 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004396 case BuiltinType::Long:
4397 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004398 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004399 case BuiltinType::LongLong:
4400 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004401 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004402 case BuiltinType::Int128:
4403 case BuiltinType::UInt128:
4404 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004405 }
4406}
4407
Eli Friedman629ffb92009-08-20 04:21:42 +00004408/// \brief Whether this is a promotable bitfield reference according
4409/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4410///
4411/// \returns the type this bit-field will promote to, or NULL if no
4412/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004413QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004414 if (E->isTypeDependent() || E->isValueDependent())
4415 return QualType();
4416
John McCalld25db7e2013-05-06 21:39:12 +00004417 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004418 if (!Field)
4419 return QualType();
4420
4421 QualType FT = Field->getType();
4422
Richard Smithcaf33902011-10-10 18:28:20 +00004423 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004424 uint64_t IntSize = getTypeSize(IntTy);
4425 // GCC extension compatibility: if the bit-field size is less than or equal
4426 // to the size of int, it gets promoted no matter what its type is.
4427 // For instance, unsigned long bf : 4 gets promoted to signed int.
4428 if (BitWidth < IntSize)
4429 return IntTy;
4430
4431 if (BitWidth == IntSize)
4432 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4433
4434 // Types bigger than int are not subject to promotions, and therefore act
4435 // like the base type.
4436 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4437 // is ridiculous.
4438 return QualType();
4439}
4440
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004441/// getPromotedIntegerType - Returns the type that Promotable will
4442/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4443/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004444QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004445 assert(!Promotable.isNull());
4446 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004447 if (const EnumType *ET = Promotable->getAs<EnumType>())
4448 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004449
4450 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4451 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4452 // (3.9.1) can be converted to a prvalue of the first of the following
4453 // types that can represent all the values of its underlying type:
4454 // int, unsigned int, long int, unsigned long int, long long int, or
4455 // unsigned long long int [...]
4456 // FIXME: Is there some better way to compute this?
4457 if (BT->getKind() == BuiltinType::WChar_S ||
4458 BT->getKind() == BuiltinType::WChar_U ||
4459 BT->getKind() == BuiltinType::Char16 ||
4460 BT->getKind() == BuiltinType::Char32) {
4461 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4462 uint64_t FromSize = getTypeSize(BT);
4463 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4464 LongLongTy, UnsignedLongLongTy };
4465 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4466 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4467 if (FromSize < ToSize ||
4468 (FromSize == ToSize &&
4469 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4470 return PromoteTypes[Idx];
4471 }
4472 llvm_unreachable("char type should fit into long long");
4473 }
4474 }
4475
4476 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004477 if (Promotable->isSignedIntegerType())
4478 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004479 uint64_t PromotableSize = getIntWidth(Promotable);
4480 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004481 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4482 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4483}
4484
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004485/// \brief Recurses in pointer/array types until it finds an objc retainable
4486/// type and returns its ownership.
4487Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4488 while (!T.isNull()) {
4489 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4490 return T.getObjCLifetime();
4491 if (T->isArrayType())
4492 T = getBaseElementType(T);
4493 else if (const PointerType *PT = T->getAs<PointerType>())
4494 T = PT->getPointeeType();
4495 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004496 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004497 else
4498 break;
4499 }
4500
4501 return Qualifiers::OCL_None;
4502}
4503
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004504static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4505 // Incomplete enum types are not treated as integer types.
4506 // FIXME: In C++, enum types are never integer types.
4507 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4508 return ET->getDecl()->getIntegerType().getTypePtr();
4509 return NULL;
4510}
4511
Mike Stump11289f42009-09-09 15:08:12 +00004512/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004513/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004514/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004515int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004516 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4517 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004518
4519 // Unwrap enums to their underlying type.
4520 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4521 LHSC = getIntegerTypeForEnum(ET);
4522 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4523 RHSC = getIntegerTypeForEnum(ET);
4524
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004525 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004526
Chris Lattner76a00cf2008-04-06 22:59:24 +00004527 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4528 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004529
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004530 unsigned LHSRank = getIntegerRank(LHSC);
4531 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004532
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004533 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4534 if (LHSRank == RHSRank) return 0;
4535 return LHSRank > RHSRank ? 1 : -1;
4536 }
Mike Stump11289f42009-09-09 15:08:12 +00004537
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004538 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4539 if (LHSUnsigned) {
4540 // If the unsigned [LHS] type is larger, return it.
4541 if (LHSRank >= RHSRank)
4542 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004543
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004544 // If the signed type can represent all values of the unsigned type, it
4545 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004546 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004547 return -1;
4548 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004549
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004550 // If the unsigned [RHS] type is larger, return it.
4551 if (RHSRank >= LHSRank)
4552 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004553
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004554 // If the signed type can represent all values of the unsigned type, it
4555 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004556 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004557 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004558}
Anders Carlsson98f07902007-08-17 05:31:46 +00004559
Anders Carlsson6d417272009-11-14 21:45:58 +00004560static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004561CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4562 DeclContext *DC, IdentifierInfo *Id) {
4563 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004564 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004565 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004566 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004567 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004568}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004569
Mike Stump11289f42009-09-09 15:08:12 +00004570// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004571QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004572 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00004573 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004574 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004575 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00004576 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004577
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004578 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004579
Anders Carlsson98f07902007-08-17 05:31:46 +00004580 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004581 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004582 // int flags;
4583 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004584 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004585 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004586 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004587 FieldTypes[3] = LongTy;
4588
Anders Carlsson98f07902007-08-17 05:31:46 +00004589 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004590 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004591 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004592 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004593 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004594 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004595 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004596 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004597 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004598 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004599 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004600 }
4601
Douglas Gregord5058122010-02-11 01:19:42 +00004602 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004603 }
Mike Stump11289f42009-09-09 15:08:12 +00004604
Anders Carlsson98f07902007-08-17 05:31:46 +00004605 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004606}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004607
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004608QualType ASTContext::getObjCSuperType() const {
4609 if (ObjCSuperType.isNull()) {
4610 RecordDecl *ObjCSuperTypeDecl =
4611 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4612 TUDecl->addDecl(ObjCSuperTypeDecl);
4613 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4614 }
4615 return ObjCSuperType;
4616}
4617
Douglas Gregor512b0772009-04-23 22:29:11 +00004618void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004619 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004620 assert(Rec && "Invalid CFConstantStringType");
4621 CFConstantStringTypeDecl = Rec->getDecl();
4622}
4623
Jay Foad39c79802011-01-12 09:06:06 +00004624QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004625 if (BlockDescriptorType)
4626 return getTagDeclType(BlockDescriptorType);
4627
4628 RecordDecl *T;
4629 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004630 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004631 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00004632 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004633
4634 QualType FieldTypes[] = {
4635 UnsignedLongTy,
4636 UnsignedLongTy,
4637 };
4638
Craig Topperd6d31ac2013-07-15 08:24:27 +00004639 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004640 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004641 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004642 };
4643
4644 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004645 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00004646 SourceLocation(),
4647 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004648 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00004649 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004650 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004651 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004652 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00004653 T->addDecl(Field);
4654 }
4655
Douglas Gregord5058122010-02-11 01:19:42 +00004656 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004657
4658 BlockDescriptorType = T;
4659
4660 return getTagDeclType(BlockDescriptorType);
4661}
4662
Jay Foad39c79802011-01-12 09:06:06 +00004663QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004664 if (BlockDescriptorExtendedType)
4665 return getTagDeclType(BlockDescriptorExtendedType);
4666
4667 RecordDecl *T;
4668 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004669 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004670 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00004671 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004672
4673 QualType FieldTypes[] = {
4674 UnsignedLongTy,
4675 UnsignedLongTy,
4676 getPointerType(VoidPtrTy),
4677 getPointerType(VoidPtrTy)
4678 };
4679
Craig Topperd6d31ac2013-07-15 08:24:27 +00004680 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004681 "reserved",
4682 "Size",
4683 "CopyFuncPtr",
4684 "DestroyFuncPtr"
4685 };
4686
4687 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004688 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004689 SourceLocation(),
4690 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004691 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004692 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004693 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004694 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004695 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004696 T->addDecl(Field);
4697 }
4698
Douglas Gregord5058122010-02-11 01:19:42 +00004699 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004700
4701 BlockDescriptorExtendedType = T;
4702
4703 return getTagDeclType(BlockDescriptorExtendedType);
4704}
4705
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004706/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4707/// requires copy/dispose. Note that this must match the logic
4708/// in buildByrefHelpers.
4709bool ASTContext::BlockRequiresCopying(QualType Ty,
4710 const VarDecl *D) {
4711 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4712 const Expr *copyExpr = getBlockVarCopyInits(D);
4713 if (!copyExpr && record->hasTrivialDestructor()) return false;
4714
Mike Stump94967902009-10-21 18:16:27 +00004715 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004716 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004717
4718 if (!Ty->isObjCRetainableType()) return false;
4719
4720 Qualifiers qs = Ty.getQualifiers();
4721
4722 // If we have lifetime, that dominates.
4723 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4724 assert(getLangOpts().ObjCAutoRefCount);
4725
4726 switch (lifetime) {
4727 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4728
4729 // These are just bits as far as the runtime is concerned.
4730 case Qualifiers::OCL_ExplicitNone:
4731 case Qualifiers::OCL_Autoreleasing:
4732 return false;
4733
4734 // Tell the runtime that this is ARC __weak, called by the
4735 // byref routines.
4736 case Qualifiers::OCL_Weak:
4737 // ARC __strong __block variables need to be retained.
4738 case Qualifiers::OCL_Strong:
4739 return true;
4740 }
4741 llvm_unreachable("fell out of lifetime switch!");
4742 }
4743 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4744 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004745}
4746
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004747bool ASTContext::getByrefLifetime(QualType Ty,
4748 Qualifiers::ObjCLifetime &LifeTime,
4749 bool &HasByrefExtendedLayout) const {
4750
4751 if (!getLangOpts().ObjC1 ||
4752 getLangOpts().getGC() != LangOptions::NonGC)
4753 return false;
4754
4755 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004756 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004757 HasByrefExtendedLayout = true;
4758 LifeTime = Qualifiers::OCL_None;
4759 }
4760 else if (getLangOpts().ObjCAutoRefCount)
4761 LifeTime = Ty.getObjCLifetime();
4762 // MRR.
4763 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4764 LifeTime = Qualifiers::OCL_ExplicitNone;
4765 else
4766 LifeTime = Qualifiers::OCL_None;
4767 return true;
4768}
4769
Douglas Gregorbab8a962011-09-08 01:46:34 +00004770TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4771 if (!ObjCInstanceTypeDecl)
4772 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4773 getTranslationUnitDecl(),
4774 SourceLocation(),
4775 SourceLocation(),
4776 &Idents.get("instancetype"),
4777 getTrivialTypeSourceInfo(getObjCIdType()));
4778 return ObjCInstanceTypeDecl;
4779}
4780
Anders Carlsson18acd442007-10-29 06:33:42 +00004781// This returns true if a type has been typedefed to BOOL:
4782// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004783static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004784 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004785 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4786 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004787
Anders Carlssond8499822007-10-29 05:01:08 +00004788 return false;
4789}
4790
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004791/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004792/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004793CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004794 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4795 return CharUnits::Zero();
4796
Ken Dyck40775002010-01-11 17:06:35 +00004797 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004798
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004799 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004800 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004801 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004802 // Treat arrays as pointers, since that's how they're passed in.
4803 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004804 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004805 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004806}
4807
4808static inline
4809std::string charUnitsToString(const CharUnits &CU) {
4810 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004811}
4812
John McCall351762c2011-02-07 10:33:21 +00004813/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004814/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004815std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4816 std::string S;
4817
David Chisnall950a9512009-11-17 19:33:30 +00004818 const BlockDecl *Decl = Expr->getBlockDecl();
4819 QualType BlockTy =
4820 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4821 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004822 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004823 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4824 BlockTy->getAs<FunctionType>()->getResultType(),
4825 S, true /*Extended*/);
4826 else
4827 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4828 S);
David Chisnall950a9512009-11-17 19:33:30 +00004829 // Compute size of all parameters.
4830 // Start with computing size of a pointer in number of bytes.
4831 // FIXME: There might(should) be a better way of doing this computation!
4832 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004833 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4834 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004835 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004836 E = Decl->param_end(); PI != E; ++PI) {
4837 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004838 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004839 if (sz.isZero())
4840 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004841 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004842 ParmOffset += sz;
4843 }
4844 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004845 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004846 // Block pointer and offset.
4847 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004848
4849 // Argument types.
4850 ParmOffset = PtrSize;
4851 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4852 Decl->param_end(); PI != E; ++PI) {
4853 ParmVarDecl *PVDecl = *PI;
4854 QualType PType = PVDecl->getOriginalType();
4855 if (const ArrayType *AT =
4856 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4857 // Use array's original type only if it has known number of
4858 // elements.
4859 if (!isa<ConstantArrayType>(AT))
4860 PType = PVDecl->getType();
4861 } else if (PType->isFunctionType())
4862 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004863 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004864 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4865 S, true /*Extended*/);
4866 else
4867 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004868 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004869 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004870 }
John McCall351762c2011-02-07 10:33:21 +00004871
4872 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004873}
4874
Douglas Gregora9d84932011-05-27 01:19:52 +00004875bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004876 std::string& S) {
4877 // Encode result type.
4878 getObjCEncodingForType(Decl->getResultType(), S);
4879 CharUnits ParmOffset;
4880 // Compute size of all parameters.
4881 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4882 E = Decl->param_end(); PI != E; ++PI) {
4883 QualType PType = (*PI)->getType();
4884 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004885 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004886 continue;
4887
David Chisnall50e4eba2010-12-30 14:05:53 +00004888 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004889 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004890 ParmOffset += sz;
4891 }
4892 S += charUnitsToString(ParmOffset);
4893 ParmOffset = CharUnits::Zero();
4894
4895 // Argument types.
4896 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4897 E = Decl->param_end(); PI != E; ++PI) {
4898 ParmVarDecl *PVDecl = *PI;
4899 QualType PType = PVDecl->getOriginalType();
4900 if (const ArrayType *AT =
4901 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4902 // Use array's original type only if it has known number of
4903 // elements.
4904 if (!isa<ConstantArrayType>(AT))
4905 PType = PVDecl->getType();
4906 } else if (PType->isFunctionType())
4907 PType = PVDecl->getType();
4908 getObjCEncodingForType(PType, S);
4909 S += charUnitsToString(ParmOffset);
4910 ParmOffset += getObjCEncodingTypeSize(PType);
4911 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004912
4913 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004914}
4915
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004916/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4917/// method parameter or return type. If Extended, include class names and
4918/// block object types.
4919void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4920 QualType T, std::string& S,
4921 bool Extended) const {
4922 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4923 getObjCEncodingForTypeQualifier(QT, S);
4924 // Encode parameter type.
4925 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4926 true /*OutermostType*/,
4927 false /*EncodingProperty*/,
4928 false /*StructField*/,
4929 Extended /*EncodeBlockParameters*/,
4930 Extended /*EncodeClassNames*/);
4931}
4932
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004933/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004934/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004935bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004936 std::string& S,
4937 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004938 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004939 // Encode return type.
4940 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4941 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004942 // Compute size of all parameters.
4943 // Start with computing size of a pointer in number of bytes.
4944 // FIXME: There might(should) be a better way of doing this computation!
4945 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004946 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004947 // The first two arguments (self and _cmd) are pointers; account for
4948 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004949 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004950 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004951 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004952 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004953 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004954 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004955 continue;
4956
Ken Dyck40775002010-01-11 17:06:35 +00004957 assert (sz.isPositive() &&
4958 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004959 ParmOffset += sz;
4960 }
Ken Dyck40775002010-01-11 17:06:35 +00004961 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004962 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004963 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004964
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004965 // Argument types.
4966 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004967 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004968 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004969 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004970 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004971 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004972 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4973 // Use array's original type only if it has known number of
4974 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004975 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004976 PType = PVDecl->getType();
4977 } else if (PType->isFunctionType())
4978 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004979 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4980 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004981 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004982 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004983 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004984
4985 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004986}
4987
Daniel Dunbar4932b362008-08-28 04:38:10 +00004988/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004989/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004990/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4991/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004992/// Property attributes are stored as a comma-delimited C string. The simple
4993/// attributes readonly and bycopy are encoded as single characters. The
4994/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4995/// encoded as single characters, followed by an identifier. Property types
4996/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004997/// these attributes are defined by the following enumeration:
4998/// @code
4999/// enum PropertyAttributes {
5000/// kPropertyReadOnly = 'R', // property is read-only.
5001/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5002/// kPropertyByref = '&', // property is a reference to the value last assigned
5003/// kPropertyDynamic = 'D', // property is dynamic
5004/// kPropertyGetter = 'G', // followed by getter selector name
5005/// kPropertySetter = 'S', // followed by setter selector name
5006/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005007/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005008/// kPropertyWeak = 'W' // 'weak' property
5009/// kPropertyStrong = 'P' // property GC'able
5010/// kPropertyNonAtomic = 'N' // property non-atomic
5011/// };
5012/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005013void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005014 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005015 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005016 // Collect information from the property implementation decl(s).
5017 bool Dynamic = false;
5018 ObjCPropertyImplDecl *SynthesizePID = 0;
5019
5020 // FIXME: Duplicated code due to poor abstraction.
5021 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00005022 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00005023 dyn_cast<ObjCCategoryImplDecl>(Container)) {
5024 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005025 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00005026 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00005027 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005028 if (PID->getPropertyDecl() == PD) {
5029 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
5030 Dynamic = true;
5031 } else {
5032 SynthesizePID = PID;
5033 }
5034 }
5035 }
5036 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00005037 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005038 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005039 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00005040 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00005041 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005042 if (PID->getPropertyDecl() == PD) {
5043 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
5044 Dynamic = true;
5045 } else {
5046 SynthesizePID = PID;
5047 }
5048 }
Mike Stump11289f42009-09-09 15:08:12 +00005049 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00005050 }
5051 }
5052
5053 // FIXME: This is not very efficient.
5054 S = "T";
5055
5056 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005057 // GCC has some special rules regarding encoding of properties which
5058 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00005059 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005060 true /* outermost type */,
5061 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005062
5063 if (PD->isReadOnly()) {
5064 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005065 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5066 S += ",C";
5067 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5068 S += ",&";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005069 } else {
5070 switch (PD->getSetterKind()) {
5071 case ObjCPropertyDecl::Assign: break;
5072 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005073 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005074 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005075 }
5076 }
5077
5078 // It really isn't clear at all what this means, since properties
5079 // are "dynamic by default".
5080 if (Dynamic)
5081 S += ",D";
5082
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005083 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5084 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005085
Daniel Dunbar4932b362008-08-28 04:38:10 +00005086 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5087 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005088 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005089 }
5090
5091 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5092 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005093 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005094 }
5095
5096 if (SynthesizePID) {
5097 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5098 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005099 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005100 }
5101
5102 // FIXME: OBJCGC: weak & strong
5103}
5104
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005105/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005106/// Another legacy compatibility encoding: 32-bit longs are encoded as
5107/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005108/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5109///
5110void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005111 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005112 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005113 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005114 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005115 else
Jay Foad39c79802011-01-12 09:06:06 +00005116 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005117 PointeeTy = IntTy;
5118 }
5119 }
5120}
5121
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005122void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00005123 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005124 // We follow the behavior of gcc, expanding structures which are
5125 // directly pointed to, and expanding embedded structures. Note that
5126 // these rules are sufficient to prevent recursive encoding of the
5127 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005128 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00005129 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005130}
5131
John McCall393a78d2012-12-20 02:45:14 +00005132static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5133 BuiltinType::Kind kind) {
5134 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005135 case BuiltinType::Void: return 'v';
5136 case BuiltinType::Bool: return 'B';
5137 case BuiltinType::Char_U:
5138 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005139 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005140 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005141 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005142 case BuiltinType::UInt: return 'I';
5143 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005144 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005145 case BuiltinType::UInt128: return 'T';
5146 case BuiltinType::ULongLong: return 'Q';
5147 case BuiltinType::Char_S:
5148 case BuiltinType::SChar: return 'c';
5149 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005150 case BuiltinType::WChar_S:
5151 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005152 case BuiltinType::Int: return 'i';
5153 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005154 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005155 case BuiltinType::LongLong: return 'q';
5156 case BuiltinType::Int128: return 't';
5157 case BuiltinType::Float: return 'f';
5158 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005159 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005160 case BuiltinType::NullPtr: return '*'; // like char*
5161
5162 case BuiltinType::Half:
5163 // FIXME: potentially need @encodes for these!
5164 return ' ';
5165
5166 case BuiltinType::ObjCId:
5167 case BuiltinType::ObjCClass:
5168 case BuiltinType::ObjCSel:
5169 llvm_unreachable("@encoding ObjC primitive type");
5170
5171 // OpenCL and placeholder types don't need @encodings.
5172 case BuiltinType::OCLImage1d:
5173 case BuiltinType::OCLImage1dArray:
5174 case BuiltinType::OCLImage1dBuffer:
5175 case BuiltinType::OCLImage2d:
5176 case BuiltinType::OCLImage2dArray:
5177 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005178 case BuiltinType::OCLEvent:
Guy Benyei61054192013-02-07 10:55:47 +00005179 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005180 case BuiltinType::Dependent:
5181#define BUILTIN_TYPE(KIND, ID)
5182#define PLACEHOLDER_TYPE(KIND, ID) \
5183 case BuiltinType::KIND:
5184#include "clang/AST/BuiltinTypes.def"
5185 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005186 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005187 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005188}
5189
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005190static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5191 EnumDecl *Enum = ET->getDecl();
5192
5193 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5194 if (!Enum->isFixed())
5195 return 'i';
5196
5197 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005198 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5199 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005200}
5201
Jay Foad39c79802011-01-12 09:06:06 +00005202static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005203 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005204 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005205 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005206 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5207 // The GNU runtime requires more information; bitfields are encoded as b,
5208 // then the offset (in bits) of the first element, then the type of the
5209 // bitfield, then the size in bits. For example, in this structure:
5210 //
5211 // struct
5212 // {
5213 // int integer;
5214 // int flags:2;
5215 // };
5216 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5217 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5218 // information is not especially sensible, but we're stuck with it for
5219 // compatibility with GCC, although providing it breaks anything that
5220 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005221 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005222 const RecordDecl *RD = FD->getParent();
5223 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005224 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005225 if (const EnumType *ET = T->getAs<EnumType>())
5226 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005227 else {
5228 const BuiltinType *BT = T->castAs<BuiltinType>();
5229 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5230 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005231 }
Richard Smithcaf33902011-10-10 18:28:20 +00005232 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005233}
5234
Daniel Dunbar07d07852009-10-18 21:17:35 +00005235// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005236void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5237 bool ExpandPointedToStructures,
5238 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005239 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005240 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005241 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005242 bool StructField,
5243 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005244 bool EncodeClassNames,
5245 bool EncodePointerToObjCTypedef) const {
John McCall393a78d2012-12-20 02:45:14 +00005246 CanQualType CT = getCanonicalType(T);
5247 switch (CT->getTypeClass()) {
5248 case Type::Builtin:
5249 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005250 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005251 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005252 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5253 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5254 else
5255 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005256 return;
Mike Stump11289f42009-09-09 15:08:12 +00005257
John McCall393a78d2012-12-20 02:45:14 +00005258 case Type::Complex: {
5259 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005260 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00005261 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00005262 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005263 return;
5264 }
John McCall393a78d2012-12-20 02:45:14 +00005265
5266 case Type::Atomic: {
5267 const AtomicType *AT = T->castAs<AtomicType>();
5268 S += 'A';
5269 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5270 false, false);
5271 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005272 }
John McCall393a78d2012-12-20 02:45:14 +00005273
5274 // encoding for pointer or reference types.
5275 case Type::Pointer:
5276 case Type::LValueReference:
5277 case Type::RValueReference: {
5278 QualType PointeeTy;
5279 if (isa<PointerType>(CT)) {
5280 const PointerType *PT = T->castAs<PointerType>();
5281 if (PT->isObjCSelType()) {
5282 S += ':';
5283 return;
5284 }
5285 PointeeTy = PT->getPointeeType();
5286 } else {
5287 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5288 }
5289
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005290 bool isReadOnly = false;
5291 // For historical/compatibility reasons, the read-only qualifier of the
5292 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5293 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005294 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005295 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005296 if (OutermostType && T.isConstQualified()) {
5297 isReadOnly = true;
5298 S += 'r';
5299 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005300 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005301 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005302 while (P->getAs<PointerType>())
5303 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005304 if (P.isConstQualified()) {
5305 isReadOnly = true;
5306 S += 'r';
5307 }
5308 }
5309 if (isReadOnly) {
5310 // Another legacy compatibility encoding. Some ObjC qualifier and type
5311 // combinations need to be rearranged.
5312 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005313 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005314 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005315 }
Mike Stump11289f42009-09-09 15:08:12 +00005316
Anders Carlssond8499822007-10-29 05:01:08 +00005317 if (PointeeTy->isCharType()) {
5318 // char pointer types should be encoded as '*' unless it is a
5319 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005320 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005321 S += '*';
5322 return;
5323 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005324 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005325 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5326 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5327 S += '#';
5328 return;
5329 }
5330 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5331 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5332 S += '@';
5333 return;
5334 }
5335 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005336 }
Anders Carlssond8499822007-10-29 05:01:08 +00005337 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005338 getLegacyIntegralTypeEncoding(PointeeTy);
5339
Mike Stump11289f42009-09-09 15:08:12 +00005340 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005341 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005342 return;
5343 }
John McCall393a78d2012-12-20 02:45:14 +00005344
5345 case Type::ConstantArray:
5346 case Type::IncompleteArray:
5347 case Type::VariableArray: {
5348 const ArrayType *AT = cast<ArrayType>(CT);
5349
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005350 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005351 // Incomplete arrays are encoded as a pointer to the array element.
5352 S += '^';
5353
Mike Stump11289f42009-09-09 15:08:12 +00005354 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005355 false, ExpandStructures, FD);
5356 } else {
5357 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005358
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005359 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5360 S += llvm::utostr(CAT->getSize().getZExtValue());
5361 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005362 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005363 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5364 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005365 S += '0';
5366 }
Mike Stump11289f42009-09-09 15:08:12 +00005367
5368 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005369 false, ExpandStructures, FD);
5370 S += ']';
5371 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005372 return;
5373 }
Mike Stump11289f42009-09-09 15:08:12 +00005374
John McCall393a78d2012-12-20 02:45:14 +00005375 case Type::FunctionNoProto:
5376 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005377 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005378 return;
Mike Stump11289f42009-09-09 15:08:12 +00005379
John McCall393a78d2012-12-20 02:45:14 +00005380 case Type::Record: {
5381 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005382 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005383 // Anonymous structures print as '?'
5384 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5385 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005386 if (ClassTemplateSpecializationDecl *Spec
5387 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5388 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005389 llvm::raw_string_ostream OS(S);
5390 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005391 TemplateArgs.data(),
5392 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005393 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005394 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005395 } else {
5396 S += '?';
5397 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005398 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005399 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005400 if (!RDecl->isUnion()) {
5401 getObjCEncodingForStructureImpl(RDecl, S, FD);
5402 } else {
5403 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5404 FieldEnd = RDecl->field_end();
5405 Field != FieldEnd; ++Field) {
5406 if (FD) {
5407 S += '"';
5408 S += Field->getNameAsString();
5409 S += '"';
5410 }
Mike Stump11289f42009-09-09 15:08:12 +00005411
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005412 // Special case bit-fields.
5413 if (Field->isBitField()) {
5414 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00005415 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005416 } else {
5417 QualType qt = Field->getType();
5418 getLegacyIntegralTypeEncoding(qt);
5419 getObjCEncodingForTypeImpl(qt, S, false, true,
5420 FD, /*OutermostType*/false,
5421 /*EncodingProperty*/false,
5422 /*StructField*/true);
5423 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005424 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005425 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005426 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005427 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005428 return;
5429 }
Mike Stump11289f42009-09-09 15:08:12 +00005430
John McCall393a78d2012-12-20 02:45:14 +00005431 case Type::BlockPointer: {
5432 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005433 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005434 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005435 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005436
5437 S += '<';
5438 // Block return type
5439 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5440 ExpandPointedToStructures, ExpandStructures,
5441 FD,
5442 false /* OutermostType */,
5443 EncodingProperty,
5444 false /* StructField */,
5445 EncodeBlockParameters,
5446 EncodeClassNames);
5447 // Block self
5448 S += "@?";
5449 // Block parameters
5450 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5451 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5452 E = FPT->arg_type_end(); I && (I != E); ++I) {
5453 getObjCEncodingForTypeImpl(*I, S,
5454 ExpandPointedToStructures,
5455 ExpandStructures,
5456 FD,
5457 false /* OutermostType */,
5458 EncodingProperty,
5459 false /* StructField */,
5460 EncodeBlockParameters,
5461 EncodeClassNames);
5462 }
5463 }
5464 S += '>';
5465 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005466 return;
5467 }
Mike Stump11289f42009-09-09 15:08:12 +00005468
John McCall393a78d2012-12-20 02:45:14 +00005469 case Type::ObjCObject:
5470 case Type::ObjCInterface: {
5471 // Ignore protocol qualifiers when mangling at this level.
5472 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005473
John McCall393a78d2012-12-20 02:45:14 +00005474 // The assumption seems to be that this assert will succeed
5475 // because nested levels will have filtered out 'id' and 'Class'.
5476 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005477 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005478 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005479 S += '{';
5480 const IdentifierInfo *II = OI->getIdentifier();
5481 S += II->getName();
5482 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005483 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005484 DeepCollectObjCIvars(OI, true, Ivars);
5485 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005486 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005487 if (Field->isBitField())
5488 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005489 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005490 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5491 false, false, false, false, false,
5492 EncodePointerToObjCTypedef);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005493 }
5494 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005495 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005496 }
Mike Stump11289f42009-09-09 15:08:12 +00005497
John McCall393a78d2012-12-20 02:45:14 +00005498 case Type::ObjCObjectPointer: {
5499 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005500 if (OPT->isObjCIdType()) {
5501 S += '@';
5502 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005503 }
Mike Stump11289f42009-09-09 15:08:12 +00005504
Steve Narofff0c86112009-10-28 22:03:49 +00005505 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5506 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5507 // Since this is a binary compatibility issue, need to consult with runtime
5508 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005509 S += '#';
5510 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005511 }
Mike Stump11289f42009-09-09 15:08:12 +00005512
Chris Lattnere7cabb92009-07-13 00:10:46 +00005513 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005514 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005515 ExpandPointedToStructures,
5516 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005517 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005518 // Note that we do extended encoding of protocol qualifer list
5519 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005520 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00005521 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5522 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005523 S += '<';
5524 S += (*I)->getNameAsString();
5525 S += '>';
5526 }
5527 S += '"';
5528 }
5529 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005530 }
Mike Stump11289f42009-09-09 15:08:12 +00005531
Chris Lattnere7cabb92009-07-13 00:10:46 +00005532 QualType PointeeTy = OPT->getPointeeType();
5533 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005534 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5535 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005536 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005537 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005538 // {...};
5539 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005540 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005541 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005542 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5543 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5544 DeepCollectObjCIvars(OI, true, Ivars);
5545 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5546 if (cast<FieldDecl>(Ivars[i]) == FD) {
5547 S += '{';
5548 S += OI->getIdentifier()->getName();
5549 S += '}';
5550 return;
5551 }
5552 }
5553 }
Mike Stump11289f42009-09-09 15:08:12 +00005554 getObjCEncodingForTypeImpl(PointeeTy, S,
5555 false, ExpandPointedToStructures,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005556 NULL,
5557 false, false, false, false, false,
5558 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005559 return;
5560 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005561
5562 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005563 if (OPT->getInterfaceDecl() &&
5564 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005565 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005566 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00005567 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5568 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005569 S += '<';
5570 S += (*I)->getNameAsString();
5571 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005572 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005573 S += '"';
5574 }
5575 return;
5576 }
Mike Stump11289f42009-09-09 15:08:12 +00005577
John McCalla9e6e8d2010-05-17 23:56:34 +00005578 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005579 // FIXME: we shoul do better than that. 'M' is available.
5580 case Type::MemberPointer:
John McCalla9e6e8d2010-05-17 23:56:34 +00005581 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005582
John McCall393a78d2012-12-20 02:45:14 +00005583 case Type::Vector:
5584 case Type::ExtVector:
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005585 // This matches gcc's encoding, even though technically it is
5586 // insufficient.
5587 // FIXME. We should do a better job than gcc.
5588 return;
John McCall393a78d2012-12-20 02:45:14 +00005589
Richard Smith27d807c2013-04-30 13:56:41 +00005590 case Type::Auto:
5591 // We could see an undeduced auto type here during error recovery.
5592 // Just ignore it.
5593 return;
5594
John McCall393a78d2012-12-20 02:45:14 +00005595#define ABSTRACT_TYPE(KIND, BASE)
5596#define TYPE(KIND, BASE)
5597#define DEPENDENT_TYPE(KIND, BASE) \
5598 case Type::KIND:
5599#define NON_CANONICAL_TYPE(KIND, BASE) \
5600 case Type::KIND:
5601#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5602 case Type::KIND:
5603#include "clang/AST/TypeNodes.def"
5604 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005605 }
John McCall393a78d2012-12-20 02:45:14 +00005606 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005607}
5608
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005609void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5610 std::string &S,
5611 const FieldDecl *FD,
5612 bool includeVBases) const {
5613 assert(RDecl && "Expected non-null RecordDecl");
5614 assert(!RDecl->isUnion() && "Should not be called for unions");
5615 if (!RDecl->getDefinition())
5616 return;
5617
5618 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5619 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5620 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5621
5622 if (CXXRec) {
5623 for (CXXRecordDecl::base_class_iterator
5624 BI = CXXRec->bases_begin(),
5625 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5626 if (!BI->isVirtual()) {
5627 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005628 if (base->isEmpty())
5629 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005630 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005631 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5632 std::make_pair(offs, base));
5633 }
5634 }
5635 }
5636
5637 unsigned i = 0;
5638 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5639 FieldEnd = RDecl->field_end();
5640 Field != FieldEnd; ++Field, ++i) {
5641 uint64_t offs = layout.getFieldOffset(i);
5642 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005643 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005644 }
5645
5646 if (CXXRec && includeVBases) {
5647 for (CXXRecordDecl::base_class_iterator
5648 BI = CXXRec->vbases_begin(),
5649 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5650 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005651 if (base->isEmpty())
5652 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005653 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005654 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5655 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005656 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5657 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005658 }
5659 }
5660
5661 CharUnits size;
5662 if (CXXRec) {
5663 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5664 } else {
5665 size = layout.getSize();
5666 }
5667
5668 uint64_t CurOffs = 0;
5669 std::multimap<uint64_t, NamedDecl *>::iterator
5670 CurLayObj = FieldOrBaseOffsets.begin();
5671
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005672 if (CXXRec && CXXRec->isDynamicClass() &&
5673 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005674 if (FD) {
5675 S += "\"_vptr$";
5676 std::string recname = CXXRec->getNameAsString();
5677 if (recname.empty()) recname = "?";
5678 S += recname;
5679 S += '"';
5680 }
5681 S += "^^?";
5682 CurOffs += getTypeSize(VoidPtrTy);
5683 }
5684
5685 if (!RDecl->hasFlexibleArrayMember()) {
5686 // Mark the end of the structure.
5687 uint64_t offs = toBits(size);
5688 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5689 std::make_pair(offs, (NamedDecl*)0));
5690 }
5691
5692 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5693 assert(CurOffs <= CurLayObj->first);
5694
5695 if (CurOffs < CurLayObj->first) {
5696 uint64_t padding = CurLayObj->first - CurOffs;
5697 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5698 // packing/alignment of members is different that normal, in which case
5699 // the encoding will be out-of-sync with the real layout.
5700 // If the runtime switches to just consider the size of types without
5701 // taking into account alignment, we could make padding explicit in the
5702 // encoding (e.g. using arrays of chars). The encoding strings would be
5703 // longer then though.
5704 CurOffs += padding;
5705 }
5706
5707 NamedDecl *dcl = CurLayObj->second;
5708 if (dcl == 0)
5709 break; // reached end of structure.
5710
5711 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5712 // We expand the bases without their virtual bases since those are going
5713 // in the initial structure. Note that this differs from gcc which
5714 // expands virtual bases each time one is encountered in the hierarchy,
5715 // making the encoding type bigger than it really is.
5716 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005717 assert(!base->isEmpty());
5718 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005719 } else {
5720 FieldDecl *field = cast<FieldDecl>(dcl);
5721 if (FD) {
5722 S += '"';
5723 S += field->getNameAsString();
5724 S += '"';
5725 }
5726
5727 if (field->isBitField()) {
5728 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00005729 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005730 } else {
5731 QualType qt = field->getType();
5732 getLegacyIntegralTypeEncoding(qt);
5733 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5734 /*OutermostType*/false,
5735 /*EncodingProperty*/false,
5736 /*StructField*/true);
5737 CurOffs += getTypeSize(field->getType());
5738 }
5739 }
5740 }
5741}
5742
Mike Stump11289f42009-09-09 15:08:12 +00005743void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005744 std::string& S) const {
5745 if (QT & Decl::OBJC_TQ_In)
5746 S += 'n';
5747 if (QT & Decl::OBJC_TQ_Inout)
5748 S += 'N';
5749 if (QT & Decl::OBJC_TQ_Out)
5750 S += 'o';
5751 if (QT & Decl::OBJC_TQ_Bycopy)
5752 S += 'O';
5753 if (QT & Decl::OBJC_TQ_Byref)
5754 S += 'R';
5755 if (QT & Decl::OBJC_TQ_Oneway)
5756 S += 'V';
5757}
5758
Douglas Gregor3ea72692011-08-12 05:46:01 +00005759TypedefDecl *ASTContext::getObjCIdDecl() const {
5760 if (!ObjCIdDecl) {
5761 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5762 T = getObjCObjectPointerType(T);
5763 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5764 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5765 getTranslationUnitDecl(),
5766 SourceLocation(), SourceLocation(),
5767 &Idents.get("id"), IdInfo);
5768 }
5769
5770 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005771}
5772
Douglas Gregor52e02802011-08-12 06:17:30 +00005773TypedefDecl *ASTContext::getObjCSelDecl() const {
5774 if (!ObjCSelDecl) {
5775 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5776 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5777 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5778 getTranslationUnitDecl(),
5779 SourceLocation(), SourceLocation(),
5780 &Idents.get("SEL"), SelInfo);
5781 }
5782 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005783}
5784
Douglas Gregor0a586182011-08-12 05:59:41 +00005785TypedefDecl *ASTContext::getObjCClassDecl() const {
5786 if (!ObjCClassDecl) {
5787 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5788 T = getObjCObjectPointerType(T);
5789 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5790 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5791 getTranslationUnitDecl(),
5792 SourceLocation(), SourceLocation(),
5793 &Idents.get("Class"), ClassInfo);
5794 }
5795
5796 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005797}
5798
Douglas Gregord53ae832012-01-17 18:09:05 +00005799ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5800 if (!ObjCProtocolClassDecl) {
5801 ObjCProtocolClassDecl
5802 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5803 SourceLocation(),
5804 &Idents.get("Protocol"),
5805 /*PrevDecl=*/0,
5806 SourceLocation(), true);
5807 }
5808
5809 return ObjCProtocolClassDecl;
5810}
5811
Meador Inge5d3fb222012-06-16 03:34:49 +00005812//===----------------------------------------------------------------------===//
5813// __builtin_va_list Construction Functions
5814//===----------------------------------------------------------------------===//
5815
5816static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5817 // typedef char* __builtin_va_list;
5818 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5819 TypeSourceInfo *TInfo
5820 = Context->getTrivialTypeSourceInfo(CharPtrType);
5821
5822 TypedefDecl *VaListTypeDecl
5823 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5824 Context->getTranslationUnitDecl(),
5825 SourceLocation(), SourceLocation(),
5826 &Context->Idents.get("__builtin_va_list"),
5827 TInfo);
5828 return VaListTypeDecl;
5829}
5830
5831static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5832 // typedef void* __builtin_va_list;
5833 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5834 TypeSourceInfo *TInfo
5835 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5836
5837 TypedefDecl *VaListTypeDecl
5838 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5839 Context->getTranslationUnitDecl(),
5840 SourceLocation(), SourceLocation(),
5841 &Context->Idents.get("__builtin_va_list"),
5842 TInfo);
5843 return VaListTypeDecl;
5844}
5845
Tim Northover9bb857a2013-01-31 12:13:10 +00005846static TypedefDecl *
5847CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5848 RecordDecl *VaListTagDecl;
5849 if (Context->getLangOpts().CPlusPlus) {
5850 // namespace std { struct __va_list {
5851 NamespaceDecl *NS;
5852 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5853 Context->getTranslationUnitDecl(),
5854 /*Inline*/false, SourceLocation(),
5855 SourceLocation(), &Context->Idents.get("std"),
5856 /*PrevDecl*/0);
5857
5858 VaListTagDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5859 Context->getTranslationUnitDecl(),
5860 SourceLocation(), SourceLocation(),
5861 &Context->Idents.get("__va_list"));
5862 VaListTagDecl->setDeclContext(NS);
5863 } else {
5864 // struct __va_list
5865 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5866 Context->getTranslationUnitDecl(),
5867 &Context->Idents.get("__va_list"));
5868 }
5869
5870 VaListTagDecl->startDefinition();
5871
5872 const size_t NumFields = 5;
5873 QualType FieldTypes[NumFields];
5874 const char *FieldNames[NumFields];
5875
5876 // void *__stack;
5877 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5878 FieldNames[0] = "__stack";
5879
5880 // void *__gr_top;
5881 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5882 FieldNames[1] = "__gr_top";
5883
5884 // void *__vr_top;
5885 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5886 FieldNames[2] = "__vr_top";
5887
5888 // int __gr_offs;
5889 FieldTypes[3] = Context->IntTy;
5890 FieldNames[3] = "__gr_offs";
5891
5892 // int __vr_offs;
5893 FieldTypes[4] = Context->IntTy;
5894 FieldNames[4] = "__vr_offs";
5895
5896 // Create fields
5897 for (unsigned i = 0; i < NumFields; ++i) {
5898 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5899 VaListTagDecl,
5900 SourceLocation(),
5901 SourceLocation(),
5902 &Context->Idents.get(FieldNames[i]),
5903 FieldTypes[i], /*TInfo=*/0,
5904 /*BitWidth=*/0,
5905 /*Mutable=*/false,
5906 ICIS_NoInit);
5907 Field->setAccess(AS_public);
5908 VaListTagDecl->addDecl(Field);
5909 }
5910 VaListTagDecl->completeDefinition();
5911 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5912 Context->VaListTagTy = VaListTagType;
5913
5914 // } __builtin_va_list;
5915 TypedefDecl *VaListTypedefDecl
5916 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5917 Context->getTranslationUnitDecl(),
5918 SourceLocation(), SourceLocation(),
5919 &Context->Idents.get("__builtin_va_list"),
5920 Context->getTrivialTypeSourceInfo(VaListTagType));
5921
5922 return VaListTypedefDecl;
5923}
5924
Meador Inge5d3fb222012-06-16 03:34:49 +00005925static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5926 // typedef struct __va_list_tag {
5927 RecordDecl *VaListTagDecl;
5928
5929 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5930 Context->getTranslationUnitDecl(),
5931 &Context->Idents.get("__va_list_tag"));
5932 VaListTagDecl->startDefinition();
5933
5934 const size_t NumFields = 5;
5935 QualType FieldTypes[NumFields];
5936 const char *FieldNames[NumFields];
5937
5938 // unsigned char gpr;
5939 FieldTypes[0] = Context->UnsignedCharTy;
5940 FieldNames[0] = "gpr";
5941
5942 // unsigned char fpr;
5943 FieldTypes[1] = Context->UnsignedCharTy;
5944 FieldNames[1] = "fpr";
5945
5946 // unsigned short reserved;
5947 FieldTypes[2] = Context->UnsignedShortTy;
5948 FieldNames[2] = "reserved";
5949
5950 // void* overflow_arg_area;
5951 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5952 FieldNames[3] = "overflow_arg_area";
5953
5954 // void* reg_save_area;
5955 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5956 FieldNames[4] = "reg_save_area";
5957
5958 // Create fields
5959 for (unsigned i = 0; i < NumFields; ++i) {
5960 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5961 SourceLocation(),
5962 SourceLocation(),
5963 &Context->Idents.get(FieldNames[i]),
5964 FieldTypes[i], /*TInfo=*/0,
5965 /*BitWidth=*/0,
5966 /*Mutable=*/false,
5967 ICIS_NoInit);
5968 Field->setAccess(AS_public);
5969 VaListTagDecl->addDecl(Field);
5970 }
5971 VaListTagDecl->completeDefinition();
5972 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005973 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005974
5975 // } __va_list_tag;
5976 TypedefDecl *VaListTagTypedefDecl
5977 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5978 Context->getTranslationUnitDecl(),
5979 SourceLocation(), SourceLocation(),
5980 &Context->Idents.get("__va_list_tag"),
5981 Context->getTrivialTypeSourceInfo(VaListTagType));
5982 QualType VaListTagTypedefType =
5983 Context->getTypedefType(VaListTagTypedefDecl);
5984
5985 // typedef __va_list_tag __builtin_va_list[1];
5986 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5987 QualType VaListTagArrayType
5988 = Context->getConstantArrayType(VaListTagTypedefType,
5989 Size, ArrayType::Normal, 0);
5990 TypeSourceInfo *TInfo
5991 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5992 TypedefDecl *VaListTypedefDecl
5993 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5994 Context->getTranslationUnitDecl(),
5995 SourceLocation(), SourceLocation(),
5996 &Context->Idents.get("__builtin_va_list"),
5997 TInfo);
5998
5999 return VaListTypedefDecl;
6000}
6001
6002static TypedefDecl *
6003CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
6004 // typedef struct __va_list_tag {
6005 RecordDecl *VaListTagDecl;
6006 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
6007 Context->getTranslationUnitDecl(),
6008 &Context->Idents.get("__va_list_tag"));
6009 VaListTagDecl->startDefinition();
6010
6011 const size_t NumFields = 4;
6012 QualType FieldTypes[NumFields];
6013 const char *FieldNames[NumFields];
6014
6015 // unsigned gp_offset;
6016 FieldTypes[0] = Context->UnsignedIntTy;
6017 FieldNames[0] = "gp_offset";
6018
6019 // unsigned fp_offset;
6020 FieldTypes[1] = Context->UnsignedIntTy;
6021 FieldNames[1] = "fp_offset";
6022
6023 // void* overflow_arg_area;
6024 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6025 FieldNames[2] = "overflow_arg_area";
6026
6027 // void* reg_save_area;
6028 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6029 FieldNames[3] = "reg_save_area";
6030
6031 // Create fields
6032 for (unsigned i = 0; i < NumFields; ++i) {
6033 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6034 VaListTagDecl,
6035 SourceLocation(),
6036 SourceLocation(),
6037 &Context->Idents.get(FieldNames[i]),
6038 FieldTypes[i], /*TInfo=*/0,
6039 /*BitWidth=*/0,
6040 /*Mutable=*/false,
6041 ICIS_NoInit);
6042 Field->setAccess(AS_public);
6043 VaListTagDecl->addDecl(Field);
6044 }
6045 VaListTagDecl->completeDefinition();
6046 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00006047 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00006048
6049 // } __va_list_tag;
6050 TypedefDecl *VaListTagTypedefDecl
6051 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6052 Context->getTranslationUnitDecl(),
6053 SourceLocation(), SourceLocation(),
6054 &Context->Idents.get("__va_list_tag"),
6055 Context->getTrivialTypeSourceInfo(VaListTagType));
6056 QualType VaListTagTypedefType =
6057 Context->getTypedefType(VaListTagTypedefDecl);
6058
6059 // typedef __va_list_tag __builtin_va_list[1];
6060 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6061 QualType VaListTagArrayType
6062 = Context->getConstantArrayType(VaListTagTypedefType,
6063 Size, ArrayType::Normal,0);
6064 TypeSourceInfo *TInfo
6065 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
6066 TypedefDecl *VaListTypedefDecl
6067 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6068 Context->getTranslationUnitDecl(),
6069 SourceLocation(), SourceLocation(),
6070 &Context->Idents.get("__builtin_va_list"),
6071 TInfo);
6072
6073 return VaListTypedefDecl;
6074}
6075
6076static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6077 // typedef int __builtin_va_list[4];
6078 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6079 QualType IntArrayType
6080 = Context->getConstantArrayType(Context->IntTy,
6081 Size, ArrayType::Normal, 0);
6082 TypedefDecl *VaListTypedefDecl
6083 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6084 Context->getTranslationUnitDecl(),
6085 SourceLocation(), SourceLocation(),
6086 &Context->Idents.get("__builtin_va_list"),
6087 Context->getTrivialTypeSourceInfo(IntArrayType));
6088
6089 return VaListTypedefDecl;
6090}
6091
Logan Chien57086ce2012-10-10 06:56:20 +00006092static TypedefDecl *
6093CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
6094 RecordDecl *VaListDecl;
6095 if (Context->getLangOpts().CPlusPlus) {
6096 // namespace std { struct __va_list {
6097 NamespaceDecl *NS;
6098 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6099 Context->getTranslationUnitDecl(),
6100 /*Inline*/false, SourceLocation(),
6101 SourceLocation(), &Context->Idents.get("std"),
6102 /*PrevDecl*/0);
6103
6104 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
6105 Context->getTranslationUnitDecl(),
6106 SourceLocation(), SourceLocation(),
6107 &Context->Idents.get("__va_list"));
6108
6109 VaListDecl->setDeclContext(NS);
6110
6111 } else {
6112 // struct __va_list {
6113 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
6114 Context->getTranslationUnitDecl(),
6115 &Context->Idents.get("__va_list"));
6116 }
6117
6118 VaListDecl->startDefinition();
6119
6120 // void * __ap;
6121 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6122 VaListDecl,
6123 SourceLocation(),
6124 SourceLocation(),
6125 &Context->Idents.get("__ap"),
6126 Context->getPointerType(Context->VoidTy),
6127 /*TInfo=*/0,
6128 /*BitWidth=*/0,
6129 /*Mutable=*/false,
6130 ICIS_NoInit);
6131 Field->setAccess(AS_public);
6132 VaListDecl->addDecl(Field);
6133
6134 // };
6135 VaListDecl->completeDefinition();
6136
6137 // typedef struct __va_list __builtin_va_list;
6138 TypeSourceInfo *TInfo
6139 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
6140
6141 TypedefDecl *VaListTypeDecl
6142 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6143 Context->getTranslationUnitDecl(),
6144 SourceLocation(), SourceLocation(),
6145 &Context->Idents.get("__builtin_va_list"),
6146 TInfo);
6147
6148 return VaListTypeDecl;
6149}
6150
Ulrich Weigand47445072013-05-06 16:26:41 +00006151static TypedefDecl *
6152CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6153 // typedef struct __va_list_tag {
6154 RecordDecl *VaListTagDecl;
6155 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
6156 Context->getTranslationUnitDecl(),
6157 &Context->Idents.get("__va_list_tag"));
6158 VaListTagDecl->startDefinition();
6159
6160 const size_t NumFields = 4;
6161 QualType FieldTypes[NumFields];
6162 const char *FieldNames[NumFields];
6163
6164 // long __gpr;
6165 FieldTypes[0] = Context->LongTy;
6166 FieldNames[0] = "__gpr";
6167
6168 // long __fpr;
6169 FieldTypes[1] = Context->LongTy;
6170 FieldNames[1] = "__fpr";
6171
6172 // void *__overflow_arg_area;
6173 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6174 FieldNames[2] = "__overflow_arg_area";
6175
6176 // void *__reg_save_area;
6177 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6178 FieldNames[3] = "__reg_save_area";
6179
6180 // Create fields
6181 for (unsigned i = 0; i < NumFields; ++i) {
6182 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6183 VaListTagDecl,
6184 SourceLocation(),
6185 SourceLocation(),
6186 &Context->Idents.get(FieldNames[i]),
6187 FieldTypes[i], /*TInfo=*/0,
6188 /*BitWidth=*/0,
6189 /*Mutable=*/false,
6190 ICIS_NoInit);
6191 Field->setAccess(AS_public);
6192 VaListTagDecl->addDecl(Field);
6193 }
6194 VaListTagDecl->completeDefinition();
6195 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6196 Context->VaListTagTy = VaListTagType;
6197
6198 // } __va_list_tag;
6199 TypedefDecl *VaListTagTypedefDecl
6200 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6201 Context->getTranslationUnitDecl(),
6202 SourceLocation(), SourceLocation(),
6203 &Context->Idents.get("__va_list_tag"),
6204 Context->getTrivialTypeSourceInfo(VaListTagType));
6205 QualType VaListTagTypedefType =
6206 Context->getTypedefType(VaListTagTypedefDecl);
6207
6208 // typedef __va_list_tag __builtin_va_list[1];
6209 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6210 QualType VaListTagArrayType
6211 = Context->getConstantArrayType(VaListTagTypedefType,
6212 Size, ArrayType::Normal,0);
6213 TypeSourceInfo *TInfo
6214 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
6215 TypedefDecl *VaListTypedefDecl
6216 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6217 Context->getTranslationUnitDecl(),
6218 SourceLocation(), SourceLocation(),
6219 &Context->Idents.get("__builtin_va_list"),
6220 TInfo);
6221
6222 return VaListTypedefDecl;
6223}
6224
Meador Inge5d3fb222012-06-16 03:34:49 +00006225static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6226 TargetInfo::BuiltinVaListKind Kind) {
6227 switch (Kind) {
6228 case TargetInfo::CharPtrBuiltinVaList:
6229 return CreateCharPtrBuiltinVaListDecl(Context);
6230 case TargetInfo::VoidPtrBuiltinVaList:
6231 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006232 case TargetInfo::AArch64ABIBuiltinVaList:
6233 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006234 case TargetInfo::PowerABIBuiltinVaList:
6235 return CreatePowerABIBuiltinVaListDecl(Context);
6236 case TargetInfo::X86_64ABIBuiltinVaList:
6237 return CreateX86_64ABIBuiltinVaListDecl(Context);
6238 case TargetInfo::PNaClABIBuiltinVaList:
6239 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006240 case TargetInfo::AAPCSABIBuiltinVaList:
6241 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006242 case TargetInfo::SystemZBuiltinVaList:
6243 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006244 }
6245
6246 llvm_unreachable("Unhandled __builtin_va_list type kind");
6247}
6248
6249TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6250 if (!BuiltinVaListDecl)
6251 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6252
6253 return BuiltinVaListDecl;
6254}
6255
Meador Ingecfb60902012-07-01 15:57:25 +00006256QualType ASTContext::getVaListTagType() const {
6257 // Force the creation of VaListTagTy by building the __builtin_va_list
6258 // declaration.
6259 if (VaListTagTy.isNull())
6260 (void) getBuiltinVaListDecl();
6261
6262 return VaListTagTy;
6263}
6264
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006265void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006266 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006267 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006268
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006269 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006270}
6271
John McCalld28ae272009-12-02 08:04:21 +00006272/// \brief Retrieve the template name that corresponds to a non-empty
6273/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006274TemplateName
6275ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6276 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006277 unsigned size = End - Begin;
6278 assert(size > 1 && "set is not overloaded!");
6279
6280 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6281 size * sizeof(FunctionTemplateDecl*));
6282 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6283
6284 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006285 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006286 NamedDecl *D = *I;
6287 assert(isa<FunctionTemplateDecl>(D) ||
6288 (isa<UsingShadowDecl>(D) &&
6289 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6290 *Storage++ = D;
6291 }
6292
6293 return TemplateName(OT);
6294}
6295
Douglas Gregordc572a32009-03-30 22:58:21 +00006296/// \brief Retrieve the template name that represents a qualified
6297/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006298TemplateName
6299ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6300 bool TemplateKeyword,
6301 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006302 assert(NNS && "Missing nested-name-specifier in qualified template name");
6303
Douglas Gregorc42075a2010-02-04 18:10:26 +00006304 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006305 llvm::FoldingSetNodeID ID;
6306 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6307
6308 void *InsertPos = 0;
6309 QualifiedTemplateName *QTN =
6310 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6311 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006312 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6313 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006314 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6315 }
6316
6317 return TemplateName(QTN);
6318}
6319
6320/// \brief Retrieve the template name that represents a dependent
6321/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006322TemplateName
6323ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6324 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006325 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006326 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006327
6328 llvm::FoldingSetNodeID ID;
6329 DependentTemplateName::Profile(ID, NNS, Name);
6330
6331 void *InsertPos = 0;
6332 DependentTemplateName *QTN =
6333 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6334
6335 if (QTN)
6336 return TemplateName(QTN);
6337
6338 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6339 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006340 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6341 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006342 } else {
6343 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006344 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6345 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006346 DependentTemplateName *CheckQTN =
6347 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6348 assert(!CheckQTN && "Dependent type name canonicalization broken");
6349 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006350 }
6351
6352 DependentTemplateNames.InsertNode(QTN, InsertPos);
6353 return TemplateName(QTN);
6354}
6355
Douglas Gregor71395fa2009-11-04 00:56:37 +00006356/// \brief Retrieve the template name that represents a dependent
6357/// template name such as \c MetaFun::template operator+.
6358TemplateName
6359ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006360 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006361 assert((!NNS || NNS->isDependent()) &&
6362 "Nested name specifier must be dependent");
6363
6364 llvm::FoldingSetNodeID ID;
6365 DependentTemplateName::Profile(ID, NNS, Operator);
6366
6367 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006368 DependentTemplateName *QTN
6369 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006370
6371 if (QTN)
6372 return TemplateName(QTN);
6373
6374 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6375 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006376 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6377 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006378 } else {
6379 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006380 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6381 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006382
6383 DependentTemplateName *CheckQTN
6384 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6385 assert(!CheckQTN && "Dependent template name canonicalization broken");
6386 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006387 }
6388
6389 DependentTemplateNames.InsertNode(QTN, InsertPos);
6390 return TemplateName(QTN);
6391}
6392
Douglas Gregor5590be02011-01-15 06:45:20 +00006393TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006394ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6395 TemplateName replacement) const {
6396 llvm::FoldingSetNodeID ID;
6397 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6398
6399 void *insertPos = 0;
6400 SubstTemplateTemplateParmStorage *subst
6401 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6402
6403 if (!subst) {
6404 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6405 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6406 }
6407
6408 return TemplateName(subst);
6409}
6410
6411TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006412ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6413 const TemplateArgument &ArgPack) const {
6414 ASTContext &Self = const_cast<ASTContext &>(*this);
6415 llvm::FoldingSetNodeID ID;
6416 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6417
6418 void *InsertPos = 0;
6419 SubstTemplateTemplateParmPackStorage *Subst
6420 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6421
6422 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006423 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006424 ArgPack.pack_size(),
6425 ArgPack.pack_begin());
6426 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6427 }
6428
6429 return TemplateName(Subst);
6430}
6431
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006432/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006433/// TargetInfo, produce the corresponding type. The unsigned @p Type
6434/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006435CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006436 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006437 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006438 case TargetInfo::SignedChar: return SignedCharTy;
6439 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006440 case TargetInfo::SignedShort: return ShortTy;
6441 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6442 case TargetInfo::SignedInt: return IntTy;
6443 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6444 case TargetInfo::SignedLong: return LongTy;
6445 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6446 case TargetInfo::SignedLongLong: return LongLongTy;
6447 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6448 }
6449
David Blaikie83d382b2011-09-23 05:06:16 +00006450 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006451}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006452
6453//===----------------------------------------------------------------------===//
6454// Type Predicates.
6455//===----------------------------------------------------------------------===//
6456
Fariborz Jahanian96207692009-02-18 21:49:28 +00006457/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6458/// garbage collection attribute.
6459///
John McCall553d45a2011-01-12 00:34:59 +00006460Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006461 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006462 return Qualifiers::GCNone;
6463
David Blaikiebbafb8a2012-03-11 07:00:24 +00006464 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006465 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6466
6467 // Default behaviour under objective-C's gc is for ObjC pointers
6468 // (or pointers to them) be treated as though they were declared
6469 // as __strong.
6470 if (GCAttrs == Qualifiers::GCNone) {
6471 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6472 return Qualifiers::Strong;
6473 else if (Ty->isPointerType())
6474 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6475 } else {
6476 // It's not valid to set GC attributes on anything that isn't a
6477 // pointer.
6478#ifndef NDEBUG
6479 QualType CT = Ty->getCanonicalTypeInternal();
6480 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6481 CT = AT->getElementType();
6482 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6483#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006484 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006485 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006486}
6487
Chris Lattner49af6a42008-04-07 06:51:04 +00006488//===----------------------------------------------------------------------===//
6489// Type Compatibility Testing
6490//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006491
Mike Stump11289f42009-09-09 15:08:12 +00006492/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006493/// compatible.
6494static bool areCompatVectorTypes(const VectorType *LHS,
6495 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006496 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006497 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006498 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006499}
6500
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006501bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6502 QualType SecondVec) {
6503 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6504 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6505
6506 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6507 return true;
6508
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006509 // Treat Neon vector types and most AltiVec vector types as if they are the
6510 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006511 const VectorType *First = FirstVec->getAs<VectorType>();
6512 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006513 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006514 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006515 First->getVectorKind() != VectorType::AltiVecPixel &&
6516 First->getVectorKind() != VectorType::AltiVecBool &&
6517 Second->getVectorKind() != VectorType::AltiVecPixel &&
6518 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006519 return true;
6520
6521 return false;
6522}
6523
Steve Naroff8e6aee52009-07-23 01:01:38 +00006524//===----------------------------------------------------------------------===//
6525// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6526//===----------------------------------------------------------------------===//
6527
6528/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6529/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006530bool
6531ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6532 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006533 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006534 return true;
6535 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6536 E = rProto->protocol_end(); PI != E; ++PI)
6537 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6538 return true;
6539 return false;
6540}
6541
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006542/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6543/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006544bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6545 QualType rhs) {
6546 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6547 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6548 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6549
6550 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6551 E = lhsQID->qual_end(); I != E; ++I) {
6552 bool match = false;
6553 ObjCProtocolDecl *lhsProto = *I;
6554 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6555 E = rhsOPT->qual_end(); J != E; ++J) {
6556 ObjCProtocolDecl *rhsProto = *J;
6557 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6558 match = true;
6559 break;
6560 }
6561 }
6562 if (!match)
6563 return false;
6564 }
6565 return true;
6566}
6567
Steve Naroff8e6aee52009-07-23 01:01:38 +00006568/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6569/// ObjCQualifiedIDType.
6570bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6571 bool compare) {
6572 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006573 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006574 lhs->isObjCIdType() || lhs->isObjCClassType())
6575 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006576 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006577 rhs->isObjCIdType() || rhs->isObjCClassType())
6578 return true;
6579
6580 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006581 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006582
Steve Naroff8e6aee52009-07-23 01:01:38 +00006583 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006584
Steve Naroff8e6aee52009-07-23 01:01:38 +00006585 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006586 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006587 // make sure we check the class hierarchy.
6588 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6589 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6590 E = lhsQID->qual_end(); I != E; ++I) {
6591 // when comparing an id<P> on lhs with a static type on rhs,
6592 // see if static class implements all of id's protocols, directly or
6593 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006594 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006595 return false;
6596 }
6597 }
6598 // If there are no qualifiers and no interface, we have an 'id'.
6599 return true;
6600 }
Mike Stump11289f42009-09-09 15:08:12 +00006601 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006602 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6603 E = lhsQID->qual_end(); I != E; ++I) {
6604 ObjCProtocolDecl *lhsProto = *I;
6605 bool match = false;
6606
6607 // when comparing an id<P> on lhs with a static type on rhs,
6608 // see if static class implements all of id's protocols, directly or
6609 // through its super class and categories.
6610 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6611 E = rhsOPT->qual_end(); J != E; ++J) {
6612 ObjCProtocolDecl *rhsProto = *J;
6613 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6614 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6615 match = true;
6616 break;
6617 }
6618 }
Mike Stump11289f42009-09-09 15:08:12 +00006619 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006620 // make sure we check the class hierarchy.
6621 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6622 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6623 E = lhsQID->qual_end(); I != E; ++I) {
6624 // when comparing an id<P> on lhs with a static type on rhs,
6625 // see if static class implements all of id's protocols, directly or
6626 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006627 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006628 match = true;
6629 break;
6630 }
6631 }
6632 }
6633 if (!match)
6634 return false;
6635 }
Mike Stump11289f42009-09-09 15:08:12 +00006636
Steve Naroff8e6aee52009-07-23 01:01:38 +00006637 return true;
6638 }
Mike Stump11289f42009-09-09 15:08:12 +00006639
Steve Naroff8e6aee52009-07-23 01:01:38 +00006640 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6641 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6642
Mike Stump11289f42009-09-09 15:08:12 +00006643 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006644 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006645 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006646 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6647 E = lhsOPT->qual_end(); I != E; ++I) {
6648 ObjCProtocolDecl *lhsProto = *I;
6649 bool match = false;
6650
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006651 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006652 // see if static class implements all of id's protocols, directly or
6653 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006654 // First, lhs protocols in the qualifier list must be found, direct
6655 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006656 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6657 E = rhsQID->qual_end(); J != E; ++J) {
6658 ObjCProtocolDecl *rhsProto = *J;
6659 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6660 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6661 match = true;
6662 break;
6663 }
6664 }
6665 if (!match)
6666 return false;
6667 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006668
6669 // Static class's protocols, or its super class or category protocols
6670 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6671 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6672 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6673 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6674 // This is rather dubious but matches gcc's behavior. If lhs has
6675 // no type qualifier and its class has no static protocol(s)
6676 // assume that it is mismatch.
6677 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6678 return false;
6679 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6680 LHSInheritedProtocols.begin(),
6681 E = LHSInheritedProtocols.end(); I != E; ++I) {
6682 bool match = false;
6683 ObjCProtocolDecl *lhsProto = (*I);
6684 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6685 E = rhsQID->qual_end(); J != E; ++J) {
6686 ObjCProtocolDecl *rhsProto = *J;
6687 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6688 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6689 match = true;
6690 break;
6691 }
6692 }
6693 if (!match)
6694 return false;
6695 }
6696 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006697 return true;
6698 }
6699 return false;
6700}
6701
Eli Friedman47f77112008-08-22 00:56:42 +00006702/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006703/// compatible for assignment from RHS to LHS. This handles validation of any
6704/// protocol qualifiers on the LHS or RHS.
6705///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006706bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6707 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006708 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6709 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6710
Steve Naroff1329fa02009-07-15 18:40:39 +00006711 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006712 if (LHS->isObjCUnqualifiedIdOrClass() ||
6713 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006714 return true;
6715
John McCall8b07ec22010-05-15 11:32:37 +00006716 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006717 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6718 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006719 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006720
6721 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6722 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6723 QualType(RHSOPT,0));
6724
John McCall8b07ec22010-05-15 11:32:37 +00006725 // If we have 2 user-defined types, fall into that path.
6726 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006727 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006728
Steve Naroff8e6aee52009-07-23 01:01:38 +00006729 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006730}
6731
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006732/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006733/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006734/// arguments in block literals. When passed as arguments, passing 'A*' where
6735/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6736/// not OK. For the return type, the opposite is not OK.
6737bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6738 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006739 const ObjCObjectPointerType *RHSOPT,
6740 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006741 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006742 return true;
6743
6744 if (LHSOPT->isObjCBuiltinType()) {
6745 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6746 }
6747
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006748 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006749 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6750 QualType(RHSOPT,0),
6751 false);
6752
6753 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6754 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6755 if (LHS && RHS) { // We have 2 user-defined types.
6756 if (LHS != RHS) {
6757 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006758 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006759 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006760 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006761 }
6762 else
6763 return true;
6764 }
6765 return false;
6766}
6767
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006768/// getIntersectionOfProtocols - This routine finds the intersection of set
6769/// of protocols inherited from two distinct objective-c pointer objects.
6770/// It is used to build composite qualifier list of the composite type of
6771/// the conditional expression involving two objective-c pointer objects.
6772static
6773void getIntersectionOfProtocols(ASTContext &Context,
6774 const ObjCObjectPointerType *LHSOPT,
6775 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006776 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006777
John McCall8b07ec22010-05-15 11:32:37 +00006778 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6779 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6780 assert(LHS->getInterface() && "LHS must have an interface base");
6781 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006782
6783 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6784 unsigned LHSNumProtocols = LHS->getNumProtocols();
6785 if (LHSNumProtocols > 0)
6786 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6787 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006788 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006789 Context.CollectInheritedProtocols(LHS->getInterface(),
6790 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006791 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6792 LHSInheritedProtocols.end());
6793 }
6794
6795 unsigned RHSNumProtocols = RHS->getNumProtocols();
6796 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006797 ObjCProtocolDecl **RHSProtocols =
6798 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006799 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6800 if (InheritedProtocolSet.count(RHSProtocols[i]))
6801 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006802 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006803 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006804 Context.CollectInheritedProtocols(RHS->getInterface(),
6805 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006806 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6807 RHSInheritedProtocols.begin(),
6808 E = RHSInheritedProtocols.end(); I != E; ++I)
6809 if (InheritedProtocolSet.count((*I)))
6810 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006811 }
6812}
6813
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006814/// areCommonBaseCompatible - Returns common base class of the two classes if
6815/// one found. Note that this is O'2 algorithm. But it will be called as the
6816/// last type comparison in a ?-exp of ObjC pointer types before a
6817/// warning is issued. So, its invokation is extremely rare.
6818QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006819 const ObjCObjectPointerType *Lptr,
6820 const ObjCObjectPointerType *Rptr) {
6821 const ObjCObjectType *LHS = Lptr->getObjectType();
6822 const ObjCObjectType *RHS = Rptr->getObjectType();
6823 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6824 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006825 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006826 return QualType();
6827
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006828 do {
John McCall8b07ec22010-05-15 11:32:37 +00006829 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006830 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006831 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006832 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6833
6834 QualType Result = QualType(LHS, 0);
6835 if (!Protocols.empty())
6836 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6837 Result = getObjCObjectPointerType(Result);
6838 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006839 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006840 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006841
6842 return QualType();
6843}
6844
John McCall8b07ec22010-05-15 11:32:37 +00006845bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6846 const ObjCObjectType *RHS) {
6847 assert(LHS->getInterface() && "LHS is not an interface type");
6848 assert(RHS->getInterface() && "RHS is not an interface type");
6849
Chris Lattner49af6a42008-04-07 06:51:04 +00006850 // Verify that the base decls are compatible: the RHS must be a subclass of
6851 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006852 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006853 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006854
Chris Lattner49af6a42008-04-07 06:51:04 +00006855 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6856 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006857 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006858 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006859
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006860 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6861 // more detailed analysis is required.
6862 if (RHS->getNumProtocols() == 0) {
6863 // OK, if LHS is a superclass of RHS *and*
6864 // this superclass is assignment compatible with LHS.
6865 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006866 bool IsSuperClass =
6867 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6868 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006869 // OK if conversion of LHS to SuperClass results in narrowing of types
6870 // ; i.e., SuperClass may implement at least one of the protocols
6871 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6872 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6873 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006874 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006875 // If super class has no protocols, it is not a match.
6876 if (SuperClassInheritedProtocols.empty())
6877 return false;
6878
6879 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6880 LHSPE = LHS->qual_end();
6881 LHSPI != LHSPE; LHSPI++) {
6882 bool SuperImplementsProtocol = false;
6883 ObjCProtocolDecl *LHSProto = (*LHSPI);
6884
6885 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6886 SuperClassInheritedProtocols.begin(),
6887 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6888 ObjCProtocolDecl *SuperClassProto = (*I);
6889 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6890 SuperImplementsProtocol = true;
6891 break;
6892 }
6893 }
6894 if (!SuperImplementsProtocol)
6895 return false;
6896 }
6897 return true;
6898 }
6899 return false;
6900 }
Mike Stump11289f42009-09-09 15:08:12 +00006901
John McCall8b07ec22010-05-15 11:32:37 +00006902 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6903 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006904 LHSPI != LHSPE; LHSPI++) {
6905 bool RHSImplementsProtocol = false;
6906
6907 // If the RHS doesn't implement the protocol on the left, the types
6908 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006909 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6910 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006911 RHSPI != RHSPE; RHSPI++) {
6912 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006913 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006914 break;
6915 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006916 }
6917 // FIXME: For better diagnostics, consider passing back the protocol name.
6918 if (!RHSImplementsProtocol)
6919 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006920 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006921 // The RHS implements all protocols listed on the LHS.
6922 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006923}
6924
Steve Naroffb7605152009-02-12 17:52:19 +00006925bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6926 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006927 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6928 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006929
Steve Naroff7cae42b2009-07-10 23:34:53 +00006930 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006931 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006932
6933 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6934 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006935}
6936
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006937bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6938 return canAssignObjCInterfaces(
6939 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6940 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6941}
6942
Mike Stump11289f42009-09-09 15:08:12 +00006943/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006944/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006945/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006946/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006947bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6948 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006949 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006950 return hasSameType(LHS, RHS);
6951
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006952 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006953}
6954
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006955bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006956 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006957}
6958
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006959bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6960 return !mergeTypes(LHS, RHS, true).isNull();
6961}
6962
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006963/// mergeTransparentUnionType - if T is a transparent union type and a member
6964/// of T is compatible with SubType, return the merged type, else return
6965/// QualType()
6966QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6967 bool OfBlockPointer,
6968 bool Unqualified) {
6969 if (const RecordType *UT = T->getAsUnionType()) {
6970 RecordDecl *UD = UT->getDecl();
6971 if (UD->hasAttr<TransparentUnionAttr>()) {
6972 for (RecordDecl::field_iterator it = UD->field_begin(),
6973 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006974 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006975 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6976 if (!MT.isNull())
6977 return MT;
6978 }
6979 }
6980 }
6981
6982 return QualType();
6983}
6984
6985/// mergeFunctionArgumentTypes - merge two types which appear as function
6986/// argument types
6987QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6988 bool OfBlockPointer,
6989 bool Unqualified) {
6990 // GNU extension: two types are compatible if they appear as a function
6991 // argument, one of the types is a transparent union type and the other
6992 // type is compatible with a union member
6993 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6994 Unqualified);
6995 if (!lmerge.isNull())
6996 return lmerge;
6997
6998 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6999 Unqualified);
7000 if (!rmerge.isNull())
7001 return rmerge;
7002
7003 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7004}
7005
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007006QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007007 bool OfBlockPointer,
7008 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00007009 const FunctionType *lbase = lhs->getAs<FunctionType>();
7010 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007011 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7012 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00007013 bool allLTypes = true;
7014 bool allRTypes = true;
7015
7016 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007017 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00007018 if (OfBlockPointer) {
7019 QualType RHS = rbase->getResultType();
7020 QualType LHS = lbase->getResultType();
7021 bool UnqualifiedResult = Unqualified;
7022 if (!UnqualifiedResult)
7023 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007024 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00007025 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007026 else
John McCall8c6b56f2010-12-15 01:06:38 +00007027 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
7028 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007029 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007030
7031 if (Unqualified)
7032 retType = retType.getUnqualifiedType();
7033
7034 CanQualType LRetType = getCanonicalType(lbase->getResultType());
7035 CanQualType RRetType = getCanonicalType(rbase->getResultType());
7036 if (Unqualified) {
7037 LRetType = LRetType.getUnqualifiedType();
7038 RRetType = RRetType.getUnqualifiedType();
7039 }
7040
7041 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007042 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007043 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007044 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00007045
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00007046 // FIXME: double check this
7047 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7048 // rbase->getRegParmAttr() != 0 &&
7049 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00007050 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7051 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00007052
Douglas Gregor8c940862010-01-18 17:14:39 +00007053 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00007054 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00007055 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00007056
John McCall8c6b56f2010-12-15 01:06:38 +00007057 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00007058 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7059 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00007060 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7061 return QualType();
7062
John McCall31168b02011-06-15 23:02:42 +00007063 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7064 return QualType();
7065
John McCall8c6b56f2010-12-15 01:06:38 +00007066 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7067 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007068
Rafael Espindola8778c282012-11-29 16:09:03 +00007069 if (lbaseInfo.getNoReturn() != NoReturn)
7070 allLTypes = false;
7071 if (rbaseInfo.getNoReturn() != NoReturn)
7072 allRTypes = false;
7073
John McCall31168b02011-06-15 23:02:42 +00007074 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007075
Eli Friedman47f77112008-08-22 00:56:42 +00007076 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007077 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7078 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007079 unsigned lproto_nargs = lproto->getNumArgs();
7080 unsigned rproto_nargs = rproto->getNumArgs();
7081
7082 // Compatible functions must have the same number of arguments
7083 if (lproto_nargs != rproto_nargs)
7084 return QualType();
7085
7086 // Variadic and non-variadic functions aren't compatible
7087 if (lproto->isVariadic() != rproto->isVariadic())
7088 return QualType();
7089
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007090 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7091 return QualType();
7092
Fariborz Jahanian97676972011-09-28 21:52:05 +00007093 if (LangOpts.ObjCAutoRefCount &&
7094 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
7095 return QualType();
7096
Eli Friedman47f77112008-08-22 00:56:42 +00007097 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007098 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00007099 for (unsigned i = 0; i < lproto_nargs; i++) {
7100 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
7101 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007102 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
7103 OfBlockPointer,
7104 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007105 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007106
7107 if (Unqualified)
7108 argtype = argtype.getUnqualifiedType();
7109
Eli Friedman47f77112008-08-22 00:56:42 +00007110 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007111 if (Unqualified) {
7112 largtype = largtype.getUnqualifiedType();
7113 rargtype = rargtype.getUnqualifiedType();
7114 }
7115
Chris Lattner465fa322008-10-05 17:34:18 +00007116 if (getCanonicalType(argtype) != getCanonicalType(largtype))
7117 allLTypes = false;
7118 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
7119 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007120 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007121
Eli Friedman47f77112008-08-22 00:56:42 +00007122 if (allLTypes) return lhs;
7123 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007124
7125 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7126 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007127 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007128 }
7129
7130 if (lproto) allRTypes = false;
7131 if (rproto) allLTypes = false;
7132
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007133 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007134 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007135 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007136 if (proto->isVariadic()) return QualType();
7137 // Check that the types are compatible with the types that
7138 // would result from default argument promotions (C99 6.7.5.3p15).
7139 // The only types actually affected are promotable integer
7140 // types and floats, which would be passed as a different
7141 // type depending on whether the prototype is visible.
7142 unsigned proto_nargs = proto->getNumArgs();
7143 for (unsigned i = 0; i < proto_nargs; ++i) {
7144 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00007145
Eli Friedman448ce402012-08-30 00:44:15 +00007146 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007147 // to pass enum values.
Eli Friedman448ce402012-08-30 00:44:15 +00007148 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
7149 argTy = Enum->getDecl()->getIntegerType();
7150 if (argTy.isNull())
7151 return QualType();
7152 }
Douglas Gregor2973d402010-02-03 19:27:29 +00007153
Eli Friedman47f77112008-08-22 00:56:42 +00007154 if (argTy->isPromotableIntegerType() ||
7155 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
7156 return QualType();
7157 }
7158
7159 if (allLTypes) return lhs;
7160 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007161
7162 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7163 EPI.ExtInfo = einfo;
Reid Kleckner896b32f2013-06-10 20:51:09 +00007164 return getFunctionType(retType, proto->getArgTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007165 }
7166
7167 if (allLTypes) return lhs;
7168 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007169 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007170}
7171
John McCall433c2e62013-03-21 00:10:07 +00007172/// Given that we have an enum type and a non-enum type, try to merge them.
7173static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7174 QualType other, bool isBlockReturnType) {
7175 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7176 // a signed integer type, or an unsigned integer type.
7177 // Compatibility is based on the underlying type, not the promotion
7178 // type.
7179 QualType underlyingType = ET->getDecl()->getIntegerType();
7180 if (underlyingType.isNull()) return QualType();
7181 if (Context.hasSameType(underlyingType, other))
7182 return other;
7183
7184 // In block return types, we're more permissive and accept any
7185 // integral type of the same size.
7186 if (isBlockReturnType && other->isIntegerType() &&
7187 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7188 return other;
7189
7190 return QualType();
7191}
7192
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007193QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007194 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007195 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007196 // C++ [expr]: If an expression initially has the type "reference to T", the
7197 // type is adjusted to "T" prior to any further analysis, the expression
7198 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007199 // expression is an lvalue unless the reference is an rvalue reference and
7200 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007201 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7202 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007203
7204 if (Unqualified) {
7205 LHS = LHS.getUnqualifiedType();
7206 RHS = RHS.getUnqualifiedType();
7207 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007208
Eli Friedman47f77112008-08-22 00:56:42 +00007209 QualType LHSCan = getCanonicalType(LHS),
7210 RHSCan = getCanonicalType(RHS);
7211
7212 // If two types are identical, they are compatible.
7213 if (LHSCan == RHSCan)
7214 return LHS;
7215
John McCall8ccfcb52009-09-24 19:53:00 +00007216 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007217 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7218 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007219 if (LQuals != RQuals) {
7220 // If any of these qualifiers are different, we have a type
7221 // mismatch.
7222 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007223 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7224 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007225 return QualType();
7226
7227 // Exactly one GC qualifier difference is allowed: __strong is
7228 // okay if the other type has no GC qualifier but is an Objective
7229 // C object pointer (i.e. implicitly strong by default). We fix
7230 // this by pretending that the unqualified type was actually
7231 // qualified __strong.
7232 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7233 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7234 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7235
7236 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7237 return QualType();
7238
7239 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7240 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7241 }
7242 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7243 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7244 }
Eli Friedman47f77112008-08-22 00:56:42 +00007245 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007246 }
7247
7248 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007249
Eli Friedmandcca6332009-06-01 01:22:52 +00007250 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7251 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007252
Chris Lattnerfd652912008-01-14 05:45:46 +00007253 // We want to consider the two function types to be the same for these
7254 // comparisons, just force one to the other.
7255 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7256 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007257
7258 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007259 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7260 LHSClass = Type::ConstantArray;
7261 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7262 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007263
John McCall8b07ec22010-05-15 11:32:37 +00007264 // ObjCInterfaces are just specialized ObjCObjects.
7265 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7266 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7267
Nate Begemance4d7fc2008-04-18 23:10:10 +00007268 // Canonicalize ExtVector -> Vector.
7269 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7270 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007271
Chris Lattner95554662008-04-07 05:43:21 +00007272 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007273 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007274 // Note that we only have special rules for turning block enum
7275 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007276 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007277 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007278 }
John McCall9dd450b2009-09-21 23:43:11 +00007279 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007280 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007281 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007282 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007283 if (OfBlockPointer && !BlockReturnType) {
7284 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7285 return LHS;
7286 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7287 return RHS;
7288 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007289
Eli Friedman47f77112008-08-22 00:56:42 +00007290 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007291 }
Eli Friedman47f77112008-08-22 00:56:42 +00007292
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007293 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007294 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007295#define TYPE(Class, Base)
7296#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007297#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007298#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7299#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7300#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007301 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007302
Richard Smith27d807c2013-04-30 13:56:41 +00007303 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007304 case Type::LValueReference:
7305 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007306 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007307 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007308
John McCall8b07ec22010-05-15 11:32:37 +00007309 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007310 case Type::IncompleteArray:
7311 case Type::VariableArray:
7312 case Type::FunctionProto:
7313 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007314 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007315
Chris Lattnerfd652912008-01-14 05:45:46 +00007316 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007317 {
7318 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007319 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7320 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007321 if (Unqualified) {
7322 LHSPointee = LHSPointee.getUnqualifiedType();
7323 RHSPointee = RHSPointee.getUnqualifiedType();
7324 }
7325 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7326 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007327 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007328 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007329 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007330 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007331 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007332 return getPointerType(ResultType);
7333 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007334 case Type::BlockPointer:
7335 {
7336 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007337 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7338 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007339 if (Unqualified) {
7340 LHSPointee = LHSPointee.getUnqualifiedType();
7341 RHSPointee = RHSPointee.getUnqualifiedType();
7342 }
7343 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7344 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007345 if (ResultType.isNull()) return QualType();
7346 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7347 return LHS;
7348 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7349 return RHS;
7350 return getBlockPointerType(ResultType);
7351 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007352 case Type::Atomic:
7353 {
7354 // Merge two pointer types, while trying to preserve typedef info
7355 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7356 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7357 if (Unqualified) {
7358 LHSValue = LHSValue.getUnqualifiedType();
7359 RHSValue = RHSValue.getUnqualifiedType();
7360 }
7361 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7362 Unqualified);
7363 if (ResultType.isNull()) return QualType();
7364 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7365 return LHS;
7366 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7367 return RHS;
7368 return getAtomicType(ResultType);
7369 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007370 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007371 {
7372 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7373 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7374 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7375 return QualType();
7376
7377 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7378 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007379 if (Unqualified) {
7380 LHSElem = LHSElem.getUnqualifiedType();
7381 RHSElem = RHSElem.getUnqualifiedType();
7382 }
7383
7384 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007385 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007386 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7387 return LHS;
7388 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7389 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007390 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7391 ArrayType::ArraySizeModifier(), 0);
7392 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7393 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007394 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7395 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007396 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7397 return LHS;
7398 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7399 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007400 if (LVAT) {
7401 // FIXME: This isn't correct! But tricky to implement because
7402 // the array's size has to be the size of LHS, but the type
7403 // has to be different.
7404 return LHS;
7405 }
7406 if (RVAT) {
7407 // FIXME: This isn't correct! But tricky to implement because
7408 // the array's size has to be the size of RHS, but the type
7409 // has to be different.
7410 return RHS;
7411 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007412 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7413 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007414 return getIncompleteArrayType(ResultType,
7415 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007416 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007417 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007418 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007419 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007420 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007421 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007422 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007423 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007424 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007425 case Type::Complex:
7426 // Distinct complex types are incompatible.
7427 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007428 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007429 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007430 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7431 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007432 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007433 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007434 case Type::ObjCObject: {
7435 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007436 // FIXME: This should be type compatibility, e.g. whether
7437 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007438 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7439 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7440 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007441 return LHS;
7442
Eli Friedman47f77112008-08-22 00:56:42 +00007443 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007444 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007445 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007446 if (OfBlockPointer) {
7447 if (canAssignObjCInterfacesInBlockPointer(
7448 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007449 RHS->getAs<ObjCObjectPointerType>(),
7450 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007451 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007452 return QualType();
7453 }
John McCall9dd450b2009-09-21 23:43:11 +00007454 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7455 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007456 return LHS;
7457
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007458 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007459 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007460 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007461
David Blaikie8a40f702012-01-17 06:56:22 +00007462 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007463}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007464
Fariborz Jahanian97676972011-09-28 21:52:05 +00007465bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7466 const FunctionProtoType *FromFunctionType,
7467 const FunctionProtoType *ToFunctionType) {
7468 if (FromFunctionType->hasAnyConsumedArgs() !=
7469 ToFunctionType->hasAnyConsumedArgs())
7470 return false;
7471 FunctionProtoType::ExtProtoInfo FromEPI =
7472 FromFunctionType->getExtProtoInfo();
7473 FunctionProtoType::ExtProtoInfo ToEPI =
7474 ToFunctionType->getExtProtoInfo();
7475 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
7476 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
7477 ArgIdx != NumArgs; ++ArgIdx) {
7478 if (FromEPI.ConsumedArguments[ArgIdx] !=
7479 ToEPI.ConsumedArguments[ArgIdx])
7480 return false;
7481 }
7482 return true;
7483}
7484
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007485/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7486/// 'RHS' attributes and returns the merged version; including for function
7487/// return types.
7488QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7489 QualType LHSCan = getCanonicalType(LHS),
7490 RHSCan = getCanonicalType(RHS);
7491 // If two types are identical, they are compatible.
7492 if (LHSCan == RHSCan)
7493 return LHS;
7494 if (RHSCan->isFunctionType()) {
7495 if (!LHSCan->isFunctionType())
7496 return QualType();
7497 QualType OldReturnType =
7498 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7499 QualType NewReturnType =
7500 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7501 QualType ResReturnType =
7502 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7503 if (ResReturnType.isNull())
7504 return QualType();
7505 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7506 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7507 // In either case, use OldReturnType to build the new function type.
7508 const FunctionType *F = LHS->getAs<FunctionType>();
7509 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007510 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7511 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007512 QualType ResultType =
7513 getFunctionType(OldReturnType, FPT->getArgTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007514 return ResultType;
7515 }
7516 }
7517 return QualType();
7518 }
7519
7520 // If the qualifiers are different, the types can still be merged.
7521 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7522 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7523 if (LQuals != RQuals) {
7524 // If any of these qualifiers are different, we have a type mismatch.
7525 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7526 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7527 return QualType();
7528
7529 // Exactly one GC qualifier difference is allowed: __strong is
7530 // okay if the other type has no GC qualifier but is an Objective
7531 // C object pointer (i.e. implicitly strong by default). We fix
7532 // this by pretending that the unqualified type was actually
7533 // qualified __strong.
7534 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7535 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7536 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7537
7538 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7539 return QualType();
7540
7541 if (GC_L == Qualifiers::Strong)
7542 return LHS;
7543 if (GC_R == Qualifiers::Strong)
7544 return RHS;
7545 return QualType();
7546 }
7547
7548 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7549 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7550 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7551 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7552 if (ResQT == LHSBaseQT)
7553 return LHS;
7554 if (ResQT == RHSBaseQT)
7555 return RHS;
7556 }
7557 return QualType();
7558}
7559
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007560//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007561// Integer Predicates
7562//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007563
Jay Foad39c79802011-01-12 09:06:06 +00007564unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007565 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007566 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007567 if (T->isBooleanType())
7568 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007569 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007570 return (unsigned)getTypeSize(T);
7571}
7572
Abramo Bagnara13640492012-09-09 10:21:24 +00007573QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007574 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007575
7576 // Turn <4 x signed int> -> <4 x unsigned int>
7577 if (const VectorType *VTy = T->getAs<VectorType>())
7578 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007579 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007580
7581 // For enums, we return the unsigned version of the base type.
7582 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007583 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007584
7585 const BuiltinType *BTy = T->getAs<BuiltinType>();
7586 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007587 switch (BTy->getKind()) {
7588 case BuiltinType::Char_S:
7589 case BuiltinType::SChar:
7590 return UnsignedCharTy;
7591 case BuiltinType::Short:
7592 return UnsignedShortTy;
7593 case BuiltinType::Int:
7594 return UnsignedIntTy;
7595 case BuiltinType::Long:
7596 return UnsignedLongTy;
7597 case BuiltinType::LongLong:
7598 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007599 case BuiltinType::Int128:
7600 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007601 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007602 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007603 }
7604}
7605
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007606ASTMutationListener::~ASTMutationListener() { }
7607
Richard Smith1fa5d642013-05-11 05:45:24 +00007608void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7609 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007610
7611//===----------------------------------------------------------------------===//
7612// Builtin Type Computation
7613//===----------------------------------------------------------------------===//
7614
7615/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007616/// pointer over the consumed characters. This returns the resultant type. If
7617/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7618/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7619/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007620///
7621/// RequiresICE is filled in on return to indicate whether the value is required
7622/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007623static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007624 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007625 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007626 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007627 // Modifiers.
7628 int HowLong = 0;
7629 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007630 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007631
Chris Lattnerdc226c22010-10-01 22:42:38 +00007632 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007633 bool Done = false;
7634 while (!Done) {
7635 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007636 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007637 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007638 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007639 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007640 case 'S':
7641 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7642 assert(!Signed && "Can't use 'S' modifier multiple times!");
7643 Signed = true;
7644 break;
7645 case 'U':
7646 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7647 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7648 Unsigned = true;
7649 break;
7650 case 'L':
7651 assert(HowLong <= 2 && "Can't have LLLL modifier");
7652 ++HowLong;
7653 break;
7654 }
7655 }
7656
7657 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007658
Chris Lattnerecd79c62009-06-14 00:45:47 +00007659 // Read the base type.
7660 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007661 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007662 case 'v':
7663 assert(HowLong == 0 && !Signed && !Unsigned &&
7664 "Bad modifiers used with 'v'!");
7665 Type = Context.VoidTy;
7666 break;
Jack Carter24bef982013-08-15 15:16:57 +00007667 case 'h':
7668 assert(HowLong == 0 && !Signed && !Unsigned &&
7669 "Bad modifiers used with 'f'!");
7670 Type = Context.HalfTy;
7671 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007672 case 'f':
7673 assert(HowLong == 0 && !Signed && !Unsigned &&
7674 "Bad modifiers used with 'f'!");
7675 Type = Context.FloatTy;
7676 break;
7677 case 'd':
7678 assert(HowLong < 2 && !Signed && !Unsigned &&
7679 "Bad modifiers used with 'd'!");
7680 if (HowLong)
7681 Type = Context.LongDoubleTy;
7682 else
7683 Type = Context.DoubleTy;
7684 break;
7685 case 's':
7686 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7687 if (Unsigned)
7688 Type = Context.UnsignedShortTy;
7689 else
7690 Type = Context.ShortTy;
7691 break;
7692 case 'i':
7693 if (HowLong == 3)
7694 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7695 else if (HowLong == 2)
7696 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7697 else if (HowLong == 1)
7698 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7699 else
7700 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7701 break;
7702 case 'c':
7703 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7704 if (Signed)
7705 Type = Context.SignedCharTy;
7706 else if (Unsigned)
7707 Type = Context.UnsignedCharTy;
7708 else
7709 Type = Context.CharTy;
7710 break;
7711 case 'b': // boolean
7712 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7713 Type = Context.BoolTy;
7714 break;
7715 case 'z': // size_t.
7716 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7717 Type = Context.getSizeType();
7718 break;
7719 case 'F':
7720 Type = Context.getCFConstantStringType();
7721 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007722 case 'G':
7723 Type = Context.getObjCIdType();
7724 break;
7725 case 'H':
7726 Type = Context.getObjCSelType();
7727 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007728 case 'M':
7729 Type = Context.getObjCSuperType();
7730 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007731 case 'a':
7732 Type = Context.getBuiltinVaListType();
7733 assert(!Type.isNull() && "builtin va list type not initialized!");
7734 break;
7735 case 'A':
7736 // This is a "reference" to a va_list; however, what exactly
7737 // this means depends on how va_list is defined. There are two
7738 // different kinds of va_list: ones passed by value, and ones
7739 // passed by reference. An example of a by-value va_list is
7740 // x86, where va_list is a char*. An example of by-ref va_list
7741 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7742 // we want this argument to be a char*&; for x86-64, we want
7743 // it to be a __va_list_tag*.
7744 Type = Context.getBuiltinVaListType();
7745 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007746 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007747 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007748 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007749 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007750 break;
7751 case 'V': {
7752 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007753 unsigned NumElements = strtoul(Str, &End, 10);
7754 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007755 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007756
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007757 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7758 RequiresICE, false);
7759 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007760
7761 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007762 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007763 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007764 break;
7765 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007766 case 'E': {
7767 char *End;
7768
7769 unsigned NumElements = strtoul(Str, &End, 10);
7770 assert(End != Str && "Missing vector size");
7771
7772 Str = End;
7773
7774 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7775 false);
7776 Type = Context.getExtVectorType(ElementType, NumElements);
7777 break;
7778 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007779 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007780 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7781 false);
7782 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007783 Type = Context.getComplexType(ElementType);
7784 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007785 }
7786 case 'Y' : {
7787 Type = Context.getPointerDiffType();
7788 break;
7789 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007790 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007791 Type = Context.getFILEType();
7792 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007793 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007794 return QualType();
7795 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007796 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007797 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007798 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007799 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007800 else
7801 Type = Context.getjmp_bufType();
7802
Mike Stump2adb4da2009-07-28 23:47:15 +00007803 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007804 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007805 return QualType();
7806 }
7807 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007808 case 'K':
7809 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7810 Type = Context.getucontext_tType();
7811
7812 if (Type.isNull()) {
7813 Error = ASTContext::GE_Missing_ucontext;
7814 return QualType();
7815 }
7816 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007817 case 'p':
7818 Type = Context.getProcessIDType();
7819 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007820 }
Mike Stump11289f42009-09-09 15:08:12 +00007821
Chris Lattnerdc226c22010-10-01 22:42:38 +00007822 // If there are modifiers and if we're allowed to parse them, go for it.
7823 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007824 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007825 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007826 default: Done = true; --Str; break;
7827 case '*':
7828 case '&': {
7829 // Both pointers and references can have their pointee types
7830 // qualified with an address space.
7831 char *End;
7832 unsigned AddrSpace = strtoul(Str, &End, 10);
7833 if (End != Str && AddrSpace != 0) {
7834 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7835 Str = End;
7836 }
7837 if (c == '*')
7838 Type = Context.getPointerType(Type);
7839 else
7840 Type = Context.getLValueReferenceType(Type);
7841 break;
7842 }
7843 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7844 case 'C':
7845 Type = Type.withConst();
7846 break;
7847 case 'D':
7848 Type = Context.getVolatileType(Type);
7849 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007850 case 'R':
7851 Type = Type.withRestrict();
7852 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007853 }
7854 }
Chris Lattner84733392010-10-01 07:13:18 +00007855
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007856 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007857 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007858
Chris Lattnerecd79c62009-06-14 00:45:47 +00007859 return Type;
7860}
7861
7862/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007863QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007864 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007865 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007866 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007867
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007868 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007869
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007870 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007871 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007872 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7873 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007874 if (Error != GE_None)
7875 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007876
7877 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7878
Chris Lattnerecd79c62009-06-14 00:45:47 +00007879 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007880 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007881 if (Error != GE_None)
7882 return QualType();
7883
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007884 // If this argument is required to be an IntegerConstantExpression and the
7885 // caller cares, fill in the bitmask we return.
7886 if (RequiresICE && IntegerConstantArgs)
7887 *IntegerConstantArgs |= 1 << ArgTypes.size();
7888
Chris Lattnerecd79c62009-06-14 00:45:47 +00007889 // Do array -> pointer decay. The builtin should use the decayed type.
7890 if (Ty->isArrayType())
7891 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007892
Chris Lattnerecd79c62009-06-14 00:45:47 +00007893 ArgTypes.push_back(Ty);
7894 }
7895
7896 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7897 "'.' should only occur at end of builtin type list!");
7898
Reid Kleckner78af0702013-08-27 23:08:25 +00007899 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00007900 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7901
7902 bool Variadic = (TypeStr[0] == '.');
7903
7904 // We really shouldn't be making a no-proto type here, especially in C++.
7905 if (ArgTypes.empty() && Variadic)
7906 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007907
John McCalldb40c7f2010-12-14 08:05:40 +00007908 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007909 EPI.ExtInfo = EI;
7910 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007911
Jordan Rose5c382722013-03-08 21:51:21 +00007912 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007913}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007914
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007915GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007916 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007917 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007918
Rafael Espindola3ae00052013-05-13 00:12:11 +00007919 GVALinkage External = GVA_StrongExternal;
7920 switch (FD->getTemplateSpecializationKind()) {
7921 case TSK_Undeclared:
7922 case TSK_ExplicitSpecialization:
7923 External = GVA_StrongExternal;
7924 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007925
Rafael Espindola3ae00052013-05-13 00:12:11 +00007926 case TSK_ExplicitInstantiationDefinition:
7927 return GVA_ExplicitTemplateInstantiation;
7928
7929 case TSK_ExplicitInstantiationDeclaration:
7930 case TSK_ImplicitInstantiation:
7931 External = GVA_TemplateInstantiation;
7932 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007933 }
7934
7935 if (!FD->isInlined())
7936 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00007937
7938 if ((!getLangOpts().CPlusPlus && !getLangOpts().MicrosoftMode) ||
7939 FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007940 // GNU or C99 inline semantics. Determine whether this symbol should be
7941 // externally visible.
7942 if (FD->isInlineDefinitionExternallyVisible())
7943 return External;
7944
7945 // C99 inline semantics, where the symbol is not externally visible.
7946 return GVA_C99Inline;
7947 }
7948
7949 // C++0x [temp.explicit]p9:
7950 // [ Note: The intent is that an inline function that is the subject of
7951 // an explicit instantiation declaration will still be implicitly
7952 // instantiated when used so that the body can be considered for
7953 // inlining, but that no out-of-line copy of the inline function would be
7954 // generated in the translation unit. -- end note ]
7955 if (FD->getTemplateSpecializationKind()
7956 == TSK_ExplicitInstantiationDeclaration)
7957 return GVA_C99Inline;
7958
7959 return GVA_CXXInline;
7960}
7961
7962GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007963 if (!VD->isExternallyVisible())
7964 return GVA_Internal;
7965
Richard Smith8809a0c2013-09-27 20:14:12 +00007966 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007967 case TSK_Undeclared:
7968 case TSK_ExplicitSpecialization:
7969 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007970
Rafael Espindola3ae00052013-05-13 00:12:11 +00007971 case TSK_ExplicitInstantiationDeclaration:
7972 llvm_unreachable("Variable should not be instantiated");
7973 // Fall through to treat this like any other instantiation.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007974
Rafael Espindola3ae00052013-05-13 00:12:11 +00007975 case TSK_ExplicitInstantiationDefinition:
7976 return GVA_ExplicitTemplateInstantiation;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007977
Rafael Espindola3ae00052013-05-13 00:12:11 +00007978 case TSK_ImplicitInstantiation:
7979 return GVA_TemplateInstantiation;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007980 }
Rafael Espindola27699c82013-05-13 14:05:53 +00007981
7982 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007983}
7984
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007985bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007986 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7987 if (!VD->isFileVarDecl())
7988 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00007989 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7990 // We never need to emit an uninstantiated function template.
7991 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7992 return false;
7993 } else
7994 return false;
7995
7996 // If this is a member of a class template, we do not need to emit it.
7997 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007998 return false;
7999
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008000 // Weak references don't produce any output by themselves.
8001 if (D->hasAttr<WeakRefAttr>())
8002 return false;
8003
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008004 // Aliases and used decls are required.
8005 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8006 return true;
8007
8008 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8009 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00008010 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00008011 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008012
8013 // Constructors and destructors are required.
8014 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8015 return true;
8016
John McCall6bd2a892013-01-25 22:31:03 +00008017 // The key function for a class is required. This rule only comes
8018 // into play when inline functions can be key functions, though.
8019 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8020 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8021 const CXXRecordDecl *RD = MD->getParent();
8022 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8023 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8024 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8025 return true;
8026 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008027 }
8028 }
8029
8030 GVALinkage Linkage = GetGVALinkageForFunction(FD);
8031
8032 // static, static inline, always_inline, and extern inline functions can
8033 // always be deferred. Normal inline functions can be deferred in C99/C++.
8034 // Implicit template instantiations can also be deferred in C++.
8035 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00008036 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008037 return false;
8038 return true;
8039 }
Douglas Gregor87d81242011-09-10 00:22:34 +00008040
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008041 const VarDecl *VD = cast<VarDecl>(D);
8042 assert(VD->isFileVarDecl() && "Expected file scoped var");
8043
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008044 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
8045 return false;
8046
Richard Smitha0e5e542012-11-12 21:38:00 +00008047 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008048 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smitha0e5e542012-11-12 21:38:00 +00008049 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
8050 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008051
Richard Smitha0e5e542012-11-12 21:38:00 +00008052 // Variables that have destruction with side-effects are required.
8053 if (VD->getType().isDestructedType())
8054 return true;
8055
8056 // Variables that have initialization with side-effects are required.
8057 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
8058 return true;
8059
8060 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008061}
Charles Davis53c59df2010-08-16 03:33:14 +00008062
Reid Kleckner78af0702013-08-27 23:08:25 +00008063CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8064 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00008065 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00008066 if (IsCXXMethod)
8067 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00008068
Reid Kleckner78af0702013-08-27 23:08:25 +00008069 return (LangOpts.MRTD && !IsVariadic) ? CC_X86StdCall : CC_C;
Charles Davis99202b32010-11-09 18:04:24 +00008070}
8071
Jay Foad39c79802011-01-12 09:06:06 +00008072bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00008073 // Pass through to the C++ ABI object
8074 return ABI->isNearlyEmpty(RD);
8075}
8076
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008077MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00008078 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00008079 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00008080 case TargetCXXABI::GenericItanium:
8081 case TargetCXXABI::GenericARM:
8082 case TargetCXXABI::iOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008083 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00008084 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008085 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008086 }
David Blaikie83d382b2011-09-23 05:06:16 +00008087 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008088}
8089
Charles Davis53c59df2010-08-16 03:33:14 +00008090CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008091
8092size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00008093 return ASTRecordLayouts.getMemorySize() +
8094 llvm::capacity_in_bytes(ObjCLayouts) +
8095 llvm::capacity_in_bytes(KeyFunctions) +
8096 llvm::capacity_in_bytes(ObjCImpls) +
8097 llvm::capacity_in_bytes(BlockVarCopyInits) +
8098 llvm::capacity_in_bytes(DeclAttrs) +
8099 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8100 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8101 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8102 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8103 llvm::capacity_in_bytes(OverriddenMethods) +
8104 llvm::capacity_in_bytes(Types) +
8105 llvm::capacity_in_bytes(VariableArrayTypes) +
8106 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008107}
Ted Kremenek540017e2011-10-06 05:00:56 +00008108
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008109/// getIntTypeForBitwidth -
8110/// sets integer QualTy according to specified details:
8111/// bitwidth, signed/unsigned.
8112/// Returns empty type if there is no appropriate target types.
8113QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8114 unsigned Signed) const {
8115 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8116 CanQualType QualTy = getFromTargetType(Ty);
8117 if (!QualTy && DestWidth == 128)
8118 return Signed ? Int128Ty : UnsignedInt128Ty;
8119 return QualTy;
8120}
8121
8122/// getRealTypeForBitwidth -
8123/// sets floating point QualTy according to specified bitwidth.
8124/// Returns empty type if there is no appropriate target types.
8125QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8126 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8127 switch (Ty) {
8128 case TargetInfo::Float:
8129 return FloatTy;
8130 case TargetInfo::Double:
8131 return DoubleTy;
8132 case TargetInfo::LongDouble:
8133 return LongDoubleTy;
8134 case TargetInfo::NoFloat:
8135 return QualType();
8136 }
8137
8138 llvm_unreachable("Unhandled TargetInfo::RealType value");
8139}
8140
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008141void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8142 if (Number > 1)
8143 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008144}
8145
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008146unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8147 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8148 MangleNumbers.find(ND);
8149 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008150}
8151
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008152MangleNumberingContext &
8153ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008154 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8155 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8156 if (!MCtx)
8157 MCtx = createMangleNumberingContext();
8158 return *MCtx;
8159}
8160
8161MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8162 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008163}
8164
Ted Kremenek540017e2011-10-06 05:00:56 +00008165void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8166 ParamIndices[D] = index;
8167}
8168
8169unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8170 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8171 assert(I != ParamIndices.end() &&
8172 "ParmIndices lacks entry set by ParmVarDecl");
8173 return I->second;
8174}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008175
Richard Smithe6c01442013-06-05 00:46:14 +00008176APValue *
8177ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8178 bool MayCreate) {
8179 assert(E && E->getStorageDuration() == SD_Static &&
8180 "don't need to cache the computed value for this temporary");
8181 if (MayCreate)
8182 return &MaterializedTemporaryValues[E];
8183
8184 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8185 MaterializedTemporaryValues.find(E);
8186 return I == MaterializedTemporaryValues.end() ? 0 : &I->second;
8187}
8188
Fariborz Jahanian615de762013-05-28 17:37:39 +00008189bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8190 const llvm::Triple &T = getTargetInfo().getTriple();
8191 if (!T.isOSDarwin())
8192 return false;
8193
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008194 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8195 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8196 return false;
8197
Fariborz Jahanian615de762013-05-28 17:37:39 +00008198 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8199 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8200 uint64_t Size = sizeChars.getQuantity();
8201 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8202 unsigned Align = alignChars.getQuantity();
8203 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8204 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8205}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008206
8207namespace {
8208
8209 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8210 /// parents as defined by the \c RecursiveASTVisitor.
8211 ///
8212 /// Note that the relationship described here is purely in terms of AST
8213 /// traversal - there are other relationships (for example declaration context)
8214 /// in the AST that are better modeled by special matchers.
8215 ///
8216 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8217 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8218
8219 public:
8220 /// \brief Builds and returns the translation unit's parent map.
8221 ///
8222 /// The caller takes ownership of the returned \c ParentMap.
8223 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8224 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8225 Visitor.TraverseDecl(&TU);
8226 return Visitor.Parents;
8227 }
8228
8229 private:
8230 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8231
8232 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8233 }
8234
8235 bool shouldVisitTemplateInstantiations() const {
8236 return true;
8237 }
8238 bool shouldVisitImplicitCode() const {
8239 return true;
8240 }
8241 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8242 // are not triggered during data recursion.
8243 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8244 return false;
8245 }
8246
8247 template <typename T>
8248 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
8249 if (Node == NULL)
8250 return true;
8251 if (ParentStack.size() > 0)
8252 // FIXME: Currently we add the same parent multiple times, for example
8253 // when we visit all subexpressions of template instantiations; this is
8254 // suboptimal, bug benign: the only way to visit those is with
8255 // hasAncestor / hasParent, and those do not create new matches.
8256 // The plan is to enable DynTypedNode to be storable in a map or hash
8257 // map. The main problem there is to implement hash functions /
8258 // comparison operators for all types that DynTypedNode supports that
8259 // do not have pointer identity.
8260 (*Parents)[Node].push_back(ParentStack.back());
8261 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8262 bool Result = (this ->* traverse) (Node);
8263 ParentStack.pop_back();
8264 return Result;
8265 }
8266
8267 bool TraverseDecl(Decl *DeclNode) {
8268 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8269 }
8270
8271 bool TraverseStmt(Stmt *StmtNode) {
8272 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8273 }
8274
8275 ASTContext::ParentMap *Parents;
8276 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8277
8278 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8279 };
8280
8281} // end namespace
8282
8283ASTContext::ParentVector
8284ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8285 assert(Node.getMemoizationData() &&
8286 "Invariant broken: only nodes that support memoization may be "
8287 "used in the parent map.");
8288 if (!AllParents) {
8289 // We always need to run over the whole translation unit, as
8290 // hasAncestor can escape any subtree.
8291 AllParents.reset(
8292 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8293 }
8294 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8295 if (I == AllParents->end()) {
8296 return ParentVector();
8297 }
8298 return I->second;
8299}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008300
8301bool
8302ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8303 const ObjCMethodDecl *MethodImpl) {
8304 // No point trying to match an unavailable/deprecated mothod.
8305 if (MethodDecl->hasAttr<UnavailableAttr>()
8306 || MethodDecl->hasAttr<DeprecatedAttr>())
8307 return false;
8308 if (MethodDecl->getObjCDeclQualifier() !=
8309 MethodImpl->getObjCDeclQualifier())
8310 return false;
8311 if (!hasSameType(MethodDecl->getResultType(),
8312 MethodImpl->getResultType()))
8313 return false;
8314
8315 if (MethodDecl->param_size() != MethodImpl->param_size())
8316 return false;
8317
8318 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8319 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8320 EF = MethodDecl->param_end();
8321 IM != EM && IF != EF; ++IM, ++IF) {
8322 const ParmVarDecl *DeclVar = (*IF);
8323 const ParmVarDecl *ImplVar = (*IM);
8324 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8325 return false;
8326 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8327 return false;
8328 }
8329 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8330
8331}