blob: 6af79cd5383e9a8cb967de61aa22f100c0376640 [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"
Reid Kleckner96f8f932014-02-05 17:27:08 +000032#include "clang/AST/VTableBuilder.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000033#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000034#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000035#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000036#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000037#include "llvm/ADT/StringExtras.h"
Robert Lyttoneaf6f362013-11-12 10:09:34 +000038#include "llvm/ADT/Triple.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000039#include "llvm/Support/Capacity.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000040#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000041#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000042#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000043
Chris Lattnerddc135e2006-11-10 06:34:16 +000044using namespace clang;
45
Douglas Gregor9672f922010-07-03 00:47:00 +000046unsigned ASTContext::NumImplicitDefaultConstructors;
47unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000048unsigned ASTContext::NumImplicitCopyConstructors;
49unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000050unsigned ASTContext::NumImplicitMoveConstructors;
51unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000052unsigned ASTContext::NumImplicitCopyAssignmentOperators;
53unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000054unsigned ASTContext::NumImplicitMoveAssignmentOperators;
55unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000056unsigned ASTContext::NumImplicitDestructors;
57unsigned ASTContext::NumImplicitDestructorsDeclared;
58
Steve Naroff0af91202007-04-27 21:51:21 +000059enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000060 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000061};
62
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000063RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000064 if (!CommentsLoaded && ExternalSource) {
65 ExternalSource->ReadComments();
66 CommentsLoaded = true;
67 }
68
69 assert(D);
70
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000071 // User can not attach documentation to implicit declarations.
72 if (D->isImplicit())
73 return NULL;
74
Dmitri Gribenkob2610882012-08-14 17:17:18 +000075 // User can not attach documentation to implicit instantiations.
76 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
77 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
78 return NULL;
79 }
80
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000081 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
82 if (VD->isStaticDataMember() &&
83 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
84 return NULL;
85 }
86
87 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
88 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
89 return NULL;
90 }
91
Dmitri Gribenko01b06512013-01-27 21:18:39 +000092 if (const ClassTemplateSpecializationDecl *CTSD =
93 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
94 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
95 if (TSK == TSK_ImplicitInstantiation ||
96 TSK == TSK_Undeclared)
97 return NULL;
98 }
99
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000100 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
101 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
102 return NULL;
103 }
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000104 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
105 // When tag declaration (but not definition!) is part of the
106 // decl-specifier-seq of some other declaration, it doesn't get comment
107 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
108 return NULL;
109 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000110 // TODO: handle comments for function parameters properly.
111 if (isa<ParmVarDecl>(D))
112 return NULL;
113
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000114 // TODO: we could look up template parameter documentation in the template
115 // documentation.
116 if (isa<TemplateTypeParmDecl>(D) ||
117 isa<NonTypeTemplateParmDecl>(D) ||
118 isa<TemplateTemplateParmDecl>(D))
119 return NULL;
120
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000121 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000122
123 // If there are no comments anywhere, we won't find anything.
124 if (RawComments.empty())
125 return NULL;
126
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000127 // Find declaration location.
128 // For Objective-C declarations we generally don't expect to have multiple
129 // declarators, thus use declaration starting location as the "declaration
130 // location".
131 // For all other declarations multiple declarators are used quite frequently,
132 // so we use the location of the identifier as the "declaration location".
133 SourceLocation DeclLoc;
134 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000135 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000136 isa<RedeclarableTemplateDecl>(D) ||
137 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000138 DeclLoc = D->getLocStart();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000139 else {
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000140 DeclLoc = D->getLocation();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000141 // If location of the typedef name is in a macro, it is because being
142 // declared via a macro. Try using declaration's starting location
143 // as the "declaration location".
144 if (DeclLoc.isMacroID() && isa<TypedefDecl>(D))
145 DeclLoc = D->getLocStart();
146 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000147
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000148 // If the declaration doesn't map directly to a location in a file, we
149 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000150 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
151 return NULL;
152
153 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000154 ArrayRef<RawComment *>::iterator Comment;
155 {
156 // When searching for comments during parsing, the comment we are looking
157 // for is usually among the last two comments we parsed -- check them
158 // first.
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000159 RawComment CommentAtDeclLoc(
160 SourceMgr, SourceRange(DeclLoc), false,
161 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000162 BeforeThanCompare<RawComment> Compare(SourceMgr);
163 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
164 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
165 if (!Found && RawComments.size() >= 2) {
166 MaybeBeforeDecl--;
167 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
168 }
169
170 if (Found) {
171 Comment = MaybeBeforeDecl + 1;
172 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
173 &CommentAtDeclLoc, Compare));
174 } else {
175 // Slow path.
176 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
177 &CommentAtDeclLoc, Compare);
178 }
179 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000180
181 // Decompose the location for the declaration and find the beginning of the
182 // file buffer.
183 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
184
185 // First check whether we have a trailing comment.
186 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000187 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Fariborz Jahanianfad28542013-08-06 23:29:00 +0000188 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian3ab62222013-08-07 16:40:29 +0000189 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000190 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000191 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000192 // Check that Doxygen trailing comment comes after the declaration, starts
193 // on the same line and in the same file as the declaration.
194 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
195 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
196 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
197 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000198 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000199 }
200 }
201
202 // The comment just after the declaration was not a trailing comment.
203 // Let's look at the previous comment.
204 if (Comment == RawComments.begin())
205 return NULL;
206 --Comment;
207
208 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000209 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000210 return NULL;
211
212 // Decompose the end of the comment.
213 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000214 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000215
216 // If the comment and the declaration aren't in the same file, then they
217 // aren't related.
218 if (DeclLocDecomp.first != CommentEndDecomp.first)
219 return NULL;
220
221 // Get the corresponding buffer.
222 bool Invalid = false;
223 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
224 &Invalid).data();
225 if (Invalid)
226 return NULL;
227
228 // Extract text between the comment and declaration.
229 StringRef Text(Buffer + CommentEndDecomp.second,
230 DeclLocDecomp.second - CommentEndDecomp.second);
231
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000232 // There should be no other declarations or preprocessor directives between
233 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000234 if (Text.find_first_of(";{}#@") != StringRef::npos)
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000235 return NULL;
236
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000237 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000238}
239
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000240namespace {
241/// If we have a 'templated' declaration for a template, adjust 'D' to
242/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000243/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000244const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000245 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000246 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000247 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000248 return FTD;
249
250 // Nothing to do if function is not an implicit instantiation.
251 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
252 return D;
253
254 // Function is an implicit instantiation of a function template?
255 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
256 return FTD;
257
258 // Function is instantiated from a member definition of a class template?
259 if (const FunctionDecl *MemberDecl =
260 FD->getInstantiatedFromMemberFunction())
261 return MemberDecl;
262
263 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000264 }
Dmitri Gribenko90631802012-08-22 17:44:32 +0000265 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
266 // Static data member is instantiated from a member definition of a class
267 // template?
268 if (VD->isStaticDataMember())
269 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
270 return MemberDecl;
271
272 return D;
273 }
274 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
275 // Is this class declaration part of a class template?
276 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
277 return CTD;
278
279 // Class is an implicit instantiation of a class template or partial
280 // specialization?
281 if (const ClassTemplateSpecializationDecl *CTSD =
282 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
283 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
284 return D;
285 llvm::PointerUnion<ClassTemplateDecl *,
286 ClassTemplatePartialSpecializationDecl *>
287 PU = CTSD->getSpecializedTemplateOrPartial();
288 return PU.is<ClassTemplateDecl*>() ?
289 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
290 static_cast<const Decl*>(
291 PU.get<ClassTemplatePartialSpecializationDecl *>());
292 }
293
294 // Class is instantiated from a member definition of a class template?
295 if (const MemberSpecializationInfo *Info =
296 CRD->getMemberSpecializationInfo())
297 return Info->getInstantiatedFrom();
298
299 return D;
300 }
301 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
302 // Enum is instantiated from a member definition of a class template?
303 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
304 return MemberDecl;
305
306 return D;
307 }
308 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000309 return D;
310}
311} // unnamed namespace
312
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000313const RawComment *ASTContext::getRawCommentForAnyRedecl(
314 const Decl *D,
315 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000316 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000317
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000318 // Check whether we have cached a comment for this declaration already.
319 {
320 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
321 RedeclComments.find(D);
322 if (Pos != RedeclComments.end()) {
323 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000324 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
325 if (OriginalDecl)
326 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000327 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000328 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000329 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000330 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000331
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000332 // Search for comments attached to declarations in the redeclaration chain.
333 const RawComment *RC = NULL;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000334 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000335 for (Decl::redecl_iterator I = D->redecls_begin(),
336 E = D->redecls_end();
337 I != E; ++I) {
338 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
339 RedeclComments.find(*I);
340 if (Pos != RedeclComments.end()) {
341 const RawCommentAndCacheFlags &Raw = Pos->second;
342 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
343 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000344 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000345 break;
346 }
347 } else {
348 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000349 OriginalDeclForRC = *I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000350 RawCommentAndCacheFlags Raw;
351 if (RC) {
352 Raw.setRaw(RC);
353 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
354 } else
355 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000356 Raw.setOriginalDecl(*I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000357 RedeclComments[*I] = Raw;
358 if (RC)
359 break;
360 }
361 }
362
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000363 // If we found a comment, it should be a documentation comment.
364 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000365
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000366 if (OriginalDecl)
367 *OriginalDecl = OriginalDeclForRC;
368
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000369 // Update cache for every declaration in the redeclaration chain.
370 RawCommentAndCacheFlags Raw;
371 Raw.setRaw(RC);
372 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000373 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000374
375 for (Decl::redecl_iterator I = D->redecls_begin(),
376 E = D->redecls_end();
377 I != E; ++I) {
378 RawCommentAndCacheFlags &R = RedeclComments[*I];
379 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
380 R = Raw;
381 }
382
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000383 return RC;
384}
385
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000386static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
387 SmallVectorImpl<const NamedDecl *> &Redeclared) {
388 const DeclContext *DC = ObjCMethod->getDeclContext();
389 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
390 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
391 if (!ID)
392 return;
393 // Add redeclared method here.
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000394 for (ObjCInterfaceDecl::known_extensions_iterator
395 Ext = ID->known_extensions_begin(),
396 ExtEnd = ID->known_extensions_end();
397 Ext != ExtEnd; ++Ext) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000398 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000399 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000400 ObjCMethod->isInstanceMethod()))
401 Redeclared.push_back(RedeclaredMethod);
402 }
403 }
404}
405
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000406comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
407 const Decl *D) const {
408 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
409 ThisDeclInfo->CommentDecl = D;
410 ThisDeclInfo->IsFilled = false;
411 ThisDeclInfo->fill();
412 ThisDeclInfo->CommentDecl = FC->getDecl();
413 comments::FullComment *CFC =
414 new (*this) comments::FullComment(FC->getBlocks(),
415 ThisDeclInfo);
416 return CFC;
417
418}
419
Richard Smithb39b9d52013-05-21 05:24:00 +0000420comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
421 const RawComment *RC = getRawCommentForDeclNoCache(D);
422 return RC ? RC->parse(*this, 0, D) : 0;
423}
424
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000425comments::FullComment *ASTContext::getCommentForDecl(
426 const Decl *D,
427 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000428 if (D->isInvalidDecl())
429 return NULL;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000430 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000431
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000432 const Decl *Canonical = D->getCanonicalDecl();
433 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
434 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000435
436 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000437 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000438 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000439 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000440 return CFC;
441 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000442 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000443 }
444
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000445 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000446
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000447 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000448 if (!RC) {
449 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000450 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000451 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000452 if (OMD && OMD->isPropertyAccessor())
453 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
454 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
455 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000456 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000457 addRedeclaredMethods(OMD, Overridden);
458 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000459 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
460 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
461 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000462 }
Fariborz Jahanian6384fbb2013-05-02 15:44:16 +0000463 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000464 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000465 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000466 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000467 if (const TagType *TT = QT->getAs<TagType>())
468 if (const Decl *TD = TT->getDecl())
469 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000470 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000471 }
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000472 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
473 while (IC->getSuperClass()) {
474 IC = IC->getSuperClass();
475 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
476 return cloneFullComment(FC, D);
477 }
478 }
479 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
480 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
481 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
482 return cloneFullComment(FC, D);
483 }
484 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
485 if (!(RD = RD->getDefinition()))
486 return NULL;
487 // Check non-virtual bases.
488 for (CXXRecordDecl::base_class_const_iterator I =
489 RD->bases_begin(), E = RD->bases_end(); I != E; ++I) {
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000490 if (I->isVirtual() || (I->getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000491 continue;
492 QualType Ty = I->getType();
493 if (Ty.isNull())
494 continue;
495 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
496 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
497 continue;
498
499 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
500 return cloneFullComment(FC, D);
501 }
502 }
503 // Check virtual bases.
504 for (CXXRecordDecl::base_class_const_iterator I =
505 RD->vbases_begin(), E = RD->vbases_end(); I != E; ++I) {
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000506 if (I->getAccessSpecifier() != AS_public)
507 continue;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000508 QualType Ty = I->getType();
509 if (Ty.isNull())
510 continue;
511 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
512 if (!(VirtualBase= VirtualBase->getDefinition()))
513 continue;
514 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
515 return cloneFullComment(FC, D);
516 }
517 }
518 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000519 return NULL;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000520 }
521
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000522 // If the RawComment was attached to other redeclaration of this Decl, we
523 // should parse the comment in context of that other Decl. This is important
524 // because comments can contain references to parameter names which can be
525 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000526 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000527 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000528
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000529 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000530 ParsedComments[Canonical] = FC;
531 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000532}
533
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000534void
535ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
536 TemplateTemplateParmDecl *Parm) {
537 ID.AddInteger(Parm->getDepth());
538 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000539 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000540
541 TemplateParameterList *Params = Parm->getTemplateParameters();
542 ID.AddInteger(Params->size());
543 for (TemplateParameterList::const_iterator P = Params->begin(),
544 PEnd = Params->end();
545 P != PEnd; ++P) {
546 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
547 ID.AddInteger(0);
548 ID.AddBoolean(TTP->isParameterPack());
549 continue;
550 }
551
552 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
553 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000554 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000555 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000556 if (NTTP->isExpandedParameterPack()) {
557 ID.AddBoolean(true);
558 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000559 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
560 QualType T = NTTP->getExpansionType(I);
561 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
562 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000563 } else
564 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000565 continue;
566 }
567
568 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
569 ID.AddInteger(2);
570 Profile(ID, TTP);
571 }
572}
573
574TemplateTemplateParmDecl *
575ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000576 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000577 // Check if we already have a canonical template template parameter.
578 llvm::FoldingSetNodeID ID;
579 CanonicalTemplateTemplateParm::Profile(ID, TTP);
580 void *InsertPos = 0;
581 CanonicalTemplateTemplateParm *Canonical
582 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
583 if (Canonical)
584 return Canonical->getParam();
585
586 // Build a canonical template parameter list.
587 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000588 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000589 CanonParams.reserve(Params->size());
590 for (TemplateParameterList::const_iterator P = Params->begin(),
591 PEnd = Params->end();
592 P != PEnd; ++P) {
593 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
594 CanonParams.push_back(
595 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000596 SourceLocation(),
597 SourceLocation(),
598 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000599 TTP->getIndex(), 0, false,
600 TTP->isParameterPack()));
601 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000602 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
603 QualType T = getCanonicalType(NTTP->getType());
604 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
605 NonTypeTemplateParmDecl *Param;
606 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000607 SmallVector<QualType, 2> ExpandedTypes;
608 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000609 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
610 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
611 ExpandedTInfos.push_back(
612 getTrivialTypeSourceInfo(ExpandedTypes.back()));
613 }
614
615 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000616 SourceLocation(),
617 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000618 NTTP->getDepth(),
619 NTTP->getPosition(), 0,
620 T,
621 TInfo,
622 ExpandedTypes.data(),
623 ExpandedTypes.size(),
624 ExpandedTInfos.data());
625 } else {
626 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000627 SourceLocation(),
628 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000629 NTTP->getDepth(),
630 NTTP->getPosition(), 0,
631 T,
632 NTTP->isParameterPack(),
633 TInfo);
634 }
635 CanonParams.push_back(Param);
636
637 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000638 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
639 cast<TemplateTemplateParmDecl>(*P)));
640 }
641
642 TemplateTemplateParmDecl *CanonTTP
643 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
644 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000645 TTP->getPosition(),
646 TTP->isParameterPack(),
647 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000648 TemplateParameterList::Create(*this, SourceLocation(),
649 SourceLocation(),
650 CanonParams.data(),
651 CanonParams.size(),
652 SourceLocation()));
653
654 // Get the new insert position for the node we care about.
655 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
656 assert(Canonical == 0 && "Shouldn't be in the map!");
657 (void)Canonical;
658
659 // Create the canonical template template parameter entry.
660 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
661 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
662 return CanonTTP;
663}
664
Charles Davis53c59df2010-08-16 03:33:14 +0000665CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000666 if (!LangOpts.CPlusPlus) return 0;
667
John McCall359b8852013-01-25 22:30:49 +0000668 switch (T.getCXXABI().getKind()) {
669 case TargetCXXABI::GenericARM:
670 case TargetCXXABI::iOS:
John McCall86353412010-08-21 22:46:04 +0000671 return CreateARMCXXABI(*this);
Tim Northover9bb857a2013-01-31 12:13:10 +0000672 case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000673 case TargetCXXABI::GenericItanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000674 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000675 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000676 return CreateMicrosoftCXXABI(*this);
677 }
David Blaikie8a40f702012-01-17 06:56:22 +0000678 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000679}
680
Douglas Gregore8bbc122011-09-02 00:18:52 +0000681static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000682 const LangOptions &LOpts) {
683 if (LOpts.FakeAddressSpaceMap) {
684 // The fake address space map must have a distinct entry for each
685 // language-specific address space.
686 static const unsigned FakeAddrSpaceMap[] = {
687 1, // opencl_global
688 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000689 3, // opencl_constant
690 4, // cuda_device
691 5, // cuda_constant
692 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000693 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000694 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000695 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000696 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000697 }
698}
699
David Tweed31d09b02013-09-13 12:04:22 +0000700static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
701 const LangOptions &LangOpts) {
702 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000703 case LangOptions::ASMM_Target:
704 return TI.useAddressSpaceMapMangling();
705 case LangOptions::ASMM_On:
706 return true;
707 case LangOptions::ASMM_Off:
708 return false;
709 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000710 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000711}
712
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000713ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000714 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000715 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000716 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000717 unsigned size_reserve,
718 bool DelayInitialization)
719 : FunctionProtoTypes(this_()),
720 TemplateSpecializationTypes(this_()),
721 DependentTemplateSpecializationTypes(this_()),
722 SubstTemplateTemplateParmPacks(this_()),
723 GlobalNestedNameSpecifier(0),
Nico Webere1687c52013-06-20 21:44:55 +0000724 Int128Decl(0), UInt128Decl(0), Float128StubDecl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000725 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000726 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanianf2578572012-08-30 18:49:41 +0000727 BOOLDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000728 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000729 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000730 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
731 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
732 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000733 NullTypeSourceInfo(QualType()),
734 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000735 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000736 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000737 Idents(idents), Selectors(sels),
738 BuiltinInfo(builtins),
739 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000740 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000741 Comments(SM), CommentsLoaded(false),
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000742 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
Rafael Espindolace2168f2013-05-29 19:51:12 +0000743 LastSDM(0, 0)
Douglas Gregore8bbc122011-09-02 00:18:52 +0000744{
Mike Stump11289f42009-09-09 15:08:12 +0000745 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000746 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000747
748 if (!DelayInitialization) {
749 assert(t && "No target supplied for ASTContext initialization");
750 InitBuiltinTypes(*t);
751 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000752}
753
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000754ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000755 // Release the DenseMaps associated with DeclContext objects.
756 // FIXME: Is this the ideal solution?
757 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000758
Manuel Klimeka7328992013-06-03 13:51:33 +0000759 // Call all of the deallocation functions on all of their targets.
760 for (DeallocationMap::const_iterator I = Deallocations.begin(),
761 E = Deallocations.end(); I != E; ++I)
762 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
763 (I->first)((I->second)[J]);
764
Ted Kremenek076baeb2010-06-08 23:00:58 +0000765 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000766 // because they can contain DenseMaps.
767 for (llvm::DenseMap<const ObjCContainerDecl*,
768 const ASTRecordLayout*>::iterator
769 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
770 // Increment in loop to prevent using deallocated memory.
771 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
772 R->Destroy(*this);
773
Ted Kremenek076baeb2010-06-08 23:00:58 +0000774 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
775 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
776 // Increment in loop to prevent using deallocated memory.
777 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
778 R->Destroy(*this);
779 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000780
781 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
782 AEnd = DeclAttrs.end();
783 A != AEnd; ++A)
784 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000785
786 for (llvm::DenseMap<const DeclContext *, MangleNumberingContext *>::iterator
787 I = MangleNumberingContexts.begin(),
788 E = MangleNumberingContexts.end();
789 I != E; ++I)
790 delete I->second;
Douglas Gregor561eceb2010-08-30 16:49:28 +0000791}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000792
Douglas Gregor1a809332010-05-23 18:26:36 +0000793void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimeka7328992013-06-03 13:51:33 +0000794 Deallocations[Callback].push_back(Data);
Douglas Gregor1a809332010-05-23 18:26:36 +0000795}
796
Mike Stump11289f42009-09-09 15:08:12 +0000797void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000798ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000799 ExternalSource.reset(Source.take());
800}
801
Chris Lattner4eb445d2007-01-26 01:27:23 +0000802void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000803 llvm::errs() << "\n*** AST Context Stats:\n";
804 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000805
Douglas Gregora30d0462009-05-26 14:40:08 +0000806 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000807#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000808#define ABSTRACT_TYPE(Name, Parent)
809#include "clang/AST/TypeNodes.def"
810 0 // Extra
811 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000812
Chris Lattner4eb445d2007-01-26 01:27:23 +0000813 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
814 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000815 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000816 }
817
Douglas Gregora30d0462009-05-26 14:40:08 +0000818 unsigned Idx = 0;
819 unsigned TotalBytes = 0;
820#define TYPE(Name, Parent) \
821 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000822 llvm::errs() << " " << counts[Idx] << " " << #Name \
823 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000824 TotalBytes += counts[Idx] * sizeof(Name##Type); \
825 ++Idx;
826#define ABSTRACT_TYPE(Name, Parent)
827#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000828
Chandler Carruth3c147a72011-07-04 05:32:14 +0000829 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
830
Douglas Gregor7454c562010-07-02 20:37:36 +0000831 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000832 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
833 << NumImplicitDefaultConstructors
834 << " implicit default constructors created\n";
835 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
836 << NumImplicitCopyConstructors
837 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000838 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000839 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
840 << NumImplicitMoveConstructors
841 << " implicit move constructors created\n";
842 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
843 << NumImplicitCopyAssignmentOperators
844 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000845 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000846 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
847 << NumImplicitMoveAssignmentOperators
848 << " implicit move assignment operators created\n";
849 llvm::errs() << NumImplicitDestructorsDeclared << "/"
850 << NumImplicitDestructors
851 << " implicit destructors created\n";
852
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000853 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000854 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000855 ExternalSource->PrintStats();
856 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000857
Douglas Gregor5b11d492010-07-25 17:53:33 +0000858 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000859}
860
Alp Toker2dea15b2013-12-17 01:22:38 +0000861RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
862 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000863 SourceLocation Loc;
864 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +0000865 if (getLangOpts().CPlusPlus)
866 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
867 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000868 else
Alp Toker2dea15b2013-12-17 01:22:38 +0000869 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
870 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000871 NewDecl->setImplicit();
872 return NewDecl;
873}
874
875TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
876 StringRef Name) const {
877 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
878 TypedefDecl *NewDecl = TypedefDecl::Create(
879 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
880 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
881 NewDecl->setImplicit();
882 return NewDecl;
883}
884
Douglas Gregor801c99d2011-08-12 06:49:56 +0000885TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000886 if (!Int128Decl)
887 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000888 return Int128Decl;
889}
890
891TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000892 if (!UInt128Decl)
893 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000894 return UInt128Decl;
895}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000896
Nico Webere1687c52013-06-20 21:44:55 +0000897TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber5b0b46f2013-06-21 01:29:36 +0000898 assert(LangOpts.CPlusPlus && "should only be called for c++");
Alp Toker56b5cc92013-12-15 10:36:26 +0000899 if (!Float128StubDecl)
Alp Toker2dea15b2013-12-17 01:22:38 +0000900 Float128StubDecl = buildImplicitRecord("__float128");
Alp Toker56b5cc92013-12-15 10:36:26 +0000901
Nico Webere1687c52013-06-20 21:44:55 +0000902 return Float128StubDecl;
903}
904
John McCall48f2d582009-10-23 23:03:21 +0000905void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000906 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000907 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000908 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000909}
910
Douglas Gregore8bbc122011-09-02 00:18:52 +0000911void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
912 assert((!this->Target || this->Target == &Target) &&
913 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000914 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000915
Douglas Gregore8bbc122011-09-02 00:18:52 +0000916 this->Target = &Target;
917
918 ABI.reset(createCXXABI(Target));
919 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +0000920 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000921
Chris Lattner970e54e2006-11-12 00:37:36 +0000922 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000923 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000924
Chris Lattner970e54e2006-11-12 00:37:36 +0000925 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000926 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000927 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000928 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000929 InitBuiltinType(CharTy, BuiltinType::Char_S);
930 else
931 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000932 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000933 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
934 InitBuiltinType(ShortTy, BuiltinType::Short);
935 InitBuiltinType(IntTy, BuiltinType::Int);
936 InitBuiltinType(LongTy, BuiltinType::Long);
937 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000938
Chris Lattner970e54e2006-11-12 00:37:36 +0000939 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000940 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
941 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
942 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
943 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
944 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000945
Chris Lattner970e54e2006-11-12 00:37:36 +0000946 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000947 InitBuiltinType(FloatTy, BuiltinType::Float);
948 InitBuiltinType(DoubleTy, BuiltinType::Double);
949 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000950
Chris Lattnerf122cef2009-04-30 02:43:43 +0000951 // GNU extension, 128-bit integers.
952 InitBuiltinType(Int128Ty, BuiltinType::Int128);
953 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
954
Hans Wennborg0d81e012013-05-10 10:08:40 +0000955 // C++ 3.9.1p5
956 if (TargetInfo::isTypeSigned(Target.getWCharType()))
957 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
958 else // -fshort-wchar makes wchar_t be unsigned.
959 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
960 if (LangOpts.CPlusPlus && LangOpts.WChar)
961 WideCharTy = WCharTy;
962 else {
963 // C99 (or C++ using -fno-wchar).
964 WideCharTy = getFromTargetType(Target.getWCharType());
965 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000966
James Molloy36365542012-05-04 10:55:22 +0000967 WIntTy = getFromTargetType(Target.getWIntType());
968
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000969 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
970 InitBuiltinType(Char16Ty, BuiltinType::Char16);
971 else // C99
972 Char16Ty = getFromTargetType(Target.getChar16Type());
973
974 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
975 InitBuiltinType(Char32Ty, BuiltinType::Char32);
976 else // C99
977 Char32Ty = getFromTargetType(Target.getChar32Type());
978
Douglas Gregor4619e432008-12-05 23:32:09 +0000979 // Placeholder type for type-dependent expressions whose type is
980 // completely unknown. No code should ever check a type against
981 // DependentTy and users should never see it; however, it is here to
982 // help diagnose failures to properly check for type-dependent
983 // expressions.
984 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000985
John McCall36e7fe32010-10-12 00:20:44 +0000986 // Placeholder type for functions.
987 InitBuiltinType(OverloadTy, BuiltinType::Overload);
988
John McCall0009fcc2011-04-26 20:42:42 +0000989 // Placeholder type for bound members.
990 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
991
John McCall526ab472011-10-25 17:37:35 +0000992 // Placeholder type for pseudo-objects.
993 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
994
John McCall31996342011-04-07 08:22:57 +0000995 // "any" type; useful for debugger-like clients.
996 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
997
John McCall8a6b59a2011-10-17 18:09:15 +0000998 // Placeholder type for unbridged ARC casts.
999 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1000
Eli Friedman34866c72012-08-31 00:14:07 +00001001 // Placeholder type for builtin functions.
1002 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1003
Chris Lattner970e54e2006-11-12 00:37:36 +00001004 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001005 FloatComplexTy = getComplexType(FloatTy);
1006 DoubleComplexTy = getComplexType(DoubleTy);
1007 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001008
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001009 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001010 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1011 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001012 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001013
1014 if (LangOpts.OpenCL) {
1015 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1016 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1017 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1018 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1019 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
1020 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001021
Guy Benyei61054192013-02-07 10:55:47 +00001022 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001023 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001024 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001025
1026 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001027 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1028 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001029
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001030 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001031
1032 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001033
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001034 // void * type
1035 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001036
1037 // nullptr type (C++0x 2.14.7)
1038 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001039
1040 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1041 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001042
1043 // Builtin type used to help define __builtin_va_list.
1044 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +00001045}
1046
David Blaikie9c902b52011-09-25 23:23:43 +00001047DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001048 return SourceMgr.getDiagnostics();
1049}
1050
Douglas Gregor561eceb2010-08-30 16:49:28 +00001051AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1052 AttrVec *&Result = DeclAttrs[D];
1053 if (!Result) {
1054 void *Mem = Allocate(sizeof(AttrVec));
1055 Result = new (Mem) AttrVec;
1056 }
1057
1058 return *Result;
1059}
1060
1061/// \brief Erase the attributes corresponding to the given declaration.
1062void ASTContext::eraseDeclAttrs(const Decl *D) {
1063 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1064 if (Pos != DeclAttrs.end()) {
1065 Pos->second->~AttrVec();
1066 DeclAttrs.erase(Pos);
1067 }
1068}
1069
Larisse Voufo39a1e502013-08-06 01:03:05 +00001070// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001071MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001072ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001073 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001074 return getTemplateOrSpecializationInfo(Var)
1075 .dyn_cast<MemberSpecializationInfo *>();
1076}
1077
1078ASTContext::TemplateOrSpecializationInfo
1079ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1080 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1081 TemplateOrInstantiation.find(Var);
1082 if (Pos == TemplateOrInstantiation.end())
1083 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001084
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001085 return Pos->second;
1086}
1087
Mike Stump11289f42009-09-09 15:08:12 +00001088void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001089ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001090 TemplateSpecializationKind TSK,
1091 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001092 assert(Inst->isStaticDataMember() && "Not a static data member");
1093 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001094 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1095 Tmpl, TSK, PointOfInstantiation));
1096}
1097
1098void
1099ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1100 TemplateOrSpecializationInfo TSI) {
1101 assert(!TemplateOrInstantiation[Inst] &&
1102 "Already noted what the variable was instantiated from");
1103 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001104}
1105
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001106FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1107 const FunctionDecl *FD){
1108 assert(FD && "Specialization is 0");
1109 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001110 = ClassScopeSpecializationPattern.find(FD);
1111 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001112 return 0;
1113
1114 return Pos->second;
1115}
1116
1117void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1118 FunctionDecl *Pattern) {
1119 assert(FD && "Specialization is 0");
1120 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001121 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001122}
1123
John McCalle61f2ba2009-11-18 02:36:19 +00001124NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001125ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001126 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001127 = InstantiatedFromUsingDecl.find(UUD);
1128 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001129 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001130
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001131 return Pos->second;
1132}
1133
1134void
John McCallb96ec562009-12-04 22:46:56 +00001135ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1136 assert((isa<UsingDecl>(Pattern) ||
1137 isa<UnresolvedUsingValueDecl>(Pattern) ||
1138 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1139 "pattern decl is not a using decl");
1140 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1141 InstantiatedFromUsingDecl[Inst] = Pattern;
1142}
1143
1144UsingShadowDecl *
1145ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1146 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1147 = InstantiatedFromUsingShadowDecl.find(Inst);
1148 if (Pos == InstantiatedFromUsingShadowDecl.end())
1149 return 0;
1150
1151 return Pos->second;
1152}
1153
1154void
1155ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1156 UsingShadowDecl *Pattern) {
1157 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1158 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001159}
1160
Anders Carlsson5da84842009-09-01 04:26:58 +00001161FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1162 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1163 = InstantiatedFromUnnamedFieldDecl.find(Field);
1164 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1165 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001166
Anders Carlsson5da84842009-09-01 04:26:58 +00001167 return Pos->second;
1168}
1169
1170void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1171 FieldDecl *Tmpl) {
1172 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1173 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1174 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1175 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001176
Anders Carlsson5da84842009-09-01 04:26:58 +00001177 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1178}
1179
Douglas Gregor832940b2010-03-02 23:58:15 +00001180ASTContext::overridden_cxx_method_iterator
1181ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1182 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001183 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001184 if (Pos == OverriddenMethods.end())
1185 return 0;
1186
1187 return Pos->second.begin();
1188}
1189
1190ASTContext::overridden_cxx_method_iterator
1191ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1192 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001193 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001194 if (Pos == OverriddenMethods.end())
1195 return 0;
1196
1197 return Pos->second.end();
1198}
1199
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001200unsigned
1201ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1202 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001203 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001204 if (Pos == OverriddenMethods.end())
1205 return 0;
1206
1207 return Pos->second.size();
1208}
1209
Douglas Gregor832940b2010-03-02 23:58:15 +00001210void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1211 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001212 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001213 OverriddenMethods[Method].push_back(Overridden);
1214}
1215
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001216void ASTContext::getOverriddenMethods(
1217 const NamedDecl *D,
1218 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001219 assert(D);
1220
1221 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001222 Overridden.append(overridden_methods_begin(CXXMethod),
1223 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001224 return;
1225 }
1226
1227 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1228 if (!Method)
1229 return;
1230
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001231 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1232 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001233 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001234}
1235
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001236void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1237 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1238 assert(!Import->isFromASTFile() && "Non-local import declaration");
1239 if (!FirstLocalImport) {
1240 FirstLocalImport = Import;
1241 LastLocalImport = Import;
1242 return;
1243 }
1244
1245 LastLocalImport->NextLocalImport = Import;
1246 LastLocalImport = Import;
1247}
1248
Chris Lattner53cfe802007-07-18 17:52:12 +00001249//===----------------------------------------------------------------------===//
1250// Type Sizing and Analysis
1251//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001252
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001253/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1254/// scalar floating point type.
1255const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001256 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001257 assert(BT && "Not a floating point type!");
1258 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001259 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001260 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001261 case BuiltinType::Float: return Target->getFloatFormat();
1262 case BuiltinType::Double: return Target->getDoubleFormat();
1263 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001264 }
1265}
1266
Rafael Espindola71eccb32013-08-08 19:53:46 +00001267CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001268 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001269
John McCall94268702010-10-08 18:24:19 +00001270 bool UseAlignAttrOnly = false;
1271 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1272 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001273
John McCall94268702010-10-08 18:24:19 +00001274 // __attribute__((aligned)) can increase or decrease alignment
1275 // *except* on a struct or struct member, where it only increases
1276 // alignment unless 'packed' is also specified.
1277 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001278 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001279 // ignore that possibility; Sema should diagnose it.
1280 if (isa<FieldDecl>(D)) {
1281 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1282 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1283 } else {
1284 UseAlignAttrOnly = true;
1285 }
1286 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001287 else if (isa<FieldDecl>(D))
1288 UseAlignAttrOnly =
1289 D->hasAttr<PackedAttr>() ||
1290 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001291
John McCall4e819612011-01-20 07:57:12 +00001292 // If we're using the align attribute only, just ignore everything
1293 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001294 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001295 // do nothing
1296
John McCall94268702010-10-08 18:24:19 +00001297 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001298 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001299 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001300 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001301 T = RT->getPointeeType();
1302 else
1303 T = getPointerType(RT->getPointeeType());
1304 }
1305 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001306 // Adjust alignments of declarations with array type by the
1307 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001308 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001309 unsigned MinWidth = Target->getLargeArrayMinWidth();
1310 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001311 if (isa<VariableArrayType>(arrayType))
1312 Align = std::max(Align, Target->getLargeArrayAlign());
1313 else if (isa<ConstantArrayType>(arrayType) &&
1314 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1315 Align = std::max(Align, Target->getLargeArrayAlign());
1316 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001317
John McCall33ddac02011-01-19 10:06:00 +00001318 // Walk through any array types while we're at it.
1319 T = getBaseElementType(arrayType);
1320 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001321 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001322 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1323 if (VD->hasGlobalStorage())
1324 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1325 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001326 }
John McCall4e819612011-01-20 07:57:12 +00001327
1328 // Fields can be subject to extra alignment constraints, like if
1329 // the field is packed, the struct is packed, or the struct has a
1330 // a max-field-alignment constraint (#pragma pack). So calculate
1331 // the actual alignment of the field within the struct, and then
1332 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001333 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1334 const RecordDecl *Parent = Field->getParent();
1335 // We can only produce a sensible answer if the record is valid.
1336 if (!Parent->isInvalidDecl()) {
1337 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001338
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001339 // Start with the record's overall alignment.
1340 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001341
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001342 // Use the GCD of that and the offset within the record.
1343 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1344 if (Offset > 0) {
1345 // Alignment is always a power of 2, so the GCD will be a power of 2,
1346 // which means we get to do this crazy thing instead of Euclid's.
1347 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1348 if (LowBitOfOffset < FieldAlign)
1349 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1350 }
1351
1352 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001353 }
Charles Davis3fc51072010-02-23 04:52:00 +00001354 }
Chris Lattner68061312009-01-24 21:53:27 +00001355 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001356
Ken Dyckcc56c542011-01-15 18:38:59 +00001357 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001358}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001359
John McCallf1249922012-08-21 04:10:00 +00001360// getTypeInfoDataSizeInChars - Return the size of a type, in
1361// chars. If the type is a record, its data size is returned. This is
1362// the size of the memcpy that's performed when assigning this type
1363// using a trivial copy/move assignment operator.
1364std::pair<CharUnits, CharUnits>
1365ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1366 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1367
1368 // In C++, objects can sometimes be allocated into the tail padding
1369 // of a base-class subobject. We decide whether that's possible
1370 // during class layout, so here we can just trust the layout results.
1371 if (getLangOpts().CPlusPlus) {
1372 if (const RecordType *RT = T->getAs<RecordType>()) {
1373 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1374 sizeAndAlign.first = layout.getDataSize();
1375 }
1376 }
1377
1378 return sizeAndAlign;
1379}
1380
Richard Trieu04d2d942013-05-14 21:59:17 +00001381/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1382/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1383std::pair<CharUnits, CharUnits>
1384static getConstantArrayInfoInChars(const ASTContext &Context,
1385 const ConstantArrayType *CAT) {
1386 std::pair<CharUnits, CharUnits> EltInfo =
1387 Context.getTypeInfoInChars(CAT->getElementType());
1388 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001389 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1390 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001391 "Overflow in array type char size evaluation");
1392 uint64_t Width = EltInfo.first.getQuantity() * Size;
1393 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001394 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1395 Context.getTargetInfo().getPointerWidth(0) == 64)
1396 Width = llvm::RoundUpToAlignment(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001397 return std::make_pair(CharUnits::fromQuantity(Width),
1398 CharUnits::fromQuantity(Align));
1399}
1400
John McCall87fe5d52010-05-20 01:18:31 +00001401std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001402ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001403 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1404 return getConstantArrayInfoInChars(*this, CAT);
John McCall87fe5d52010-05-20 01:18:31 +00001405 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +00001406 return std::make_pair(toCharUnitsFromBits(Info.first),
1407 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +00001408}
1409
1410std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001411ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001412 return getTypeInfoInChars(T.getTypePtr());
1413}
1414
Daniel Dunbarc6475872012-03-09 04:12:54 +00001415std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1416 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1417 if (it != MemoizedTypeInfo.end())
1418 return it->second;
1419
1420 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1421 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1422 return Info;
1423}
1424
1425/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1426/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001427///
1428/// FIXME: Pointers into different addr spaces could have different sizes and
1429/// alignment requirements: getPointerInfo should take an AddrSpace, this
1430/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001431std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001432ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001433 uint64_t Width=0;
1434 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001435 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001436#define TYPE(Class, Base)
1437#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001438#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001439#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001440#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1441 case Type::Class: \
1442 assert(!T->isDependentType() && "should not see dependent types here"); \
1443 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001444#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001445 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001446
Chris Lattner355332d2007-07-13 22:27:08 +00001447 case Type::FunctionNoProto:
1448 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001449 // GCC extension: alignof(function) = 32 bits
1450 Width = 0;
1451 Align = 32;
1452 break;
1453
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001454 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001455 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001456 Width = 0;
1457 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1458 break;
1459
Steve Naroff5c131802007-08-30 01:06:46 +00001460 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001461 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001462
Chris Lattner37e05872008-03-05 18:54:05 +00001463 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001464 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001465 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1466 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001467 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001468 Align = EltInfo.second;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001469 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1470 getTargetInfo().getPointerWidth(0) == 64)
1471 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001472 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001473 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001474 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001475 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001476 const VectorType *VT = cast<VectorType>(T);
1477 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1478 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001479 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001480 // If the alignment is not a power of 2, round up to the next power of 2.
1481 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001482 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001483 Align = llvm::NextPowerOf2(Align);
1484 Width = llvm::RoundUpToAlignment(Width, Align);
1485 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001486 // Adjust the alignment based on the target max.
1487 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1488 if (TargetVectorAlign && TargetVectorAlign < Align)
1489 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001490 break;
1491 }
Chris Lattner647fb222007-07-18 18:26:58 +00001492
Chris Lattner7570e9c2008-03-08 08:52:55 +00001493 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001494 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001495 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001496 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001497 // GCC extension: alignof(void) = 8 bits.
1498 Width = 0;
1499 Align = 8;
1500 break;
1501
Chris Lattner6a4f7452007-12-19 19:23:28 +00001502 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001503 Width = Target->getBoolWidth();
1504 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001505 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001506 case BuiltinType::Char_S:
1507 case BuiltinType::Char_U:
1508 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001509 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001510 Width = Target->getCharWidth();
1511 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001512 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001513 case BuiltinType::WChar_S:
1514 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001515 Width = Target->getWCharWidth();
1516 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001517 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001518 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001519 Width = Target->getChar16Width();
1520 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001521 break;
1522 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001523 Width = Target->getChar32Width();
1524 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001525 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001526 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001527 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001528 Width = Target->getShortWidth();
1529 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001530 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001531 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001532 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001533 Width = Target->getIntWidth();
1534 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001535 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001536 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001537 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001538 Width = Target->getLongWidth();
1539 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001540 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001541 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001542 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001543 Width = Target->getLongLongWidth();
1544 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001545 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001546 case BuiltinType::Int128:
1547 case BuiltinType::UInt128:
1548 Width = 128;
1549 Align = 128; // int128_t is 128-bit aligned on all targets.
1550 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001551 case BuiltinType::Half:
1552 Width = Target->getHalfWidth();
1553 Align = Target->getHalfAlign();
1554 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001555 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001556 Width = Target->getFloatWidth();
1557 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001558 break;
1559 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001560 Width = Target->getDoubleWidth();
1561 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001562 break;
1563 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001564 Width = Target->getLongDoubleWidth();
1565 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001566 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001567 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001568 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1569 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001570 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001571 case BuiltinType::ObjCId:
1572 case BuiltinType::ObjCClass:
1573 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001574 Width = Target->getPointerWidth(0);
1575 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001576 break;
Guy Benyei61054192013-02-07 10:55:47 +00001577 case BuiltinType::OCLSampler:
1578 // Samplers are modeled as integers.
1579 Width = Target->getIntWidth();
1580 Align = Target->getIntAlign();
1581 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001582 case BuiltinType::OCLEvent:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001583 case BuiltinType::OCLImage1d:
1584 case BuiltinType::OCLImage1dArray:
1585 case BuiltinType::OCLImage1dBuffer:
1586 case BuiltinType::OCLImage2d:
1587 case BuiltinType::OCLImage2dArray:
1588 case BuiltinType::OCLImage3d:
1589 // Currently these types are pointers to opaque types.
1590 Width = Target->getPointerWidth(0);
1591 Align = Target->getPointerAlign(0);
1592 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001593 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001594 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001595 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001596 Width = Target->getPointerWidth(0);
1597 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001598 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001599 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001600 unsigned AS = getTargetAddressSpace(
1601 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001602 Width = Target->getPointerWidth(AS);
1603 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001604 break;
1605 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001606 case Type::LValueReference:
1607 case Type::RValueReference: {
1608 // alignof and sizeof should never enter this code path here, so we go
1609 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001610 unsigned AS = getTargetAddressSpace(
1611 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001612 Width = Target->getPointerWidth(AS);
1613 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001614 break;
1615 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001616 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001617 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001618 Width = Target->getPointerWidth(AS);
1619 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001620 break;
1621 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001622 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001623 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Reid Kleckner3a52abf2013-03-28 20:02:56 +00001624 llvm::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001625 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001626 }
Chris Lattner647fb222007-07-18 18:26:58 +00001627 case Type::Complex: {
1628 // Complex types have the same alignment as their elements, but twice the
1629 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001630 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001631 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001632 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001633 Align = EltInfo.second;
1634 break;
1635 }
John McCall8b07ec22010-05-15 11:32:37 +00001636 case Type::ObjCObject:
1637 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001638 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001639 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001640 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001641 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001642 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001643 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001644 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001645 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001646 break;
1647 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001648 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001649 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001650 const TagType *TT = cast<TagType>(T);
1651
1652 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001653 Width = 8;
1654 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001655 break;
1656 }
Mike Stump11289f42009-09-09 15:08:12 +00001657
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001658 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001659 return getTypeInfo(ET->getDecl()->getIntegerType());
1660
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001661 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001662 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001663 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001664 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001665 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001666 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001667
Chris Lattner63d2b362009-10-22 05:17:15 +00001668 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001669 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1670 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001671
Richard Smith30482bc2011-02-20 03:19:35 +00001672 case Type::Auto: {
1673 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001674 assert(!A->getDeducedType().isNull() &&
1675 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001676 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001677 }
1678
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001679 case Type::Paren:
1680 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1681
Douglas Gregoref462e62009-04-30 17:32:17 +00001682 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001683 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001684 std::pair<uint64_t, unsigned> Info
1685 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001686 // If the typedef has an aligned attribute on it, it overrides any computed
1687 // alignment we have. This violates the GCC documentation (which says that
1688 // attribute(aligned) can only round up) but matches its implementation.
1689 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1690 Align = AttrAlign;
1691 else
1692 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001693 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001694 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001695 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001696
Abramo Bagnara6150c882010-05-11 21:36:43 +00001697 case Type::Elaborated:
1698 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001699
John McCall81904512011-01-06 01:58:22 +00001700 case Type::Attributed:
1701 return getTypeInfo(
1702 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1703
Eli Friedman0dfb8892011-10-06 23:00:33 +00001704 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001705 // Start with the base type information.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001706 std::pair<uint64_t, unsigned> Info
1707 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1708 Width = Info.first;
1709 Align = Info.second;
John McCalla8ec7eb2013-03-07 21:37:17 +00001710
1711 // If the size of the type doesn't exceed the platform's max
1712 // atomic promotion width, make the size and alignment more
1713 // favorable to atomic operations:
1714 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1715 // Round the size up to a power of 2.
1716 if (!llvm::isPowerOf2_64(Width))
1717 Width = llvm::NextPowerOf2(Width);
1718
1719 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001720 Align = static_cast<unsigned>(Width);
1721 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001722 }
1723
Douglas Gregoref462e62009-04-30 17:32:17 +00001724 }
Mike Stump11289f42009-09-09 15:08:12 +00001725
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001726 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001727 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001728}
1729
Ken Dyckcc56c542011-01-15 18:38:59 +00001730/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1731CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1732 return CharUnits::fromQuantity(BitSize / getCharWidth());
1733}
1734
Ken Dyckb0fcc592011-02-11 01:54:29 +00001735/// toBits - Convert a size in characters to a size in characters.
1736int64_t ASTContext::toBits(CharUnits CharSize) const {
1737 return CharSize.getQuantity() * getCharWidth();
1738}
1739
Ken Dyck8c89d592009-12-22 14:23:30 +00001740/// getTypeSizeInChars - Return the size of the specified type, in characters.
1741/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001742CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001743 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001744}
Jay Foad39c79802011-01-12 09:06:06 +00001745CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001746 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001747}
1748
Ken Dycka6046ab2010-01-26 17:25:18 +00001749/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001750/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001751CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001752 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001753}
Jay Foad39c79802011-01-12 09:06:06 +00001754CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001755 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001756}
1757
Chris Lattnera3402cd2009-01-27 18:08:34 +00001758/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1759/// type for the current target in bits. This can be different than the ABI
1760/// alignment in cases where it is beneficial for performance to overalign
1761/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001762unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001763 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001764
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001765 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1766 return ABIAlign; // Never overalign on XCore.
1767
Eli Friedman7ab09572009-05-25 21:27:19 +00001768 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001769 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001770 T = CT->getElementType().getTypePtr();
1771 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001772 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1773 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001774 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1775
Chris Lattnera3402cd2009-01-27 18:08:34 +00001776 return ABIAlign;
1777}
1778
Ulrich Weigandfa806422013-05-06 16:23:57 +00001779/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1780/// to a global variable of the specified type.
1781unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1782 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1783}
1784
1785/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1786/// should be given to a global variable of the specified type.
1787CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1788 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1789}
1790
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001791/// DeepCollectObjCIvars -
1792/// This routine first collects all declared, but not synthesized, ivars in
1793/// super class and then collects all ivars, including those synthesized for
1794/// current class. This routine is used for implementation of current class
1795/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001796///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001797void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1798 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001799 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001800 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1801 DeepCollectObjCIvars(SuperClass, false, Ivars);
1802 if (!leafClass) {
1803 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1804 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001805 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001806 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001807 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001808 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001809 Iv= Iv->getNextIvar())
1810 Ivars.push_back(Iv);
1811 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001812}
1813
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001814/// CollectInheritedProtocols - Collect all protocols in current class and
1815/// those inherited by it.
1816void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001817 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001818 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001819 // We can use protocol_iterator here instead of
1820 // all_referenced_protocol_iterator since we are walking all categories.
1821 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1822 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001823 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001824 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001825 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001826 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001827 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001828 CollectInheritedProtocols(*P, Protocols);
1829 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001830 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001831
1832 // Categories of this Interface.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001833 for (ObjCInterfaceDecl::visible_categories_iterator
1834 Cat = OI->visible_categories_begin(),
1835 CatEnd = OI->visible_categories_end();
1836 Cat != CatEnd; ++Cat) {
1837 CollectInheritedProtocols(*Cat, Protocols);
1838 }
1839
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001840 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1841 while (SD) {
1842 CollectInheritedProtocols(SD, Protocols);
1843 SD = SD->getSuperClass();
1844 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001845 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001846 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001847 PE = OC->protocol_end(); P != PE; ++P) {
1848 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001849 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001850 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1851 PE = Proto->protocol_end(); P != PE; ++P)
1852 CollectInheritedProtocols(*P, Protocols);
1853 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001854 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001855 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1856 PE = OP->protocol_end(); P != PE; ++P) {
1857 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001858 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001859 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1860 PE = Proto->protocol_end(); P != PE; ++P)
1861 CollectInheritedProtocols(*P, Protocols);
1862 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001863 }
1864}
1865
Jay Foad39c79802011-01-12 09:06:06 +00001866unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001867 unsigned count = 0;
1868 // Count ivars declared in class extension.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001869 for (ObjCInterfaceDecl::known_extensions_iterator
1870 Ext = OI->known_extensions_begin(),
1871 ExtEnd = OI->known_extensions_end();
1872 Ext != ExtEnd; ++Ext) {
1873 count += Ext->ivar_size();
1874 }
1875
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001876 // Count ivar defined in this class's implementation. This
1877 // includes synthesized ivars.
1878 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001879 count += ImplDecl->ivar_size();
1880
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001881 return count;
1882}
1883
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001884bool ASTContext::isSentinelNullExpr(const Expr *E) {
1885 if (!E)
1886 return false;
1887
1888 // nullptr_t is always treated as null.
1889 if (E->getType()->isNullPtrType()) return true;
1890
1891 if (E->getType()->isAnyPointerType() &&
1892 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1893 Expr::NPC_ValueDependentIsNull))
1894 return true;
1895
1896 // Unfortunately, __null has type 'int'.
1897 if (isa<GNUNullExpr>(E)) return true;
1898
1899 return false;
1900}
1901
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001902/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1903ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1904 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1905 I = ObjCImpls.find(D);
1906 if (I != ObjCImpls.end())
1907 return cast<ObjCImplementationDecl>(I->second);
1908 return 0;
1909}
1910/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1911ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1912 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1913 I = ObjCImpls.find(D);
1914 if (I != ObjCImpls.end())
1915 return cast<ObjCCategoryImplDecl>(I->second);
1916 return 0;
1917}
1918
1919/// \brief Set the implementation of ObjCInterfaceDecl.
1920void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1921 ObjCImplementationDecl *ImplD) {
1922 assert(IFaceD && ImplD && "Passed null params");
1923 ObjCImpls[IFaceD] = ImplD;
1924}
1925/// \brief Set the implementation of ObjCCategoryDecl.
1926void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1927 ObjCCategoryImplDecl *ImplD) {
1928 assert(CatD && ImplD && "Passed null params");
1929 ObjCImpls[CatD] = ImplD;
1930}
1931
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001932const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1933 const NamedDecl *ND) const {
1934 if (const ObjCInterfaceDecl *ID =
1935 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001936 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001937 if (const ObjCCategoryDecl *CD =
1938 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001939 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001940 if (const ObjCImplDecl *IMD =
1941 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001942 return IMD->getClassInterface();
1943
1944 return 0;
1945}
1946
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001947/// \brief Get the copy initialization expression of VarDecl,or NULL if
1948/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001949Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001950 assert(VD && "Passed null params");
1951 assert(VD->hasAttr<BlocksAttr>() &&
1952 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001953 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001954 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001955 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1956}
1957
1958/// \brief Set the copy inialization expression of a block var decl.
1959void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1960 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001961 assert(VD->hasAttr<BlocksAttr>() &&
1962 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001963 BlockVarCopyInits[VD] = Init;
1964}
1965
John McCallbcd03502009-12-07 02:54:59 +00001966TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001967 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001968 if (!DataSize)
1969 DataSize = TypeLoc::getFullDataSizeForType(T);
1970 else
1971 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001972 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001973
John McCallbcd03502009-12-07 02:54:59 +00001974 TypeSourceInfo *TInfo =
1975 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1976 new (TInfo) TypeSourceInfo(T);
1977 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001978}
1979
John McCallbcd03502009-12-07 02:54:59 +00001980TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001981 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001982 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001983 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001984 return DI;
1985}
1986
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001987const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001988ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001989 return getObjCLayout(D, 0);
1990}
1991
1992const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001993ASTContext::getASTObjCImplementationLayout(
1994 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001995 return getObjCLayout(D->getClassInterface(), D);
1996}
1997
Chris Lattner983a8bb2007-07-13 22:13:22 +00001998//===----------------------------------------------------------------------===//
1999// Type creation/memoization methods
2000//===----------------------------------------------------------------------===//
2001
Jay Foad39c79802011-01-12 09:06:06 +00002002QualType
John McCall33ddac02011-01-19 10:06:00 +00002003ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2004 unsigned fastQuals = quals.getFastQualifiers();
2005 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002006
2007 // Check if we've already instantiated this type.
2008 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002009 ExtQuals::Profile(ID, baseType, quals);
2010 void *insertPos = 0;
2011 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2012 assert(eq->getQualifiers() == quals);
2013 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002014 }
2015
John McCall33ddac02011-01-19 10:06:00 +00002016 // If the base type is not canonical, make the appropriate canonical type.
2017 QualType canon;
2018 if (!baseType->isCanonicalUnqualified()) {
2019 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002020 canonSplit.Quals.addConsistentQualifiers(quals);
2021 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002022
2023 // Re-find the insert position.
2024 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2025 }
2026
2027 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2028 ExtQualNodes.InsertNode(eq, insertPos);
2029 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002030}
2031
Jay Foad39c79802011-01-12 09:06:06 +00002032QualType
2033ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002034 QualType CanT = getCanonicalType(T);
2035 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002036 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002037
John McCall8ccfcb52009-09-24 19:53:00 +00002038 // If we are composing extended qualifiers together, merge together
2039 // into one ExtQuals node.
2040 QualifierCollector Quals;
2041 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002042
John McCall8ccfcb52009-09-24 19:53:00 +00002043 // If this type already has an address space specified, it cannot get
2044 // another one.
2045 assert(!Quals.hasAddressSpace() &&
2046 "Type cannot be in multiple addr spaces!");
2047 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002048
John McCall8ccfcb52009-09-24 19:53:00 +00002049 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002050}
2051
Chris Lattnerd60183d2009-02-18 22:53:11 +00002052QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002053 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002054 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002055 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002056 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002057
John McCall53fa7142010-12-24 02:08:15 +00002058 if (const PointerType *ptr = T->getAs<PointerType>()) {
2059 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002060 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002061 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2062 return getPointerType(ResultType);
2063 }
2064 }
Mike Stump11289f42009-09-09 15:08:12 +00002065
John McCall8ccfcb52009-09-24 19:53:00 +00002066 // If we are composing extended qualifiers together, merge together
2067 // into one ExtQuals node.
2068 QualifierCollector Quals;
2069 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002070
John McCall8ccfcb52009-09-24 19:53:00 +00002071 // If this type already has an ObjCGC specified, it cannot get
2072 // another one.
2073 assert(!Quals.hasObjCGCAttr() &&
2074 "Type cannot have multiple ObjCGCs!");
2075 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002076
John McCall8ccfcb52009-09-24 19:53:00 +00002077 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002078}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002079
John McCall4f5019e2010-12-19 02:44:49 +00002080const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2081 FunctionType::ExtInfo Info) {
2082 if (T->getExtInfo() == Info)
2083 return T;
2084
2085 QualType Result;
2086 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002087 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002088 } else {
2089 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2090 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2091 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002092 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002093 }
2094
2095 return cast<FunctionType>(Result.getTypePtr());
2096}
2097
Richard Smith2a7d4812013-05-04 07:00:32 +00002098void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2099 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002100 FD = FD->getMostRecentDecl();
2101 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002102 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2103 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002104 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002105 if (FunctionDecl *Next = FD->getPreviousDecl())
2106 FD = Next;
2107 else
2108 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002109 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002110 if (ASTMutationListener *L = getASTMutationListener())
2111 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002112}
2113
Chris Lattnerc6395932007-06-22 20:56:16 +00002114/// getComplexType - Return the uniqued reference to the type for a complex
2115/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002116QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002117 // Unique pointers, to guarantee there is only one pointer of a particular
2118 // structure.
2119 llvm::FoldingSetNodeID ID;
2120 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002121
Chris Lattnerc6395932007-06-22 20:56:16 +00002122 void *InsertPos = 0;
2123 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2124 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002125
Chris Lattnerc6395932007-06-22 20:56:16 +00002126 // If the pointee type isn't canonical, this won't be a canonical type either,
2127 // so fill in the canonical type field.
2128 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002129 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002130 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002131
Chris Lattnerc6395932007-06-22 20:56:16 +00002132 // Get the new insert position for the node we care about.
2133 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002134 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002135 }
John McCall90d1c2d2009-09-24 23:30:46 +00002136 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002137 Types.push_back(New);
2138 ComplexTypes.InsertNode(New, InsertPos);
2139 return QualType(New, 0);
2140}
2141
Chris Lattner970e54e2006-11-12 00:37:36 +00002142/// getPointerType - Return the uniqued reference to the type for a pointer to
2143/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002144QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002145 // Unique pointers, to guarantee there is only one pointer of a particular
2146 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002147 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002148 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002149
Chris Lattner67521df2007-01-27 01:29:36 +00002150 void *InsertPos = 0;
2151 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002152 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002153
Chris Lattner7ccecb92006-11-12 08:50:50 +00002154 // If the pointee type isn't canonical, this won't be a canonical type either,
2155 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002156 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002157 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002158 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002159
Bob Wilsonc8541f22013-03-15 17:12:43 +00002160 // Get the new insert position for the node we care about.
2161 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2162 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2163 }
John McCall90d1c2d2009-09-24 23:30:46 +00002164 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002165 Types.push_back(New);
2166 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002167 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002168}
2169
Reid Kleckner0503a872013-12-05 01:23:43 +00002170QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2171 llvm::FoldingSetNodeID ID;
2172 AdjustedType::Profile(ID, Orig, New);
2173 void *InsertPos = 0;
2174 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2175 if (AT)
2176 return QualType(AT, 0);
2177
2178 QualType Canonical = getCanonicalType(New);
2179
2180 // Get the new insert position for the node we care about.
2181 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2182 assert(AT == 0 && "Shouldn't be in the map!");
2183
2184 AT = new (*this, TypeAlignment)
2185 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2186 Types.push_back(AT);
2187 AdjustedTypes.InsertNode(AT, InsertPos);
2188 return QualType(AT, 0);
2189}
2190
Reid Kleckner8a365022013-06-24 17:51:48 +00002191QualType ASTContext::getDecayedType(QualType T) const {
2192 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2193
Reid Kleckner8a365022013-06-24 17:51:48 +00002194 QualType Decayed;
2195
2196 // C99 6.7.5.3p7:
2197 // A declaration of a parameter as "array of type" shall be
2198 // adjusted to "qualified pointer to type", where the type
2199 // qualifiers (if any) are those specified within the [ and ] of
2200 // the array type derivation.
2201 if (T->isArrayType())
2202 Decayed = getArrayDecayedType(T);
2203
2204 // C99 6.7.5.3p8:
2205 // A declaration of a parameter as "function returning type"
2206 // shall be adjusted to "pointer to function returning type", as
2207 // in 6.3.2.1.
2208 if (T->isFunctionType())
2209 Decayed = getPointerType(T);
2210
Reid Kleckner0503a872013-12-05 01:23:43 +00002211 llvm::FoldingSetNodeID ID;
2212 AdjustedType::Profile(ID, T, Decayed);
2213 void *InsertPos = 0;
2214 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2215 if (AT)
2216 return QualType(AT, 0);
2217
Reid Kleckner8a365022013-06-24 17:51:48 +00002218 QualType Canonical = getCanonicalType(Decayed);
2219
2220 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002221 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2222 assert(AT == 0 && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002223
Reid Kleckner0503a872013-12-05 01:23:43 +00002224 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2225 Types.push_back(AT);
2226 AdjustedTypes.InsertNode(AT, InsertPos);
2227 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002228}
2229
Mike Stump11289f42009-09-09 15:08:12 +00002230/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002231/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002232QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002233 assert(T->isFunctionType() && "block of function types only");
2234 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002235 // structure.
2236 llvm::FoldingSetNodeID ID;
2237 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002238
Steve Naroffec33ed92008-08-27 16:04:49 +00002239 void *InsertPos = 0;
2240 if (BlockPointerType *PT =
2241 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2242 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002243
2244 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002245 // type either so fill in the canonical type field.
2246 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002247 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002248 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002249
Steve Naroffec33ed92008-08-27 16:04:49 +00002250 // Get the new insert position for the node we care about.
2251 BlockPointerType *NewIP =
2252 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002253 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002254 }
John McCall90d1c2d2009-09-24 23:30:46 +00002255 BlockPointerType *New
2256 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002257 Types.push_back(New);
2258 BlockPointerTypes.InsertNode(New, InsertPos);
2259 return QualType(New, 0);
2260}
2261
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002262/// getLValueReferenceType - Return the uniqued reference to the type for an
2263/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002264QualType
2265ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002266 assert(getCanonicalType(T) != OverloadTy &&
2267 "Unresolved overloaded function type");
2268
Bill Wendling3708c182007-05-27 10:15:43 +00002269 // Unique pointers, to guarantee there is only one pointer of a particular
2270 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002271 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002272 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002273
2274 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002275 if (LValueReferenceType *RT =
2276 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002277 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002278
John McCallfc93cf92009-10-22 22:37:11 +00002279 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2280
Bill Wendling3708c182007-05-27 10:15:43 +00002281 // If the referencee type isn't canonical, this won't be a canonical type
2282 // either, so fill in the canonical type field.
2283 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002284 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2285 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2286 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002287
Bill Wendling3708c182007-05-27 10:15:43 +00002288 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002289 LValueReferenceType *NewIP =
2290 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002291 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002292 }
2293
John McCall90d1c2d2009-09-24 23:30:46 +00002294 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002295 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2296 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002297 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002298 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002299
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002300 return QualType(New, 0);
2301}
2302
2303/// getRValueReferenceType - Return the uniqued reference to the type for an
2304/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002305QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002306 // Unique pointers, to guarantee there is only one pointer of a particular
2307 // structure.
2308 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002309 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002310
2311 void *InsertPos = 0;
2312 if (RValueReferenceType *RT =
2313 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2314 return QualType(RT, 0);
2315
John McCallfc93cf92009-10-22 22:37:11 +00002316 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2317
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002318 // If the referencee type isn't canonical, this won't be a canonical type
2319 // either, so fill in the canonical type field.
2320 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002321 if (InnerRef || !T.isCanonical()) {
2322 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2323 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002324
2325 // Get the new insert position for the node we care about.
2326 RValueReferenceType *NewIP =
2327 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002328 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002329 }
2330
John McCall90d1c2d2009-09-24 23:30:46 +00002331 RValueReferenceType *New
2332 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002333 Types.push_back(New);
2334 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002335 return QualType(New, 0);
2336}
2337
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002338/// getMemberPointerType - Return the uniqued reference to the type for a
2339/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002340QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002341 // Unique pointers, to guarantee there is only one pointer of a particular
2342 // structure.
2343 llvm::FoldingSetNodeID ID;
2344 MemberPointerType::Profile(ID, T, Cls);
2345
2346 void *InsertPos = 0;
2347 if (MemberPointerType *PT =
2348 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2349 return QualType(PT, 0);
2350
2351 // If the pointee or class type isn't canonical, this won't be a canonical
2352 // type either, so fill in the canonical type field.
2353 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002354 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002355 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2356
2357 // Get the new insert position for the node we care about.
2358 MemberPointerType *NewIP =
2359 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002360 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002361 }
John McCall90d1c2d2009-09-24 23:30:46 +00002362 MemberPointerType *New
2363 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002364 Types.push_back(New);
2365 MemberPointerTypes.InsertNode(New, InsertPos);
2366 return QualType(New, 0);
2367}
2368
Mike Stump11289f42009-09-09 15:08:12 +00002369/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002370/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002371QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002372 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002373 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002374 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002375 assert((EltTy->isDependentType() ||
2376 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002377 "Constant array of VLAs is illegal!");
2378
Chris Lattnere2df3f92009-05-13 04:12:56 +00002379 // Convert the array size into a canonical width matching the pointer size for
2380 // the target.
2381 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002382 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002383 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002384
Chris Lattner23b7eb62007-06-15 23:05:46 +00002385 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002386 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002387
Chris Lattner36f8e652007-01-27 08:31:04 +00002388 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002389 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002390 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002391 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002392
John McCall33ddac02011-01-19 10:06:00 +00002393 // If the element type isn't canonical or has qualifiers, this won't
2394 // be a canonical type either, so fill in the canonical type field.
2395 QualType Canon;
2396 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2397 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002398 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002399 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002400 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002401
Chris Lattner36f8e652007-01-27 08:31:04 +00002402 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002403 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002404 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002405 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002406 }
Mike Stump11289f42009-09-09 15:08:12 +00002407
John McCall90d1c2d2009-09-24 23:30:46 +00002408 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002409 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002410 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002411 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002412 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002413}
2414
John McCall06549462011-01-18 08:40:38 +00002415/// getVariableArrayDecayedType - Turns the given type, which may be
2416/// variably-modified, into the corresponding type with all the known
2417/// sizes replaced with [*].
2418QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2419 // Vastly most common case.
2420 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002421
John McCall06549462011-01-18 08:40:38 +00002422 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002423
John McCall06549462011-01-18 08:40:38 +00002424 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002425 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002426 switch (ty->getTypeClass()) {
2427#define TYPE(Class, Base)
2428#define ABSTRACT_TYPE(Class, Base)
2429#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2430#include "clang/AST/TypeNodes.def"
2431 llvm_unreachable("didn't desugar past all non-canonical types?");
2432
2433 // These types should never be variably-modified.
2434 case Type::Builtin:
2435 case Type::Complex:
2436 case Type::Vector:
2437 case Type::ExtVector:
2438 case Type::DependentSizedExtVector:
2439 case Type::ObjCObject:
2440 case Type::ObjCInterface:
2441 case Type::ObjCObjectPointer:
2442 case Type::Record:
2443 case Type::Enum:
2444 case Type::UnresolvedUsing:
2445 case Type::TypeOfExpr:
2446 case Type::TypeOf:
2447 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002448 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002449 case Type::DependentName:
2450 case Type::InjectedClassName:
2451 case Type::TemplateSpecialization:
2452 case Type::DependentTemplateSpecialization:
2453 case Type::TemplateTypeParm:
2454 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002455 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002456 case Type::PackExpansion:
2457 llvm_unreachable("type should never be variably-modified");
2458
2459 // These types can be variably-modified but should never need to
2460 // further decay.
2461 case Type::FunctionNoProto:
2462 case Type::FunctionProto:
2463 case Type::BlockPointer:
2464 case Type::MemberPointer:
2465 return type;
2466
2467 // These types can be variably-modified. All these modifications
2468 // preserve structure except as noted by comments.
2469 // TODO: if we ever care about optimizing VLAs, there are no-op
2470 // optimizations available here.
2471 case Type::Pointer:
2472 result = getPointerType(getVariableArrayDecayedType(
2473 cast<PointerType>(ty)->getPointeeType()));
2474 break;
2475
2476 case Type::LValueReference: {
2477 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2478 result = getLValueReferenceType(
2479 getVariableArrayDecayedType(lv->getPointeeType()),
2480 lv->isSpelledAsLValue());
2481 break;
2482 }
2483
2484 case Type::RValueReference: {
2485 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2486 result = getRValueReferenceType(
2487 getVariableArrayDecayedType(lv->getPointeeType()));
2488 break;
2489 }
2490
Eli Friedman0dfb8892011-10-06 23:00:33 +00002491 case Type::Atomic: {
2492 const AtomicType *at = cast<AtomicType>(ty);
2493 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2494 break;
2495 }
2496
John McCall06549462011-01-18 08:40:38 +00002497 case Type::ConstantArray: {
2498 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2499 result = getConstantArrayType(
2500 getVariableArrayDecayedType(cat->getElementType()),
2501 cat->getSize(),
2502 cat->getSizeModifier(),
2503 cat->getIndexTypeCVRQualifiers());
2504 break;
2505 }
2506
2507 case Type::DependentSizedArray: {
2508 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2509 result = getDependentSizedArrayType(
2510 getVariableArrayDecayedType(dat->getElementType()),
2511 dat->getSizeExpr(),
2512 dat->getSizeModifier(),
2513 dat->getIndexTypeCVRQualifiers(),
2514 dat->getBracketsRange());
2515 break;
2516 }
2517
2518 // Turn incomplete types into [*] types.
2519 case Type::IncompleteArray: {
2520 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2521 result = getVariableArrayType(
2522 getVariableArrayDecayedType(iat->getElementType()),
2523 /*size*/ 0,
2524 ArrayType::Normal,
2525 iat->getIndexTypeCVRQualifiers(),
2526 SourceRange());
2527 break;
2528 }
2529
2530 // Turn VLA types into [*] types.
2531 case Type::VariableArray: {
2532 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2533 result = getVariableArrayType(
2534 getVariableArrayDecayedType(vat->getElementType()),
2535 /*size*/ 0,
2536 ArrayType::Star,
2537 vat->getIndexTypeCVRQualifiers(),
2538 vat->getBracketsRange());
2539 break;
2540 }
2541 }
2542
2543 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002544 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002545}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002546
Steve Naroffcadebd02007-08-30 18:14:25 +00002547/// getVariableArrayType - Returns a non-unique reference to the type for a
2548/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002549QualType ASTContext::getVariableArrayType(QualType EltTy,
2550 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002551 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002552 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002553 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002554 // Since we don't unique expressions, it isn't possible to unique VLA's
2555 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002556 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002557
John McCall33ddac02011-01-19 10:06:00 +00002558 // Be sure to pull qualifiers off the element type.
2559 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2560 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002561 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002562 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002563 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002564 }
2565
John McCall90d1c2d2009-09-24 23:30:46 +00002566 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002567 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002568
2569 VariableArrayTypes.push_back(New);
2570 Types.push_back(New);
2571 return QualType(New, 0);
2572}
2573
Douglas Gregor4619e432008-12-05 23:32:09 +00002574/// getDependentSizedArrayType - Returns a non-unique reference to
2575/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002576/// type.
John McCall33ddac02011-01-19 10:06:00 +00002577QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2578 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002579 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002580 unsigned elementTypeQuals,
2581 SourceRange brackets) const {
2582 assert((!numElements || numElements->isTypeDependent() ||
2583 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002584 "Size must be type- or value-dependent!");
2585
John McCall33ddac02011-01-19 10:06:00 +00002586 // Dependently-sized array types that do not have a specified number
2587 // of elements will have their sizes deduced from a dependent
2588 // initializer. We do no canonicalization here at all, which is okay
2589 // because they can't be used in most locations.
2590 if (!numElements) {
2591 DependentSizedArrayType *newType
2592 = new (*this, TypeAlignment)
2593 DependentSizedArrayType(*this, elementType, QualType(),
2594 numElements, ASM, elementTypeQuals,
2595 brackets);
2596 Types.push_back(newType);
2597 return QualType(newType, 0);
2598 }
2599
2600 // Otherwise, we actually build a new type every time, but we
2601 // also build a canonical type.
2602
2603 SplitQualType canonElementType = getCanonicalType(elementType).split();
2604
2605 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002606 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002607 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002608 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002609 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002610
John McCall33ddac02011-01-19 10:06:00 +00002611 // Look for an existing type with these properties.
2612 DependentSizedArrayType *canonTy =
2613 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002614
John McCall33ddac02011-01-19 10:06:00 +00002615 // If we don't have one, build one.
2616 if (!canonTy) {
2617 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002618 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002619 QualType(), numElements, ASM, elementTypeQuals,
2620 brackets);
2621 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2622 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002623 }
2624
John McCall33ddac02011-01-19 10:06:00 +00002625 // Apply qualifiers from the element type to the array.
2626 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002627 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002628
John McCall33ddac02011-01-19 10:06:00 +00002629 // If we didn't need extra canonicalization for the element type,
2630 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002631 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002632 return canon;
2633
2634 // Otherwise, we need to build a type which follows the spelling
2635 // of the element type.
2636 DependentSizedArrayType *sugaredType
2637 = new (*this, TypeAlignment)
2638 DependentSizedArrayType(*this, elementType, canon, numElements,
2639 ASM, elementTypeQuals, brackets);
2640 Types.push_back(sugaredType);
2641 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002642}
2643
John McCall33ddac02011-01-19 10:06:00 +00002644QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002645 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002646 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002647 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002648 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002649
John McCall33ddac02011-01-19 10:06:00 +00002650 void *insertPos = 0;
2651 if (IncompleteArrayType *iat =
2652 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2653 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002654
2655 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002656 // either, so fill in the canonical type field. We also have to pull
2657 // qualifiers off the element type.
2658 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002659
John McCall33ddac02011-01-19 10:06:00 +00002660 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2661 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002662 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002663 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002664 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002665
2666 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002667 IncompleteArrayType *existing =
2668 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2669 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002670 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002671
John McCall33ddac02011-01-19 10:06:00 +00002672 IncompleteArrayType *newType = new (*this, TypeAlignment)
2673 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002674
John McCall33ddac02011-01-19 10:06:00 +00002675 IncompleteArrayTypes.InsertNode(newType, insertPos);
2676 Types.push_back(newType);
2677 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002678}
2679
Steve Naroff91fcddb2007-07-18 18:00:27 +00002680/// getVectorType - Return the unique reference to a vector type of
2681/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002682QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002683 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002684 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002685
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002686 // Check if we've already instantiated a vector of this type.
2687 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002688 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002689
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002690 void *InsertPos = 0;
2691 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2692 return QualType(VTP, 0);
2693
2694 // If the element type isn't canonical, this won't be a canonical type either,
2695 // so fill in the canonical type field.
2696 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002697 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002698 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002699
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002700 // Get the new insert position for the node we care about.
2701 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002702 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002703 }
John McCall90d1c2d2009-09-24 23:30:46 +00002704 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002705 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002706 VectorTypes.InsertNode(New, InsertPos);
2707 Types.push_back(New);
2708 return QualType(New, 0);
2709}
2710
Nate Begemance4d7fc2008-04-18 23:10:10 +00002711/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002712/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002713QualType
2714ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002715 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002716
Steve Naroff91fcddb2007-07-18 18:00:27 +00002717 // Check if we've already instantiated a vector of this type.
2718 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002719 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002720 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002721 void *InsertPos = 0;
2722 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2723 return QualType(VTP, 0);
2724
2725 // If the element type isn't canonical, this won't be a canonical type either,
2726 // so fill in the canonical type field.
2727 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002728 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002729 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002730
Steve Naroff91fcddb2007-07-18 18:00:27 +00002731 // Get the new insert position for the node we care about.
2732 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002733 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002734 }
John McCall90d1c2d2009-09-24 23:30:46 +00002735 ExtVectorType *New = new (*this, TypeAlignment)
2736 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002737 VectorTypes.InsertNode(New, InsertPos);
2738 Types.push_back(New);
2739 return QualType(New, 0);
2740}
2741
Jay Foad39c79802011-01-12 09:06:06 +00002742QualType
2743ASTContext::getDependentSizedExtVectorType(QualType vecType,
2744 Expr *SizeExpr,
2745 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002746 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002747 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002748 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002749
Douglas Gregor352169a2009-07-31 03:54:25 +00002750 void *InsertPos = 0;
2751 DependentSizedExtVectorType *Canon
2752 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2753 DependentSizedExtVectorType *New;
2754 if (Canon) {
2755 // We already have a canonical version of this array type; use it as
2756 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002757 New = new (*this, TypeAlignment)
2758 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2759 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002760 } else {
2761 QualType CanonVecTy = getCanonicalType(vecType);
2762 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002763 New = new (*this, TypeAlignment)
2764 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2765 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002766
2767 DependentSizedExtVectorType *CanonCheck
2768 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2769 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2770 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002771 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2772 } else {
2773 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2774 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002775 New = new (*this, TypeAlignment)
2776 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002777 }
2778 }
Mike Stump11289f42009-09-09 15:08:12 +00002779
Douglas Gregor758a8692009-06-17 21:51:59 +00002780 Types.push_back(New);
2781 return QualType(New, 0);
2782}
2783
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002784/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002785///
Jay Foad39c79802011-01-12 09:06:06 +00002786QualType
2787ASTContext::getFunctionNoProtoType(QualType ResultTy,
2788 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002789 const CallingConv CallConv = Info.getCC();
2790
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002791 // Unique functions, to guarantee there is only one function of a particular
2792 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002793 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002794 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002795
Chris Lattner47955de2007-01-27 08:37:20 +00002796 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002797 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002798 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002799 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002800
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002801 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002802 if (!ResultTy.isCanonical()) {
2803 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002804
Chris Lattner47955de2007-01-27 08:37:20 +00002805 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002806 FunctionNoProtoType *NewIP =
2807 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002808 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002809 }
Mike Stump11289f42009-09-09 15:08:12 +00002810
Roman Divacky65b88cd2011-03-01 17:40:53 +00002811 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002812 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002813 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002814 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002815 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002816 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002817}
2818
Douglas Gregorcd780372013-01-17 23:36:45 +00002819/// \brief Determine whether \p T is canonical as the result type of a function.
2820static bool isCanonicalResultType(QualType T) {
2821 return T.isCanonical() &&
2822 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2823 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2824}
2825
Jay Foad39c79802011-01-12 09:06:06 +00002826QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002827ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002828 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002829 size_t NumArgs = ArgArray.size();
2830
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002831 // Unique functions, to guarantee there is only one function of a particular
2832 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002833 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002834 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2835 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002836
2837 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002838 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002839 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002840 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002841
2842 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002843 bool isCanonical =
Douglas Gregorcd780372013-01-17 23:36:45 +00002844 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002845 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002846 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002847 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002848 isCanonical = false;
2849
2850 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002851 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002852 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002853 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002854 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002855 CanonicalArgs.reserve(NumArgs);
2856 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002857 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002858
John McCalldb40c7f2010-12-14 08:05:40 +00002859 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002860 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002861 CanonicalEPI.ExceptionSpecType = EST_None;
2862 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002863
Douglas Gregorcd780372013-01-17 23:36:45 +00002864 // Result types do not have ARC lifetime qualifiers.
2865 QualType CanResultTy = getCanonicalType(ResultTy);
2866 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2867 Qualifiers Qs = CanResultTy.getQualifiers();
2868 Qs.removeObjCLifetime();
2869 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2870 }
2871
Jordan Rose5c382722013-03-08 21:51:21 +00002872 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002873
Chris Lattnerfd4de792007-01-27 01:15:32 +00002874 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002875 FunctionProtoType *NewIP =
2876 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002877 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002878 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002879
John McCall31168b02011-06-15 23:02:42 +00002880 // FunctionProtoType objects are allocated with extra bytes after
2881 // them for three variable size arrays at the end:
2882 // - parameter types
2883 // - exception types
2884 // - consumed-arguments flags
2885 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002886 // expression, or information used to resolve the exception
2887 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002888 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002889 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002890 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002891 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002892 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002893 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002894 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002895 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002896 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2897 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002898 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002899 if (EPI.ConsumedParameters)
John McCall31168b02011-06-15 23:02:42 +00002900 Size += NumArgs * sizeof(bool);
2901
John McCalldb40c7f2010-12-14 08:05:40 +00002902 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002903 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00002904 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002905 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002906 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002907 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002908}
Chris Lattneref51c202006-11-10 07:17:23 +00002909
John McCalle78aac42010-03-10 03:28:59 +00002910#ifndef NDEBUG
2911static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2912 if (!isa<CXXRecordDecl>(D)) return false;
2913 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2914 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2915 return true;
2916 if (RD->getDescribedClassTemplate() &&
2917 !isa<ClassTemplateSpecializationDecl>(RD))
2918 return true;
2919 return false;
2920}
2921#endif
2922
2923/// getInjectedClassNameType - Return the unique reference to the
2924/// injected class name type for the specified templated declaration.
2925QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002926 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002927 assert(NeedsInjectedClassNameType(Decl));
2928 if (Decl->TypeForDecl) {
2929 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002930 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002931 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2932 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2933 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2934 } else {
John McCall424cec92011-01-19 06:33:43 +00002935 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002936 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002937 Decl->TypeForDecl = newType;
2938 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002939 }
2940 return QualType(Decl->TypeForDecl, 0);
2941}
2942
Douglas Gregor83a586e2008-04-13 21:07:44 +00002943/// getTypeDeclType - Return the unique reference to the type for the
2944/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002945QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002946 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002947 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002948
Richard Smithdda56e42011-04-15 14:24:37 +00002949 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002950 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002951
John McCall96f0b5f2010-03-10 06:48:02 +00002952 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2953 "Template type parameter types are always available.");
2954
John McCall81e38502010-02-16 03:57:14 +00002955 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00002956 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00002957 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002958 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002959 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00002960 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002961 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002962 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002963 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002964 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2965 Decl->TypeForDecl = newType;
2966 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002967 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002968 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002969
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002970 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002971}
2972
Chris Lattner32d920b2007-01-26 02:01:53 +00002973/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002974/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002975QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002976ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2977 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002978 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002979
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002980 if (Canonical.isNull())
2981 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002982 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002983 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002984 Decl->TypeForDecl = newType;
2985 Types.push_back(newType);
2986 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002987}
2988
Jay Foad39c79802011-01-12 09:06:06 +00002989QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002990 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2991
Douglas Gregorec9fd132012-01-14 16:38:05 +00002992 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002993 if (PrevDecl->TypeForDecl)
2994 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2995
John McCall424cec92011-01-19 06:33:43 +00002996 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2997 Decl->TypeForDecl = newType;
2998 Types.push_back(newType);
2999 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003000}
3001
Jay Foad39c79802011-01-12 09:06:06 +00003002QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003003 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3004
Douglas Gregorec9fd132012-01-14 16:38:05 +00003005 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003006 if (PrevDecl->TypeForDecl)
3007 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3008
John McCall424cec92011-01-19 06:33:43 +00003009 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3010 Decl->TypeForDecl = newType;
3011 Types.push_back(newType);
3012 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003013}
3014
John McCall81904512011-01-06 01:58:22 +00003015QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3016 QualType modifiedType,
3017 QualType equivalentType) {
3018 llvm::FoldingSetNodeID id;
3019 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3020
3021 void *insertPos = 0;
3022 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3023 if (type) return QualType(type, 0);
3024
3025 QualType canon = getCanonicalType(equivalentType);
3026 type = new (*this, TypeAlignment)
3027 AttributedType(canon, attrKind, modifiedType, equivalentType);
3028
3029 Types.push_back(type);
3030 AttributedTypes.InsertNode(type, insertPos);
3031
3032 return QualType(type, 0);
3033}
3034
3035
John McCallcebee162009-10-18 09:09:24 +00003036/// \brief Retrieve a substitution-result type.
3037QualType
3038ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003039 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003040 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003041 && "replacement types must always be canonical");
3042
3043 llvm::FoldingSetNodeID ID;
3044 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3045 void *InsertPos = 0;
3046 SubstTemplateTypeParmType *SubstParm
3047 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3048
3049 if (!SubstParm) {
3050 SubstParm = new (*this, TypeAlignment)
3051 SubstTemplateTypeParmType(Parm, Replacement);
3052 Types.push_back(SubstParm);
3053 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3054 }
3055
3056 return QualType(SubstParm, 0);
3057}
3058
Douglas Gregorada4b792011-01-14 02:55:32 +00003059/// \brief Retrieve a
3060QualType ASTContext::getSubstTemplateTypeParmPackType(
3061 const TemplateTypeParmType *Parm,
3062 const TemplateArgument &ArgPack) {
3063#ifndef NDEBUG
3064 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
3065 PEnd = ArgPack.pack_end();
3066 P != PEnd; ++P) {
3067 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3068 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
3069 }
3070#endif
3071
3072 llvm::FoldingSetNodeID ID;
3073 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3074 void *InsertPos = 0;
3075 if (SubstTemplateTypeParmPackType *SubstParm
3076 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3077 return QualType(SubstParm, 0);
3078
3079 QualType Canon;
3080 if (!Parm->isCanonicalUnqualified()) {
3081 Canon = getCanonicalType(QualType(Parm, 0));
3082 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3083 ArgPack);
3084 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3085 }
3086
3087 SubstTemplateTypeParmPackType *SubstParm
3088 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3089 ArgPack);
3090 Types.push_back(SubstParm);
3091 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3092 return QualType(SubstParm, 0);
3093}
3094
Douglas Gregoreff93e02009-02-05 23:33:38 +00003095/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003096/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003097/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003098QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003099 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003100 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003101 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003102 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003103 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003104 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003105 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3106
3107 if (TypeParm)
3108 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003109
Chandler Carruth08836322011-05-01 00:51:33 +00003110 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003111 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003112 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003113
3114 TemplateTypeParmType *TypeCheck
3115 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3116 assert(!TypeCheck && "Template type parameter canonical type broken");
3117 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003118 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003119 TypeParm = new (*this, TypeAlignment)
3120 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003121
3122 Types.push_back(TypeParm);
3123 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3124
3125 return QualType(TypeParm, 0);
3126}
3127
John McCalle78aac42010-03-10 03:28:59 +00003128TypeSourceInfo *
3129ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3130 SourceLocation NameLoc,
3131 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003132 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003133 assert(!Name.getAsDependentTemplateName() &&
3134 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003135 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003136
3137 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003138 TemplateSpecializationTypeLoc TL =
3139 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003140 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003141 TL.setTemplateNameLoc(NameLoc);
3142 TL.setLAngleLoc(Args.getLAngleLoc());
3143 TL.setRAngleLoc(Args.getRAngleLoc());
3144 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3145 TL.setArgLocInfo(i, Args[i].getLocInfo());
3146 return DI;
3147}
3148
Mike Stump11289f42009-09-09 15:08:12 +00003149QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003150ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003151 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003152 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003153 assert(!Template.getAsDependentTemplateName() &&
3154 "No dependent template names here!");
3155
John McCall6b51f282009-11-23 01:53:49 +00003156 unsigned NumArgs = Args.size();
3157
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003158 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003159 ArgVec.reserve(NumArgs);
3160 for (unsigned i = 0; i != NumArgs; ++i)
3161 ArgVec.push_back(Args[i].getArgument());
3162
John McCall2408e322010-04-27 00:57:59 +00003163 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003164 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003165}
3166
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003167#ifndef NDEBUG
3168static bool hasAnyPackExpansions(const TemplateArgument *Args,
3169 unsigned NumArgs) {
3170 for (unsigned I = 0; I != NumArgs; ++I)
3171 if (Args[I].isPackExpansion())
3172 return true;
3173
3174 return true;
3175}
3176#endif
3177
John McCall0ad16662009-10-29 08:12:44 +00003178QualType
3179ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003180 const TemplateArgument *Args,
3181 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003182 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003183 assert(!Template.getAsDependentTemplateName() &&
3184 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003185 // Look through qualified template names.
3186 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3187 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003188
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003189 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003190 Template.getAsTemplateDecl() &&
3191 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003192 QualType CanonType;
3193 if (!Underlying.isNull())
3194 CanonType = getCanonicalType(Underlying);
3195 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003196 // We can get here with an alias template when the specialization contains
3197 // a pack expansion that does not match up with a parameter pack.
3198 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3199 "Caller must compute aliased type");
3200 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003201 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3202 NumArgs);
3203 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003204
Douglas Gregora8e02e72009-07-28 23:00:59 +00003205 // Allocate the (non-canonical) template specialization type, but don't
3206 // try to unique it: these types typically have location information that
3207 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003208 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3209 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003210 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003211 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003212 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003213 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3214 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003215
Douglas Gregor8bf42052009-02-09 18:46:07 +00003216 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003217 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003218}
3219
Mike Stump11289f42009-09-09 15:08:12 +00003220QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003221ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3222 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003223 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003224 assert(!Template.getAsDependentTemplateName() &&
3225 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003226
Douglas Gregore29139c2011-03-03 17:04:51 +00003227 // Look through qualified template names.
3228 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3229 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003230
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003231 // Build the canonical template specialization type.
3232 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003233 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003234 CanonArgs.reserve(NumArgs);
3235 for (unsigned I = 0; I != NumArgs; ++I)
3236 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3237
3238 // Determine whether this canonical template specialization type already
3239 // exists.
3240 llvm::FoldingSetNodeID ID;
3241 TemplateSpecializationType::Profile(ID, CanonTemplate,
3242 CanonArgs.data(), NumArgs, *this);
3243
3244 void *InsertPos = 0;
3245 TemplateSpecializationType *Spec
3246 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3247
3248 if (!Spec) {
3249 // Allocate a new canonical template specialization type.
3250 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3251 sizeof(TemplateArgument) * NumArgs),
3252 TypeAlignment);
3253 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3254 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003255 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003256 Types.push_back(Spec);
3257 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3258 }
3259
3260 assert(Spec->isDependentType() &&
3261 "Non-dependent template-id type must have a canonical type");
3262 return QualType(Spec, 0);
3263}
3264
3265QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003266ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3267 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003268 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003269 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003270 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003271
3272 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003273 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003274 if (T)
3275 return QualType(T, 0);
3276
Douglas Gregorc42075a2010-02-04 18:10:26 +00003277 QualType Canon = NamedType;
3278 if (!Canon.isCanonical()) {
3279 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003280 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3281 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003282 (void)CheckT;
3283 }
3284
Abramo Bagnara6150c882010-05-11 21:36:43 +00003285 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003286 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003287 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003288 return QualType(T, 0);
3289}
3290
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003291QualType
Jay Foad39c79802011-01-12 09:06:06 +00003292ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003293 llvm::FoldingSetNodeID ID;
3294 ParenType::Profile(ID, InnerType);
3295
3296 void *InsertPos = 0;
3297 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3298 if (T)
3299 return QualType(T, 0);
3300
3301 QualType Canon = InnerType;
3302 if (!Canon.isCanonical()) {
3303 Canon = getCanonicalType(InnerType);
3304 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3305 assert(!CheckT && "Paren canonical type broken");
3306 (void)CheckT;
3307 }
3308
3309 T = new (*this) ParenType(InnerType, Canon);
3310 Types.push_back(T);
3311 ParenTypes.InsertNode(T, InsertPos);
3312 return QualType(T, 0);
3313}
3314
Douglas Gregor02085352010-03-31 20:19:30 +00003315QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3316 NestedNameSpecifier *NNS,
3317 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003318 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003319 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3320
3321 if (Canon.isNull()) {
3322 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003323 ElaboratedTypeKeyword CanonKeyword = Keyword;
3324 if (Keyword == ETK_None)
3325 CanonKeyword = ETK_Typename;
3326
3327 if (CanonNNS != NNS || CanonKeyword != Keyword)
3328 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003329 }
3330
3331 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003332 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003333
3334 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003335 DependentNameType *T
3336 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003337 if (T)
3338 return QualType(T, 0);
3339
Douglas Gregor02085352010-03-31 20:19:30 +00003340 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003341 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003342 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003343 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003344}
3345
Mike Stump11289f42009-09-09 15:08:12 +00003346QualType
John McCallc392f372010-06-11 00:33:02 +00003347ASTContext::getDependentTemplateSpecializationType(
3348 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003349 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003350 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003351 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003352 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003353 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003354 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3355 ArgCopy.push_back(Args[I].getArgument());
3356 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3357 ArgCopy.size(),
3358 ArgCopy.data());
3359}
3360
3361QualType
3362ASTContext::getDependentTemplateSpecializationType(
3363 ElaboratedTypeKeyword Keyword,
3364 NestedNameSpecifier *NNS,
3365 const IdentifierInfo *Name,
3366 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003367 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003368 assert((!NNS || NNS->isDependent()) &&
3369 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003370
Douglas Gregorc42075a2010-02-04 18:10:26 +00003371 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003372 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3373 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003374
3375 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00003376 DependentTemplateSpecializationType *T
3377 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003378 if (T)
3379 return QualType(T, 0);
3380
John McCallc392f372010-06-11 00:33:02 +00003381 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003382
John McCallc392f372010-06-11 00:33:02 +00003383 ElaboratedTypeKeyword CanonKeyword = Keyword;
3384 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3385
3386 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003387 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003388 for (unsigned I = 0; I != NumArgs; ++I) {
3389 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3390 if (!CanonArgs[I].structurallyEquals(Args[I]))
3391 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003392 }
3393
John McCallc392f372010-06-11 00:33:02 +00003394 QualType Canon;
3395 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3396 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3397 Name, NumArgs,
3398 CanonArgs.data());
3399
3400 // Find the insert position again.
3401 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3402 }
3403
3404 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3405 sizeof(TemplateArgument) * NumArgs),
3406 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003407 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003408 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003409 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003410 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003411 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003412}
3413
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003414QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003415 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003416 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003417 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003418
3419 assert(Pattern->containsUnexpandedParameterPack() &&
3420 "Pack expansions must expand one or more parameter packs");
3421 void *InsertPos = 0;
3422 PackExpansionType *T
3423 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3424 if (T)
3425 return QualType(T, 0);
3426
3427 QualType Canon;
3428 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003429 Canon = getCanonicalType(Pattern);
3430 // The canonical type might not contain an unexpanded parameter pack, if it
3431 // contains an alias template specialization which ignores one of its
3432 // parameters.
3433 if (Canon->containsUnexpandedParameterPack()) {
3434 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003435
Richard Smith68eea502012-07-16 00:20:35 +00003436 // Find the insert position again, in case we inserted an element into
3437 // PackExpansionTypes and invalidated our insert position.
3438 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3439 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003440 }
3441
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003442 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003443 Types.push_back(T);
3444 PackExpansionTypes.InsertNode(T, InsertPos);
3445 return QualType(T, 0);
3446}
3447
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003448/// CmpProtocolNames - Comparison predicate for sorting protocols
3449/// alphabetically.
3450static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3451 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003452 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003453}
3454
John McCall8b07ec22010-05-15 11:32:37 +00003455static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003456 unsigned NumProtocols) {
3457 if (NumProtocols == 0) return true;
3458
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003459 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3460 return false;
3461
John McCallfc93cf92009-10-22 22:37:11 +00003462 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003463 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3464 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003465 return false;
3466 return true;
3467}
3468
3469static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003470 unsigned &NumProtocols) {
3471 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003472
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003473 // Sort protocols, keyed by name.
3474 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3475
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003476 // Canonicalize.
3477 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3478 Protocols[I] = Protocols[I]->getCanonicalDecl();
3479
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003480 // Remove duplicates.
3481 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3482 NumProtocols = ProtocolsEnd-Protocols;
3483}
3484
John McCall8b07ec22010-05-15 11:32:37 +00003485QualType ASTContext::getObjCObjectType(QualType BaseType,
3486 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003487 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003488 // If the base type is an interface and there aren't any protocols
3489 // to add, then the interface type will do just fine.
3490 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3491 return BaseType;
3492
3493 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003494 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003495 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003496 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003497 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3498 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003499
John McCall8b07ec22010-05-15 11:32:37 +00003500 // Build the canonical type, which has the canonical base type and
3501 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003502 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003503 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3504 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3505 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003506 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003507 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003508 unsigned UniqueCount = NumProtocols;
3509
John McCallfc93cf92009-10-22 22:37:11 +00003510 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003511 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3512 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003513 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003514 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3515 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003516 }
3517
3518 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003519 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3520 }
3521
3522 unsigned Size = sizeof(ObjCObjectTypeImpl);
3523 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3524 void *Mem = Allocate(Size, TypeAlignment);
3525 ObjCObjectTypeImpl *T =
3526 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3527
3528 Types.push_back(T);
3529 ObjCObjectTypes.InsertNode(T, InsertPos);
3530 return QualType(T, 0);
3531}
3532
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003533/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3534/// protocol list adopt all protocols in QT's qualified-id protocol
3535/// list.
3536bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3537 ObjCInterfaceDecl *IC) {
3538 if (!QT->isObjCQualifiedIdType())
3539 return false;
3540
3541 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3542 // If both the right and left sides have qualifiers.
3543 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3544 E = OPT->qual_end(); I != E; ++I) {
3545 ObjCProtocolDecl *Proto = *I;
3546 if (!IC->ClassImplementsProtocol(Proto, false))
3547 return false;
3548 }
3549 return true;
3550 }
3551 return false;
3552}
3553
3554/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3555/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3556/// of protocols.
3557bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3558 ObjCInterfaceDecl *IDecl) {
3559 if (!QT->isObjCQualifiedIdType())
3560 return false;
3561 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3562 if (!OPT)
3563 return false;
3564 if (!IDecl->hasDefinition())
3565 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003566 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3567 CollectInheritedProtocols(IDecl, InheritedProtocols);
3568 if (InheritedProtocols.empty())
3569 return false;
3570
3571 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator PI =
3572 InheritedProtocols.begin(),
3573 E = InheritedProtocols.end(); PI != E; ++PI) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003574 // If both the right and left sides have qualifiers.
3575 bool Adopts = false;
3576 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3577 E = OPT->qual_end(); I != E; ++I) {
3578 ObjCProtocolDecl *Proto = *I;
3579 // return 'true' if '*PI' is in the inheritance hierarchy of Proto
3580 if ((Adopts = ProtocolCompatibleWithProtocol(*PI, Proto)))
3581 break;
3582 }
3583 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003584 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003585 }
3586 return true;
3587}
3588
John McCall8b07ec22010-05-15 11:32:37 +00003589/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3590/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003591QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003592 llvm::FoldingSetNodeID ID;
3593 ObjCObjectPointerType::Profile(ID, ObjectT);
3594
3595 void *InsertPos = 0;
3596 if (ObjCObjectPointerType *QT =
3597 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3598 return QualType(QT, 0);
3599
3600 // Find the canonical object type.
3601 QualType Canonical;
3602 if (!ObjectT.isCanonical()) {
3603 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3604
3605 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003606 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3607 }
3608
Douglas Gregorf85bee62010-02-08 22:59:26 +00003609 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003610 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3611 ObjCObjectPointerType *QType =
3612 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003613
Steve Narofffb4330f2009-06-17 22:40:22 +00003614 Types.push_back(QType);
3615 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003616 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003617}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003618
Douglas Gregor1c283312010-08-11 12:19:30 +00003619/// getObjCInterfaceType - Return the unique reference to the type for the
3620/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003621QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3622 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003623 if (Decl->TypeForDecl)
3624 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003625
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003626 if (PrevDecl) {
3627 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3628 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3629 return QualType(PrevDecl->TypeForDecl, 0);
3630 }
3631
Douglas Gregor7671e532011-12-16 16:34:57 +00003632 // Prefer the definition, if there is one.
3633 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3634 Decl = Def;
3635
Douglas Gregor1c283312010-08-11 12:19:30 +00003636 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3637 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3638 Decl->TypeForDecl = T;
3639 Types.push_back(T);
3640 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003641}
3642
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003643/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3644/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003645/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003646/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003647/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003648QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003649 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003650 if (tofExpr->isTypeDependent()) {
3651 llvm::FoldingSetNodeID ID;
3652 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003653
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003654 void *InsertPos = 0;
3655 DependentTypeOfExprType *Canon
3656 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3657 if (Canon) {
3658 // We already have a "canonical" version of an identical, dependent
3659 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003660 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003661 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003662 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003663 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003664 Canon
3665 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003666 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3667 toe = Canon;
3668 }
3669 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003670 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003671 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003672 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003673 Types.push_back(toe);
3674 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003675}
3676
Steve Naroffa773cd52007-08-01 18:02:17 +00003677/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3678/// TypeOfType AST's. The only motivation to unique these nodes would be
3679/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003680/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003681/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003682QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003683 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003684 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003685 Types.push_back(tot);
3686 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003687}
3688
Anders Carlssonad6bd352009-06-24 21:24:56 +00003689
Anders Carlsson81df7b82009-06-24 19:06:50 +00003690/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3691/// DecltypeType AST's. The only motivation to unique these nodes would be
3692/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003693/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003694/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003695QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003696 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003697
3698 // C++0x [temp.type]p2:
3699 // If an expression e involves a template parameter, decltype(e) denotes a
3700 // unique dependent type. Two such decltype-specifiers refer to the same
3701 // type only if their expressions are equivalent (14.5.6.1).
3702 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003703 llvm::FoldingSetNodeID ID;
3704 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003705
Douglas Gregora21f6c32009-07-30 23:36:40 +00003706 void *InsertPos = 0;
3707 DependentDecltypeType *Canon
3708 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3709 if (Canon) {
3710 // We already have a "canonical" version of an equivalent, dependent
3711 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003712 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003713 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003714 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003715 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003716 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003717 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3718 dt = Canon;
3719 }
3720 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003721 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3722 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003723 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003724 Types.push_back(dt);
3725 return QualType(dt, 0);
3726}
3727
Alexis Hunte852b102011-05-24 22:41:36 +00003728/// getUnaryTransformationType - We don't unique these, since the memory
3729/// savings are minimal and these are rare.
3730QualType ASTContext::getUnaryTransformType(QualType BaseType,
3731 QualType UnderlyingType,
3732 UnaryTransformType::UTTKind Kind)
3733 const {
3734 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003735 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3736 Kind,
3737 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003738 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003739 Types.push_back(Ty);
3740 return QualType(Ty, 0);
3741}
3742
Richard Smith2a7d4812013-05-04 07:00:32 +00003743/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3744/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3745/// canonical deduced-but-dependent 'auto' type.
3746QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003747 bool IsDependent) const {
3748 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003749 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003750
Richard Smith2a7d4812013-05-04 07:00:32 +00003751 // Look in the folding set for an existing type.
Richard Smithb2bc2e62011-02-21 20:05:19 +00003752 void *InsertPos = 0;
Richard Smith2a7d4812013-05-04 07:00:32 +00003753 llvm::FoldingSetNodeID ID;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003754 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003755 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3756 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003757
Richard Smith74aeef52013-04-26 16:15:35 +00003758 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003759 IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003760 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003761 Types.push_back(AT);
3762 if (InsertPos)
3763 AutoTypes.InsertNode(AT, InsertPos);
3764 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003765}
3766
Eli Friedman0dfb8892011-10-06 23:00:33 +00003767/// getAtomicType - Return the uniqued reference to the atomic type for
3768/// the given value type.
3769QualType ASTContext::getAtomicType(QualType T) const {
3770 // Unique pointers, to guarantee there is only one pointer of a particular
3771 // structure.
3772 llvm::FoldingSetNodeID ID;
3773 AtomicType::Profile(ID, T);
3774
3775 void *InsertPos = 0;
3776 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3777 return QualType(AT, 0);
3778
3779 // If the atomic value type isn't canonical, this won't be a canonical type
3780 // either, so fill in the canonical type field.
3781 QualType Canonical;
3782 if (!T.isCanonical()) {
3783 Canonical = getAtomicType(getCanonicalType(T));
3784
3785 // Get the new insert position for the node we care about.
3786 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3787 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3788 }
3789 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3790 Types.push_back(New);
3791 AtomicTypes.InsertNode(New, InsertPos);
3792 return QualType(New, 0);
3793}
3794
Richard Smith02e85f32011-04-14 22:09:26 +00003795/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3796QualType ASTContext::getAutoDeductType() const {
3797 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00003798 AutoDeductTy = QualType(
3799 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003800 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00003801 0);
Richard Smith02e85f32011-04-14 22:09:26 +00003802 return AutoDeductTy;
3803}
3804
3805/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3806QualType ASTContext::getAutoRRefDeductType() const {
3807 if (AutoRRefDeductTy.isNull())
3808 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3809 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3810 return AutoRRefDeductTy;
3811}
3812
Chris Lattnerfb072462007-01-23 05:45:31 +00003813/// getTagDeclType - Return the unique reference to the type for the
3814/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003815QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003816 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003817 // FIXME: What is the design on getTagDeclType when it requires casting
3818 // away const? mutable?
3819 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003820}
3821
Mike Stump11289f42009-09-09 15:08:12 +00003822/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3823/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3824/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003825CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003826 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003827}
Chris Lattnerfb072462007-01-23 05:45:31 +00003828
Hans Wennborg27541db2011-10-27 08:29:09 +00003829/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3830CanQualType ASTContext::getIntMaxType() const {
3831 return getFromTargetType(Target->getIntMaxType());
3832}
3833
3834/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3835CanQualType ASTContext::getUIntMaxType() const {
3836 return getFromTargetType(Target->getUIntMaxType());
3837}
3838
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003839/// getSignedWCharType - Return the type of "signed wchar_t".
3840/// Used when in C++, as a GCC extension.
3841QualType ASTContext::getSignedWCharType() const {
3842 // FIXME: derive from "Target" ?
3843 return WCharTy;
3844}
3845
3846/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3847/// Used when in C++, as a GCC extension.
3848QualType ASTContext::getUnsignedWCharType() const {
3849 // FIXME: derive from "Target" ?
3850 return UnsignedIntTy;
3851}
3852
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00003853QualType ASTContext::getIntPtrType() const {
3854 return getFromTargetType(Target->getIntPtrType());
3855}
3856
3857QualType ASTContext::getUIntPtrType() const {
3858 return getCorrespondingUnsignedType(getIntPtrType());
3859}
3860
Hans Wennborg27541db2011-10-27 08:29:09 +00003861/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003862/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3863QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003864 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003865}
3866
Eli Friedman4e91899e2012-11-27 02:58:24 +00003867/// \brief Return the unique type for "pid_t" defined in
3868/// <sys/types.h>. We need this to compute the correct type for vfork().
3869QualType ASTContext::getProcessIDType() const {
3870 return getFromTargetType(Target->getProcessIDType());
3871}
3872
Chris Lattnera21ad802008-04-02 05:18:44 +00003873//===----------------------------------------------------------------------===//
3874// Type Operators
3875//===----------------------------------------------------------------------===//
3876
Jay Foad39c79802011-01-12 09:06:06 +00003877CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003878 // Push qualifiers into arrays, and then discard any remaining
3879 // qualifiers.
3880 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003881 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003882 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003883 QualType Result;
3884 if (isa<ArrayType>(Ty)) {
3885 Result = getArrayDecayedType(QualType(Ty,0));
3886 } else if (isa<FunctionType>(Ty)) {
3887 Result = getPointerType(QualType(Ty, 0));
3888 } else {
3889 Result = QualType(Ty, 0);
3890 }
3891
3892 return CanQualType::CreateUnsafe(Result);
3893}
3894
John McCall6c9dd522011-01-18 07:41:22 +00003895QualType ASTContext::getUnqualifiedArrayType(QualType type,
3896 Qualifiers &quals) {
3897 SplitQualType splitType = type.getSplitUnqualifiedType();
3898
3899 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3900 // the unqualified desugared type and then drops it on the floor.
3901 // We then have to strip that sugar back off with
3902 // getUnqualifiedDesugaredType(), which is silly.
3903 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003904 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003905
3906 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003907 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003908 quals = splitType.Quals;
3909 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003910 }
3911
John McCall6c9dd522011-01-18 07:41:22 +00003912 // Otherwise, recurse on the array's element type.
3913 QualType elementType = AT->getElementType();
3914 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3915
3916 // If that didn't change the element type, AT has no qualifiers, so we
3917 // can just use the results in splitType.
3918 if (elementType == unqualElementType) {
3919 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003920 quals = splitType.Quals;
3921 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003922 }
3923
3924 // Otherwise, add in the qualifiers from the outermost type, then
3925 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003926 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003927
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003928 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003929 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003930 CAT->getSizeModifier(), 0);
3931 }
3932
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003933 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003934 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003935 }
3936
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003937 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003938 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003939 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003940 VAT->getSizeModifier(),
3941 VAT->getIndexTypeCVRQualifiers(),
3942 VAT->getBracketsRange());
3943 }
3944
3945 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003946 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003947 DSAT->getSizeModifier(), 0,
3948 SourceRange());
3949}
3950
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003951/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3952/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3953/// they point to and return true. If T1 and T2 aren't pointer types
3954/// or pointer-to-member types, or if they are not similar at this
3955/// level, returns false and leaves T1 and T2 unchanged. Top-level
3956/// qualifiers on T1 and T2 are ignored. This function will typically
3957/// be called in a loop that successively "unwraps" pointer and
3958/// pointer-to-member types to compare them at each level.
3959bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3960 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3961 *T2PtrType = T2->getAs<PointerType>();
3962 if (T1PtrType && T2PtrType) {
3963 T1 = T1PtrType->getPointeeType();
3964 T2 = T2PtrType->getPointeeType();
3965 return true;
3966 }
3967
3968 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3969 *T2MPType = T2->getAs<MemberPointerType>();
3970 if (T1MPType && T2MPType &&
3971 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3972 QualType(T2MPType->getClass(), 0))) {
3973 T1 = T1MPType->getPointeeType();
3974 T2 = T2MPType->getPointeeType();
3975 return true;
3976 }
3977
David Blaikiebbafb8a2012-03-11 07:00:24 +00003978 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003979 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3980 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3981 if (T1OPType && T2OPType) {
3982 T1 = T1OPType->getPointeeType();
3983 T2 = T2OPType->getPointeeType();
3984 return true;
3985 }
3986 }
3987
3988 // FIXME: Block pointers, too?
3989
3990 return false;
3991}
3992
Jay Foad39c79802011-01-12 09:06:06 +00003993DeclarationNameInfo
3994ASTContext::getNameForTemplate(TemplateName Name,
3995 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003996 switch (Name.getKind()) {
3997 case TemplateName::QualifiedTemplate:
3998 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003999 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004000 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4001 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004002
John McCalld9dfe3a2011-06-30 08:33:18 +00004003 case TemplateName::OverloadedTemplate: {
4004 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4005 // DNInfo work in progress: CHECKME: what about DNLoc?
4006 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4007 }
4008
4009 case TemplateName::DependentTemplate: {
4010 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004011 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004012 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004013 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4014 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004015 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004016 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4017 // DNInfo work in progress: FIXME: source locations?
4018 DeclarationNameLoc DNLoc;
4019 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4020 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4021 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004022 }
4023 }
4024
John McCalld9dfe3a2011-06-30 08:33:18 +00004025 case TemplateName::SubstTemplateTemplateParm: {
4026 SubstTemplateTemplateParmStorage *subst
4027 = Name.getAsSubstTemplateTemplateParm();
4028 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4029 NameLoc);
4030 }
4031
4032 case TemplateName::SubstTemplateTemplateParmPack: {
4033 SubstTemplateTemplateParmPackStorage *subst
4034 = Name.getAsSubstTemplateTemplateParmPack();
4035 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4036 NameLoc);
4037 }
4038 }
4039
4040 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004041}
4042
Jay Foad39c79802011-01-12 09:06:06 +00004043TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004044 switch (Name.getKind()) {
4045 case TemplateName::QualifiedTemplate:
4046 case TemplateName::Template: {
4047 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004048 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004049 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004050 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4051
4052 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004053 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004054 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004055
John McCalld9dfe3a2011-06-30 08:33:18 +00004056 case TemplateName::OverloadedTemplate:
4057 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004058
John McCalld9dfe3a2011-06-30 08:33:18 +00004059 case TemplateName::DependentTemplate: {
4060 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4061 assert(DTN && "Non-dependent template names must refer to template decls.");
4062 return DTN->CanonicalTemplateName;
4063 }
4064
4065 case TemplateName::SubstTemplateTemplateParm: {
4066 SubstTemplateTemplateParmStorage *subst
4067 = Name.getAsSubstTemplateTemplateParm();
4068 return getCanonicalTemplateName(subst->getReplacement());
4069 }
4070
4071 case TemplateName::SubstTemplateTemplateParmPack: {
4072 SubstTemplateTemplateParmPackStorage *subst
4073 = Name.getAsSubstTemplateTemplateParmPack();
4074 TemplateTemplateParmDecl *canonParameter
4075 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4076 TemplateArgument canonArgPack
4077 = getCanonicalTemplateArgument(subst->getArgumentPack());
4078 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4079 }
4080 }
4081
4082 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004083}
4084
Douglas Gregoradee3e32009-11-11 23:06:43 +00004085bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4086 X = getCanonicalTemplateName(X);
4087 Y = getCanonicalTemplateName(Y);
4088 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4089}
4090
Mike Stump11289f42009-09-09 15:08:12 +00004091TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004092ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004093 switch (Arg.getKind()) {
4094 case TemplateArgument::Null:
4095 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004096
Douglas Gregora8e02e72009-07-28 23:00:59 +00004097 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004098 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004099
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004100 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004101 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4102 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004103 }
Mike Stump11289f42009-09-09 15:08:12 +00004104
Eli Friedmanb826a002012-09-26 02:36:12 +00004105 case TemplateArgument::NullPtr:
4106 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4107 /*isNullPtr*/true);
4108
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004109 case TemplateArgument::Template:
4110 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004111
4112 case TemplateArgument::TemplateExpansion:
4113 return TemplateArgument(getCanonicalTemplateName(
4114 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004115 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004116
Douglas Gregora8e02e72009-07-28 23:00:59 +00004117 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004118 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004119
Douglas Gregora8e02e72009-07-28 23:00:59 +00004120 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004121 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004122
Douglas Gregora8e02e72009-07-28 23:00:59 +00004123 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004124 if (Arg.pack_size() == 0)
4125 return Arg;
4126
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004127 TemplateArgument *CanonArgs
4128 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004129 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004130 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004131 AEnd = Arg.pack_end();
4132 A != AEnd; (void)++A, ++Idx)
4133 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004134
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004135 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00004136 }
4137 }
4138
4139 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004140 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004141}
4142
Douglas Gregor333489b2009-03-27 23:10:48 +00004143NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004144ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004145 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00004146 return 0;
4147
4148 switch (NNS->getKind()) {
4149 case NestedNameSpecifier::Identifier:
4150 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004151 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004152 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4153 NNS->getAsIdentifier());
4154
4155 case NestedNameSpecifier::Namespace:
4156 // A namespace is canonical; build a nested-name-specifier with
4157 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004158 return NestedNameSpecifier::Create(*this, 0,
4159 NNS->getAsNamespace()->getOriginalNamespace());
4160
4161 case NestedNameSpecifier::NamespaceAlias:
4162 // A namespace is canonical; build a nested-name-specifier with
4163 // this namespace and no prefix.
4164 return NestedNameSpecifier::Create(*this, 0,
4165 NNS->getAsNamespaceAlias()->getNamespace()
4166 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004167
4168 case NestedNameSpecifier::TypeSpec:
4169 case NestedNameSpecifier::TypeSpecWithTemplate: {
4170 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004171
4172 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4173 // break it apart into its prefix and identifier, then reconsititute those
4174 // as the canonical nested-name-specifier. This is required to canonicalize
4175 // a dependent nested-name-specifier involving typedefs of dependent-name
4176 // types, e.g.,
4177 // typedef typename T::type T1;
4178 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004179 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4180 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004181 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004182
Eli Friedman5358a0a2012-03-03 04:09:56 +00004183 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4184 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4185 // first place?
John McCall33ddac02011-01-19 10:06:00 +00004186 return NestedNameSpecifier::Create(*this, 0, false,
4187 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004188 }
4189
4190 case NestedNameSpecifier::Global:
4191 // The global specifier is canonical and unique.
4192 return NNS;
4193 }
4194
David Blaikie8a40f702012-01-17 06:56:22 +00004195 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004196}
4197
Chris Lattner7adf0762008-08-04 07:31:14 +00004198
Jay Foad39c79802011-01-12 09:06:06 +00004199const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004200 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004201 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004202 // Handle the common positive case fast.
4203 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4204 return AT;
4205 }
Mike Stump11289f42009-09-09 15:08:12 +00004206
John McCall8ccfcb52009-09-24 19:53:00 +00004207 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004208 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00004209 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004210
John McCall8ccfcb52009-09-24 19:53:00 +00004211 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004212 // implements C99 6.7.3p8: "If the specification of an array type includes
4213 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004214
Chris Lattner7adf0762008-08-04 07:31:14 +00004215 // If we get here, we either have type qualifiers on the type, or we have
4216 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004217 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004218
John McCall33ddac02011-01-19 10:06:00 +00004219 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004220 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004221
Chris Lattner7adf0762008-08-04 07:31:14 +00004222 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004223 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00004224 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004225 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004226
Chris Lattner7adf0762008-08-04 07:31:14 +00004227 // Otherwise, we have an array and we have qualifiers on it. Push the
4228 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004229 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004230
Chris Lattner7adf0762008-08-04 07:31:14 +00004231 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4232 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4233 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004234 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004235 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4236 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4237 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004238 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004239
Mike Stump11289f42009-09-09 15:08:12 +00004240 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004241 = dyn_cast<DependentSizedArrayType>(ATy))
4242 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004243 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004244 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004245 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004246 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004247 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004248
Chris Lattner7adf0762008-08-04 07:31:14 +00004249 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004250 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004251 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004252 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004253 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004254 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004255}
4256
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004257QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004258 if (T->isArrayType() || T->isFunctionType())
4259 return getDecayedType(T);
4260 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004261}
4262
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004263QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004264 T = getVariableArrayDecayedType(T);
4265 T = getAdjustedParameterType(T);
4266 return T.getUnqualifiedType();
4267}
4268
Chris Lattnera21ad802008-04-02 05:18:44 +00004269/// getArrayDecayedType - Return the properly qualified result of decaying the
4270/// specified array type to a pointer. This operation is non-trivial when
4271/// handling typedefs etc. The canonical type of "T" must be an array type,
4272/// this returns a pointer to a properly qualified element of the array.
4273///
4274/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004275QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004276 // Get the element type with 'getAsArrayType' so that we don't lose any
4277 // typedefs in the element type of the array. This also handles propagation
4278 // of type qualifiers from the array type into the element type if present
4279 // (C99 6.7.3p8).
4280 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4281 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004282
Chris Lattner7adf0762008-08-04 07:31:14 +00004283 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004284
4285 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004286 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004287}
4288
John McCall33ddac02011-01-19 10:06:00 +00004289QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4290 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004291}
4292
John McCall33ddac02011-01-19 10:06:00 +00004293QualType ASTContext::getBaseElementType(QualType type) const {
4294 Qualifiers qs;
4295 while (true) {
4296 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004297 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004298 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004299
John McCall33ddac02011-01-19 10:06:00 +00004300 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004301 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004302 }
Mike Stump11289f42009-09-09 15:08:12 +00004303
John McCall33ddac02011-01-19 10:06:00 +00004304 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004305}
4306
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004307/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004308uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004309ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4310 uint64_t ElementCount = 1;
4311 do {
4312 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004313 CA = dyn_cast_or_null<ConstantArrayType>(
4314 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004315 } while (CA);
4316 return ElementCount;
4317}
4318
Steve Naroff0af91202007-04-27 21:51:21 +00004319/// getFloatingRank - Return a relative rank for floating point types.
4320/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004321static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004322 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004323 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004324
John McCall9dd450b2009-09-21 23:43:11 +00004325 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4326 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004327 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004328 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004329 case BuiltinType::Float: return FloatRank;
4330 case BuiltinType::Double: return DoubleRank;
4331 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004332 }
4333}
4334
Mike Stump11289f42009-09-09 15:08:12 +00004335/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4336/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004337/// 'typeDomain' is a real floating point or complex type.
4338/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004339QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4340 QualType Domain) const {
4341 FloatingRank EltRank = getFloatingRank(Size);
4342 if (Domain->isComplexType()) {
4343 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004344 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004345 case FloatRank: return FloatComplexTy;
4346 case DoubleRank: return DoubleComplexTy;
4347 case LongDoubleRank: return LongDoubleComplexTy;
4348 }
Steve Naroff0af91202007-04-27 21:51:21 +00004349 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004350
4351 assert(Domain->isRealFloatingType() && "Unknown domain!");
4352 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004353 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004354 case FloatRank: return FloatTy;
4355 case DoubleRank: return DoubleTy;
4356 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004357 }
David Blaikief47fa302012-01-17 02:30:50 +00004358 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004359}
4360
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004361/// getFloatingTypeOrder - Compare the rank of the two specified floating
4362/// point types, ignoring the domain of the type (i.e. 'double' ==
4363/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004364/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004365int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004366 FloatingRank LHSR = getFloatingRank(LHS);
4367 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004368
Chris Lattnerb90739d2008-04-06 23:38:49 +00004369 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004370 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004371 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004372 return 1;
4373 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004374}
4375
Chris Lattner76a00cf2008-04-06 22:59:24 +00004376/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4377/// routine will assert if passed a built-in type that isn't an integer or enum,
4378/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004379unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004380 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004381
Chris Lattner76a00cf2008-04-06 22:59:24 +00004382 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004383 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004384 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004385 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004386 case BuiltinType::Char_S:
4387 case BuiltinType::Char_U:
4388 case BuiltinType::SChar:
4389 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004390 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004391 case BuiltinType::Short:
4392 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004393 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004394 case BuiltinType::Int:
4395 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004396 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004397 case BuiltinType::Long:
4398 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004399 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004400 case BuiltinType::LongLong:
4401 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004402 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004403 case BuiltinType::Int128:
4404 case BuiltinType::UInt128:
4405 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004406 }
4407}
4408
Eli Friedman629ffb92009-08-20 04:21:42 +00004409/// \brief Whether this is a promotable bitfield reference according
4410/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4411///
4412/// \returns the type this bit-field will promote to, or NULL if no
4413/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004414QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004415 if (E->isTypeDependent() || E->isValueDependent())
4416 return QualType();
4417
John McCalld25db7e2013-05-06 21:39:12 +00004418 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004419 if (!Field)
4420 return QualType();
4421
4422 QualType FT = Field->getType();
4423
Richard Smithcaf33902011-10-10 18:28:20 +00004424 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004425 uint64_t IntSize = getTypeSize(IntTy);
4426 // GCC extension compatibility: if the bit-field size is less than or equal
4427 // to the size of int, it gets promoted no matter what its type is.
4428 // For instance, unsigned long bf : 4 gets promoted to signed int.
4429 if (BitWidth < IntSize)
4430 return IntTy;
4431
4432 if (BitWidth == IntSize)
4433 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4434
4435 // Types bigger than int are not subject to promotions, and therefore act
4436 // like the base type.
4437 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4438 // is ridiculous.
4439 return QualType();
4440}
4441
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004442/// getPromotedIntegerType - Returns the type that Promotable will
4443/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4444/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004445QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004446 assert(!Promotable.isNull());
4447 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004448 if (const EnumType *ET = Promotable->getAs<EnumType>())
4449 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004450
4451 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4452 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4453 // (3.9.1) can be converted to a prvalue of the first of the following
4454 // types that can represent all the values of its underlying type:
4455 // int, unsigned int, long int, unsigned long int, long long int, or
4456 // unsigned long long int [...]
4457 // FIXME: Is there some better way to compute this?
4458 if (BT->getKind() == BuiltinType::WChar_S ||
4459 BT->getKind() == BuiltinType::WChar_U ||
4460 BT->getKind() == BuiltinType::Char16 ||
4461 BT->getKind() == BuiltinType::Char32) {
4462 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4463 uint64_t FromSize = getTypeSize(BT);
4464 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4465 LongLongTy, UnsignedLongLongTy };
4466 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4467 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4468 if (FromSize < ToSize ||
4469 (FromSize == ToSize &&
4470 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4471 return PromoteTypes[Idx];
4472 }
4473 llvm_unreachable("char type should fit into long long");
4474 }
4475 }
4476
4477 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004478 if (Promotable->isSignedIntegerType())
4479 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004480 uint64_t PromotableSize = getIntWidth(Promotable);
4481 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004482 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4483 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4484}
4485
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004486/// \brief Recurses in pointer/array types until it finds an objc retainable
4487/// type and returns its ownership.
4488Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4489 while (!T.isNull()) {
4490 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4491 return T.getObjCLifetime();
4492 if (T->isArrayType())
4493 T = getBaseElementType(T);
4494 else if (const PointerType *PT = T->getAs<PointerType>())
4495 T = PT->getPointeeType();
4496 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004497 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004498 else
4499 break;
4500 }
4501
4502 return Qualifiers::OCL_None;
4503}
4504
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004505static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4506 // Incomplete enum types are not treated as integer types.
4507 // FIXME: In C++, enum types are never integer types.
4508 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4509 return ET->getDecl()->getIntegerType().getTypePtr();
4510 return NULL;
4511}
4512
Mike Stump11289f42009-09-09 15:08:12 +00004513/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004514/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004515/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004516int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004517 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4518 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004519
4520 // Unwrap enums to their underlying type.
4521 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4522 LHSC = getIntegerTypeForEnum(ET);
4523 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4524 RHSC = getIntegerTypeForEnum(ET);
4525
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004526 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004527
Chris Lattner76a00cf2008-04-06 22:59:24 +00004528 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4529 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004530
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004531 unsigned LHSRank = getIntegerRank(LHSC);
4532 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004533
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004534 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4535 if (LHSRank == RHSRank) return 0;
4536 return LHSRank > RHSRank ? 1 : -1;
4537 }
Mike Stump11289f42009-09-09 15:08:12 +00004538
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004539 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4540 if (LHSUnsigned) {
4541 // If the unsigned [LHS] type is larger, return it.
4542 if (LHSRank >= RHSRank)
4543 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004544
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004545 // If the signed type can represent all values of the unsigned type, it
4546 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004547 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004548 return -1;
4549 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004550
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004551 // If the unsigned [RHS] type is larger, return it.
4552 if (RHSRank >= LHSRank)
4553 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004554
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004555 // If the signed type can represent all values of the unsigned type, it
4556 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004557 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004558 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004559}
Anders Carlsson98f07902007-08-17 05:31:46 +00004560
Mike Stump11289f42009-09-09 15:08:12 +00004561// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004562QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004563 if (!CFConstantStringTypeDecl) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004564 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
John McCallae580fe2010-02-05 01:33:36 +00004565 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004566
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004567 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004568
Anders Carlsson98f07902007-08-17 05:31:46 +00004569 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004570 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004571 // int flags;
4572 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004573 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004574 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004575 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004576 FieldTypes[3] = LongTy;
4577
Anders Carlsson98f07902007-08-17 05:31:46 +00004578 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004579 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004580 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004581 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004582 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004583 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004584 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004585 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004586 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004587 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004588 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004589 }
4590
Douglas Gregord5058122010-02-11 01:19:42 +00004591 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004592 }
Mike Stump11289f42009-09-09 15:08:12 +00004593
Anders Carlsson98f07902007-08-17 05:31:46 +00004594 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004595}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004596
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004597QualType ASTContext::getObjCSuperType() const {
4598 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004599 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004600 TUDecl->addDecl(ObjCSuperTypeDecl);
4601 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4602 }
4603 return ObjCSuperType;
4604}
4605
Douglas Gregor512b0772009-04-23 22:29:11 +00004606void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004607 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004608 assert(Rec && "Invalid CFConstantStringType");
4609 CFConstantStringTypeDecl = Rec->getDecl();
4610}
4611
Jay Foad39c79802011-01-12 09:06:06 +00004612QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004613 if (BlockDescriptorType)
4614 return getTagDeclType(BlockDescriptorType);
4615
Alp Toker2dea15b2013-12-17 01:22:38 +00004616 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004617 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004618 RD = buildImplicitRecord("__block_descriptor");
4619 RD->startDefinition();
4620
Mike Stumpd0153282009-10-20 02:12:22 +00004621 QualType FieldTypes[] = {
4622 UnsignedLongTy,
4623 UnsignedLongTy,
4624 };
4625
Craig Topperd6d31ac2013-07-15 08:24:27 +00004626 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004627 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004628 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004629 };
4630
4631 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004632 FieldDecl *Field = FieldDecl::Create(
4633 *this, RD, SourceLocation(), SourceLocation(),
4634 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/0,
4635 /*BitWidth=*/0, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004636 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004637 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004638 }
4639
Alp Toker2dea15b2013-12-17 01:22:38 +00004640 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004641
Alp Toker2dea15b2013-12-17 01:22:38 +00004642 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004643
4644 return getTagDeclType(BlockDescriptorType);
4645}
4646
Jay Foad39c79802011-01-12 09:06:06 +00004647QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004648 if (BlockDescriptorExtendedType)
4649 return getTagDeclType(BlockDescriptorExtendedType);
4650
Alp Toker2dea15b2013-12-17 01:22:38 +00004651 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004652 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004653 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4654 RD->startDefinition();
4655
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004656 QualType FieldTypes[] = {
4657 UnsignedLongTy,
4658 UnsignedLongTy,
4659 getPointerType(VoidPtrTy),
4660 getPointerType(VoidPtrTy)
4661 };
4662
Craig Topperd6d31ac2013-07-15 08:24:27 +00004663 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004664 "reserved",
4665 "Size",
4666 "CopyFuncPtr",
4667 "DestroyFuncPtr"
4668 };
4669
4670 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004671 FieldDecl *Field = FieldDecl::Create(
4672 *this, RD, SourceLocation(), SourceLocation(),
4673 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/0,
4674 /*BitWidth=*/0,
4675 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004676 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004677 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004678 }
4679
Alp Toker2dea15b2013-12-17 01:22:38 +00004680 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004681
Alp Toker2dea15b2013-12-17 01:22:38 +00004682 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004683 return getTagDeclType(BlockDescriptorExtendedType);
4684}
4685
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004686/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4687/// requires copy/dispose. Note that this must match the logic
4688/// in buildByrefHelpers.
4689bool ASTContext::BlockRequiresCopying(QualType Ty,
4690 const VarDecl *D) {
4691 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4692 const Expr *copyExpr = getBlockVarCopyInits(D);
4693 if (!copyExpr && record->hasTrivialDestructor()) return false;
4694
Mike Stump94967902009-10-21 18:16:27 +00004695 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004696 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004697
4698 if (!Ty->isObjCRetainableType()) return false;
4699
4700 Qualifiers qs = Ty.getQualifiers();
4701
4702 // If we have lifetime, that dominates.
4703 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4704 assert(getLangOpts().ObjCAutoRefCount);
4705
4706 switch (lifetime) {
4707 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4708
4709 // These are just bits as far as the runtime is concerned.
4710 case Qualifiers::OCL_ExplicitNone:
4711 case Qualifiers::OCL_Autoreleasing:
4712 return false;
4713
4714 // Tell the runtime that this is ARC __weak, called by the
4715 // byref routines.
4716 case Qualifiers::OCL_Weak:
4717 // ARC __strong __block variables need to be retained.
4718 case Qualifiers::OCL_Strong:
4719 return true;
4720 }
4721 llvm_unreachable("fell out of lifetime switch!");
4722 }
4723 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4724 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004725}
4726
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004727bool ASTContext::getByrefLifetime(QualType Ty,
4728 Qualifiers::ObjCLifetime &LifeTime,
4729 bool &HasByrefExtendedLayout) const {
4730
4731 if (!getLangOpts().ObjC1 ||
4732 getLangOpts().getGC() != LangOptions::NonGC)
4733 return false;
4734
4735 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004736 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004737 HasByrefExtendedLayout = true;
4738 LifeTime = Qualifiers::OCL_None;
4739 }
4740 else if (getLangOpts().ObjCAutoRefCount)
4741 LifeTime = Ty.getObjCLifetime();
4742 // MRR.
4743 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4744 LifeTime = Qualifiers::OCL_ExplicitNone;
4745 else
4746 LifeTime = Qualifiers::OCL_None;
4747 return true;
4748}
4749
Douglas Gregorbab8a962011-09-08 01:46:34 +00004750TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4751 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00004752 ObjCInstanceTypeDecl =
4753 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00004754 return ObjCInstanceTypeDecl;
4755}
4756
Anders Carlsson18acd442007-10-29 06:33:42 +00004757// This returns true if a type has been typedefed to BOOL:
4758// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004759static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004760 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004761 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4762 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004763
Anders Carlssond8499822007-10-29 05:01:08 +00004764 return false;
4765}
4766
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004767/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004768/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004769CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004770 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4771 return CharUnits::Zero();
4772
Ken Dyck40775002010-01-11 17:06:35 +00004773 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004774
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004775 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004776 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004777 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004778 // Treat arrays as pointers, since that's how they're passed in.
4779 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004780 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004781 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004782}
4783
4784static inline
4785std::string charUnitsToString(const CharUnits &CU) {
4786 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004787}
4788
John McCall351762c2011-02-07 10:33:21 +00004789/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004790/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004791std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4792 std::string S;
4793
David Chisnall950a9512009-11-17 19:33:30 +00004794 const BlockDecl *Decl = Expr->getBlockDecl();
4795 QualType BlockTy =
4796 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4797 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004798 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00004799 getObjCEncodingForMethodParameter(
4800 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
4801 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004802 else
Alp Toker314cc812014-01-25 16:55:45 +00004803 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004804 // Compute size of all parameters.
4805 // Start with computing size of a pointer in number of bytes.
4806 // FIXME: There might(should) be a better way of doing this computation!
4807 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004808 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4809 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004810 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004811 E = Decl->param_end(); PI != E; ++PI) {
4812 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004813 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004814 if (sz.isZero())
4815 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004816 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004817 ParmOffset += sz;
4818 }
4819 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004820 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004821 // Block pointer and offset.
4822 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004823
4824 // Argument types.
4825 ParmOffset = PtrSize;
4826 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4827 Decl->param_end(); PI != E; ++PI) {
4828 ParmVarDecl *PVDecl = *PI;
4829 QualType PType = PVDecl->getOriginalType();
4830 if (const ArrayType *AT =
4831 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4832 // Use array's original type only if it has known number of
4833 // elements.
4834 if (!isa<ConstantArrayType>(AT))
4835 PType = PVDecl->getType();
4836 } else if (PType->isFunctionType())
4837 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004838 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004839 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4840 S, true /*Extended*/);
4841 else
4842 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004843 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004844 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004845 }
John McCall351762c2011-02-07 10:33:21 +00004846
4847 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004848}
4849
Douglas Gregora9d84932011-05-27 01:19:52 +00004850bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004851 std::string& S) {
4852 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00004853 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00004854 CharUnits ParmOffset;
4855 // Compute size of all parameters.
4856 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4857 E = Decl->param_end(); PI != E; ++PI) {
4858 QualType PType = (*PI)->getType();
4859 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004860 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004861 continue;
4862
David Chisnall50e4eba2010-12-30 14:05:53 +00004863 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004864 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004865 ParmOffset += sz;
4866 }
4867 S += charUnitsToString(ParmOffset);
4868 ParmOffset = CharUnits::Zero();
4869
4870 // Argument types.
4871 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4872 E = Decl->param_end(); PI != E; ++PI) {
4873 ParmVarDecl *PVDecl = *PI;
4874 QualType PType = PVDecl->getOriginalType();
4875 if (const ArrayType *AT =
4876 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4877 // Use array's original type only if it has known number of
4878 // elements.
4879 if (!isa<ConstantArrayType>(AT))
4880 PType = PVDecl->getType();
4881 } else if (PType->isFunctionType())
4882 PType = PVDecl->getType();
4883 getObjCEncodingForType(PType, S);
4884 S += charUnitsToString(ParmOffset);
4885 ParmOffset += getObjCEncodingTypeSize(PType);
4886 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004887
4888 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004889}
4890
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004891/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4892/// method parameter or return type. If Extended, include class names and
4893/// block object types.
4894void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4895 QualType T, std::string& S,
4896 bool Extended) const {
4897 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4898 getObjCEncodingForTypeQualifier(QT, S);
4899 // Encode parameter type.
4900 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4901 true /*OutermostType*/,
4902 false /*EncodingProperty*/,
4903 false /*StructField*/,
4904 Extended /*EncodeBlockParameters*/,
4905 Extended /*EncodeClassNames*/);
4906}
4907
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004908/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004909/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004910bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004911 std::string& S,
4912 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004913 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004914 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00004915 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4916 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004917 // Compute size of all parameters.
4918 // Start with computing size of a pointer in number of bytes.
4919 // FIXME: There might(should) be a better way of doing this computation!
4920 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004921 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004922 // The first two arguments (self and _cmd) are pointers; account for
4923 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004924 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004925 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004926 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004927 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004928 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004929 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004930 continue;
4931
Ken Dyck40775002010-01-11 17:06:35 +00004932 assert (sz.isPositive() &&
4933 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004934 ParmOffset += sz;
4935 }
Ken Dyck40775002010-01-11 17:06:35 +00004936 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004937 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004938 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004939
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004940 // Argument types.
4941 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004942 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004943 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004944 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004945 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004946 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004947 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4948 // Use array's original type only if it has known number of
4949 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004950 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004951 PType = PVDecl->getType();
4952 } else if (PType->isFunctionType())
4953 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004954 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4955 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004956 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004957 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004958 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004959
4960 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004961}
4962
Fariborz Jahaniandad96302014-01-22 19:02:20 +00004963ObjCPropertyImplDecl *
4964ASTContext::getObjCPropertyImplDeclForPropertyDecl(
4965 const ObjCPropertyDecl *PD,
4966 const Decl *Container) const {
4967 if (!Container)
4968 return 0;
4969 if (const ObjCCategoryImplDecl *CID =
4970 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4971 for (ObjCCategoryImplDecl::propimpl_iterator
4972 i = CID->propimpl_begin(), e = CID->propimpl_end();
4973 i != e; ++i) {
4974 ObjCPropertyImplDecl *PID = *i;
4975 if (PID->getPropertyDecl() == PD)
4976 return PID;
4977 }
4978 } else {
4979 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
4980 for (ObjCCategoryImplDecl::propimpl_iterator
4981 i = OID->propimpl_begin(), e = OID->propimpl_end();
4982 i != e; ++i) {
4983 ObjCPropertyImplDecl *PID = *i;
4984 if (PID->getPropertyDecl() == PD)
4985 return PID;
4986 }
4987 }
4988 return 0;
4989}
4990
Daniel Dunbar4932b362008-08-28 04:38:10 +00004991/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004992/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004993/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4994/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004995/// Property attributes are stored as a comma-delimited C string. The simple
4996/// attributes readonly and bycopy are encoded as single characters. The
4997/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4998/// encoded as single characters, followed by an identifier. Property types
4999/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005000/// these attributes are defined by the following enumeration:
5001/// @code
5002/// enum PropertyAttributes {
5003/// kPropertyReadOnly = 'R', // property is read-only.
5004/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5005/// kPropertyByref = '&', // property is a reference to the value last assigned
5006/// kPropertyDynamic = 'D', // property is dynamic
5007/// kPropertyGetter = 'G', // followed by getter selector name
5008/// kPropertySetter = 'S', // followed by setter selector name
5009/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005010/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005011/// kPropertyWeak = 'W' // 'weak' property
5012/// kPropertyStrong = 'P' // property GC'able
5013/// kPropertyNonAtomic = 'N' // property non-atomic
5014/// };
5015/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005016void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005017 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005018 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005019 // Collect information from the property implementation decl(s).
5020 bool Dynamic = false;
5021 ObjCPropertyImplDecl *SynthesizePID = 0;
5022
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005023 if (ObjCPropertyImplDecl *PropertyImpDecl =
5024 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5025 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5026 Dynamic = true;
5027 else
5028 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005029 }
5030
5031 // FIXME: This is not very efficient.
5032 S = "T";
5033
5034 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005035 // GCC has some special rules regarding encoding of properties which
5036 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00005037 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005038 true /* outermost type */,
5039 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005040
5041 if (PD->isReadOnly()) {
5042 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005043 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5044 S += ",C";
5045 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5046 S += ",&";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005047 } else {
5048 switch (PD->getSetterKind()) {
5049 case ObjCPropertyDecl::Assign: break;
5050 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005051 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005052 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005053 }
5054 }
5055
5056 // It really isn't clear at all what this means, since properties
5057 // are "dynamic by default".
5058 if (Dynamic)
5059 S += ",D";
5060
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005061 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5062 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005063
Daniel Dunbar4932b362008-08-28 04:38:10 +00005064 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5065 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005066 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005067 }
5068
5069 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5070 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005071 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005072 }
5073
5074 if (SynthesizePID) {
5075 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5076 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005077 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005078 }
5079
5080 // FIXME: OBJCGC: weak & strong
5081}
5082
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005083/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005084/// Another legacy compatibility encoding: 32-bit longs are encoded as
5085/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005086/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5087///
5088void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005089 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005090 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005091 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005092 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005093 else
Jay Foad39c79802011-01-12 09:06:06 +00005094 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005095 PointeeTy = IntTy;
5096 }
5097 }
5098}
5099
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005100void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00005101 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005102 // We follow the behavior of gcc, expanding structures which are
5103 // directly pointed to, and expanding embedded structures. Note that
5104 // these rules are sufficient to prevent recursive encoding of the
5105 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005106 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00005107 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005108}
5109
John McCall393a78d2012-12-20 02:45:14 +00005110static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5111 BuiltinType::Kind kind) {
5112 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005113 case BuiltinType::Void: return 'v';
5114 case BuiltinType::Bool: return 'B';
5115 case BuiltinType::Char_U:
5116 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005117 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005118 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005119 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005120 case BuiltinType::UInt: return 'I';
5121 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005122 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005123 case BuiltinType::UInt128: return 'T';
5124 case BuiltinType::ULongLong: return 'Q';
5125 case BuiltinType::Char_S:
5126 case BuiltinType::SChar: return 'c';
5127 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005128 case BuiltinType::WChar_S:
5129 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005130 case BuiltinType::Int: return 'i';
5131 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005132 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005133 case BuiltinType::LongLong: return 'q';
5134 case BuiltinType::Int128: return 't';
5135 case BuiltinType::Float: return 'f';
5136 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005137 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005138 case BuiltinType::NullPtr: return '*'; // like char*
5139
5140 case BuiltinType::Half:
5141 // FIXME: potentially need @encodes for these!
5142 return ' ';
5143
5144 case BuiltinType::ObjCId:
5145 case BuiltinType::ObjCClass:
5146 case BuiltinType::ObjCSel:
5147 llvm_unreachable("@encoding ObjC primitive type");
5148
5149 // OpenCL and placeholder types don't need @encodings.
5150 case BuiltinType::OCLImage1d:
5151 case BuiltinType::OCLImage1dArray:
5152 case BuiltinType::OCLImage1dBuffer:
5153 case BuiltinType::OCLImage2d:
5154 case BuiltinType::OCLImage2dArray:
5155 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005156 case BuiltinType::OCLEvent:
Guy Benyei61054192013-02-07 10:55:47 +00005157 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005158 case BuiltinType::Dependent:
5159#define BUILTIN_TYPE(KIND, ID)
5160#define PLACEHOLDER_TYPE(KIND, ID) \
5161 case BuiltinType::KIND:
5162#include "clang/AST/BuiltinTypes.def"
5163 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005164 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005165 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005166}
5167
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005168static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5169 EnumDecl *Enum = ET->getDecl();
5170
5171 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5172 if (!Enum->isFixed())
5173 return 'i';
5174
5175 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005176 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5177 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005178}
5179
Jay Foad39c79802011-01-12 09:06:06 +00005180static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005181 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005182 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005183 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005184 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5185 // The GNU runtime requires more information; bitfields are encoded as b,
5186 // then the offset (in bits) of the first element, then the type of the
5187 // bitfield, then the size in bits. For example, in this structure:
5188 //
5189 // struct
5190 // {
5191 // int integer;
5192 // int flags:2;
5193 // };
5194 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5195 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5196 // information is not especially sensible, but we're stuck with it for
5197 // compatibility with GCC, although providing it breaks anything that
5198 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005199 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005200 const RecordDecl *RD = FD->getParent();
5201 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005202 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005203 if (const EnumType *ET = T->getAs<EnumType>())
5204 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005205 else {
5206 const BuiltinType *BT = T->castAs<BuiltinType>();
5207 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5208 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005209 }
Richard Smithcaf33902011-10-10 18:28:20 +00005210 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005211}
5212
Daniel Dunbar07d07852009-10-18 21:17:35 +00005213// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005214void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5215 bool ExpandPointedToStructures,
5216 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005217 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005218 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005219 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005220 bool StructField,
5221 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005222 bool EncodeClassNames,
5223 bool EncodePointerToObjCTypedef) const {
John McCall393a78d2012-12-20 02:45:14 +00005224 CanQualType CT = getCanonicalType(T);
5225 switch (CT->getTypeClass()) {
5226 case Type::Builtin:
5227 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005228 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005229 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005230 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5231 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5232 else
5233 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005234 return;
Mike Stump11289f42009-09-09 15:08:12 +00005235
John McCall393a78d2012-12-20 02:45:14 +00005236 case Type::Complex: {
5237 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005238 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00005239 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00005240 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005241 return;
5242 }
John McCall393a78d2012-12-20 02:45:14 +00005243
5244 case Type::Atomic: {
5245 const AtomicType *AT = T->castAs<AtomicType>();
5246 S += 'A';
5247 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5248 false, false);
5249 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005250 }
John McCall393a78d2012-12-20 02:45:14 +00005251
5252 // encoding for pointer or reference types.
5253 case Type::Pointer:
5254 case Type::LValueReference:
5255 case Type::RValueReference: {
5256 QualType PointeeTy;
5257 if (isa<PointerType>(CT)) {
5258 const PointerType *PT = T->castAs<PointerType>();
5259 if (PT->isObjCSelType()) {
5260 S += ':';
5261 return;
5262 }
5263 PointeeTy = PT->getPointeeType();
5264 } else {
5265 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5266 }
5267
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005268 bool isReadOnly = false;
5269 // For historical/compatibility reasons, the read-only qualifier of the
5270 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5271 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005272 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005273 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005274 if (OutermostType && T.isConstQualified()) {
5275 isReadOnly = true;
5276 S += 'r';
5277 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005278 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005279 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005280 while (P->getAs<PointerType>())
5281 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005282 if (P.isConstQualified()) {
5283 isReadOnly = true;
5284 S += 'r';
5285 }
5286 }
5287 if (isReadOnly) {
5288 // Another legacy compatibility encoding. Some ObjC qualifier and type
5289 // combinations need to be rearranged.
5290 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005291 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005292 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005293 }
Mike Stump11289f42009-09-09 15:08:12 +00005294
Anders Carlssond8499822007-10-29 05:01:08 +00005295 if (PointeeTy->isCharType()) {
5296 // char pointer types should be encoded as '*' unless it is a
5297 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005298 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005299 S += '*';
5300 return;
5301 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005302 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005303 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5304 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5305 S += '#';
5306 return;
5307 }
5308 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5309 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5310 S += '@';
5311 return;
5312 }
5313 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005314 }
Anders Carlssond8499822007-10-29 05:01:08 +00005315 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005316 getLegacyIntegralTypeEncoding(PointeeTy);
5317
Mike Stump11289f42009-09-09 15:08:12 +00005318 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005319 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005320 return;
5321 }
John McCall393a78d2012-12-20 02:45:14 +00005322
5323 case Type::ConstantArray:
5324 case Type::IncompleteArray:
5325 case Type::VariableArray: {
5326 const ArrayType *AT = cast<ArrayType>(CT);
5327
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005328 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005329 // Incomplete arrays are encoded as a pointer to the array element.
5330 S += '^';
5331
Mike Stump11289f42009-09-09 15:08:12 +00005332 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005333 false, ExpandStructures, FD);
5334 } else {
5335 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005336
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005337 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5338 S += llvm::utostr(CAT->getSize().getZExtValue());
5339 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005340 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005341 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5342 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005343 S += '0';
5344 }
Mike Stump11289f42009-09-09 15:08:12 +00005345
5346 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005347 false, ExpandStructures, FD);
5348 S += ']';
5349 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005350 return;
5351 }
Mike Stump11289f42009-09-09 15:08:12 +00005352
John McCall393a78d2012-12-20 02:45:14 +00005353 case Type::FunctionNoProto:
5354 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005355 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005356 return;
Mike Stump11289f42009-09-09 15:08:12 +00005357
John McCall393a78d2012-12-20 02:45:14 +00005358 case Type::Record: {
5359 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005360 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005361 // Anonymous structures print as '?'
5362 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5363 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005364 if (ClassTemplateSpecializationDecl *Spec
5365 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5366 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005367 llvm::raw_string_ostream OS(S);
5368 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005369 TemplateArgs.data(),
5370 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005371 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005372 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005373 } else {
5374 S += '?';
5375 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005376 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005377 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005378 if (!RDecl->isUnion()) {
5379 getObjCEncodingForStructureImpl(RDecl, S, FD);
5380 } else {
5381 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5382 FieldEnd = RDecl->field_end();
5383 Field != FieldEnd; ++Field) {
5384 if (FD) {
5385 S += '"';
5386 S += Field->getNameAsString();
5387 S += '"';
5388 }
Mike Stump11289f42009-09-09 15:08:12 +00005389
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005390 // Special case bit-fields.
5391 if (Field->isBitField()) {
5392 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00005393 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005394 } else {
5395 QualType qt = Field->getType();
5396 getLegacyIntegralTypeEncoding(qt);
5397 getObjCEncodingForTypeImpl(qt, S, false, true,
5398 FD, /*OutermostType*/false,
5399 /*EncodingProperty*/false,
5400 /*StructField*/true);
5401 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005402 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005403 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005404 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005405 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005406 return;
5407 }
Mike Stump11289f42009-09-09 15:08:12 +00005408
John McCall393a78d2012-12-20 02:45:14 +00005409 case Type::BlockPointer: {
5410 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005411 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005412 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005413 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005414
5415 S += '<';
5416 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005417 getObjCEncodingForTypeImpl(
5418 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5419 FD, false /* OutermostType */, EncodingProperty,
5420 false /* StructField */, EncodeBlockParameters, EncodeClassNames);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005421 // Block self
5422 S += "@?";
5423 // Block parameters
5424 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Alp Toker9cacbab2014-01-20 20:26:09 +00005425 for (FunctionProtoType::param_type_iterator I = FPT->param_type_begin(),
5426 E = FPT->param_type_end();
5427 I && (I != E); ++I) {
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005428 getObjCEncodingForTypeImpl(*I, S,
5429 ExpandPointedToStructures,
5430 ExpandStructures,
5431 FD,
5432 false /* OutermostType */,
5433 EncodingProperty,
5434 false /* StructField */,
5435 EncodeBlockParameters,
5436 EncodeClassNames);
5437 }
5438 }
5439 S += '>';
5440 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005441 return;
5442 }
Mike Stump11289f42009-09-09 15:08:12 +00005443
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005444 case Type::ObjCObject: {
5445 // hack to match legacy encoding of *id and *Class
5446 QualType Ty = getObjCObjectPointerType(CT);
5447 if (Ty->isObjCIdType()) {
5448 S += "{objc_object=}";
5449 return;
5450 }
5451 else if (Ty->isObjCClassType()) {
5452 S += "{objc_class=}";
5453 return;
5454 }
5455 }
5456
John McCall393a78d2012-12-20 02:45:14 +00005457 case Type::ObjCInterface: {
5458 // Ignore protocol qualifiers when mangling at this level.
5459 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005460
John McCall393a78d2012-12-20 02:45:14 +00005461 // The assumption seems to be that this assert will succeed
5462 // because nested levels will have filtered out 'id' and 'Class'.
5463 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005464 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005465 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005466 S += '{';
5467 const IdentifierInfo *II = OI->getIdentifier();
5468 S += II->getName();
5469 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005470 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005471 DeepCollectObjCIvars(OI, true, Ivars);
5472 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005473 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005474 if (Field->isBitField())
5475 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005476 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005477 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5478 false, false, false, false, false,
5479 EncodePointerToObjCTypedef);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005480 }
5481 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005482 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005483 }
Mike Stump11289f42009-09-09 15:08:12 +00005484
John McCall393a78d2012-12-20 02:45:14 +00005485 case Type::ObjCObjectPointer: {
5486 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005487 if (OPT->isObjCIdType()) {
5488 S += '@';
5489 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005490 }
Mike Stump11289f42009-09-09 15:08:12 +00005491
Steve Narofff0c86112009-10-28 22:03:49 +00005492 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5493 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5494 // Since this is a binary compatibility issue, need to consult with runtime
5495 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005496 S += '#';
5497 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005498 }
Mike Stump11289f42009-09-09 15:08:12 +00005499
Chris Lattnere7cabb92009-07-13 00:10:46 +00005500 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005501 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005502 ExpandPointedToStructures,
5503 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005504 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005505 // Note that we do extended encoding of protocol qualifer list
5506 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005507 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00005508 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5509 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005510 S += '<';
5511 S += (*I)->getNameAsString();
5512 S += '>';
5513 }
5514 S += '"';
5515 }
5516 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005517 }
Mike Stump11289f42009-09-09 15:08:12 +00005518
Chris Lattnere7cabb92009-07-13 00:10:46 +00005519 QualType PointeeTy = OPT->getPointeeType();
5520 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005521 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5522 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005523 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005524 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005525 // {...};
5526 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005527 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005528 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005529 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5530 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5531 DeepCollectObjCIvars(OI, true, Ivars);
5532 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5533 if (cast<FieldDecl>(Ivars[i]) == FD) {
5534 S += '{';
5535 S += OI->getIdentifier()->getName();
5536 S += '}';
5537 return;
5538 }
5539 }
5540 }
Mike Stump11289f42009-09-09 15:08:12 +00005541 getObjCEncodingForTypeImpl(PointeeTy, S,
5542 false, ExpandPointedToStructures,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005543 NULL,
5544 false, false, false, false, false,
5545 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005546 return;
5547 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005548
5549 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005550 if (OPT->getInterfaceDecl() &&
5551 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005552 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005553 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00005554 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5555 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005556 S += '<';
5557 S += (*I)->getNameAsString();
5558 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005559 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005560 S += '"';
5561 }
5562 return;
5563 }
Mike Stump11289f42009-09-09 15:08:12 +00005564
John McCalla9e6e8d2010-05-17 23:56:34 +00005565 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005566 // FIXME: we shoul do better than that. 'M' is available.
5567 case Type::MemberPointer:
John McCalla9e6e8d2010-05-17 23:56:34 +00005568 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005569
John McCall393a78d2012-12-20 02:45:14 +00005570 case Type::Vector:
5571 case Type::ExtVector:
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005572 // This matches gcc's encoding, even though technically it is
5573 // insufficient.
5574 // FIXME. We should do a better job than gcc.
5575 return;
John McCall393a78d2012-12-20 02:45:14 +00005576
Richard Smith27d807c2013-04-30 13:56:41 +00005577 case Type::Auto:
5578 // We could see an undeduced auto type here during error recovery.
5579 // Just ignore it.
5580 return;
5581
John McCall393a78d2012-12-20 02:45:14 +00005582#define ABSTRACT_TYPE(KIND, BASE)
5583#define TYPE(KIND, BASE)
5584#define DEPENDENT_TYPE(KIND, BASE) \
5585 case Type::KIND:
5586#define NON_CANONICAL_TYPE(KIND, BASE) \
5587 case Type::KIND:
5588#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5589 case Type::KIND:
5590#include "clang/AST/TypeNodes.def"
5591 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005592 }
John McCall393a78d2012-12-20 02:45:14 +00005593 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005594}
5595
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005596void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5597 std::string &S,
5598 const FieldDecl *FD,
5599 bool includeVBases) const {
5600 assert(RDecl && "Expected non-null RecordDecl");
5601 assert(!RDecl->isUnion() && "Should not be called for unions");
5602 if (!RDecl->getDefinition())
5603 return;
5604
5605 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5606 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5607 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5608
5609 if (CXXRec) {
5610 for (CXXRecordDecl::base_class_iterator
5611 BI = CXXRec->bases_begin(),
5612 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5613 if (!BI->isVirtual()) {
5614 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005615 if (base->isEmpty())
5616 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005617 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005618 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5619 std::make_pair(offs, base));
5620 }
5621 }
5622 }
5623
5624 unsigned i = 0;
5625 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5626 FieldEnd = RDecl->field_end();
5627 Field != FieldEnd; ++Field, ++i) {
5628 uint64_t offs = layout.getFieldOffset(i);
5629 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005630 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005631 }
5632
5633 if (CXXRec && includeVBases) {
5634 for (CXXRecordDecl::base_class_iterator
5635 BI = CXXRec->vbases_begin(),
5636 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5637 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005638 if (base->isEmpty())
5639 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005640 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005641 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5642 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005643 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5644 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005645 }
5646 }
5647
5648 CharUnits size;
5649 if (CXXRec) {
5650 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5651 } else {
5652 size = layout.getSize();
5653 }
5654
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005655#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005656 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005657#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005658 std::multimap<uint64_t, NamedDecl *>::iterator
5659 CurLayObj = FieldOrBaseOffsets.begin();
5660
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005661 if (CXXRec && CXXRec->isDynamicClass() &&
5662 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005663 if (FD) {
5664 S += "\"_vptr$";
5665 std::string recname = CXXRec->getNameAsString();
5666 if (recname.empty()) recname = "?";
5667 S += recname;
5668 S += '"';
5669 }
5670 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005671#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005672 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005673#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005674 }
5675
5676 if (!RDecl->hasFlexibleArrayMember()) {
5677 // Mark the end of the structure.
5678 uint64_t offs = toBits(size);
5679 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5680 std::make_pair(offs, (NamedDecl*)0));
5681 }
5682
5683 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005684#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005685 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005686 if (CurOffs < CurLayObj->first) {
5687 uint64_t padding = CurLayObj->first - CurOffs;
5688 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5689 // packing/alignment of members is different that normal, in which case
5690 // the encoding will be out-of-sync with the real layout.
5691 // If the runtime switches to just consider the size of types without
5692 // taking into account alignment, we could make padding explicit in the
5693 // encoding (e.g. using arrays of chars). The encoding strings would be
5694 // longer then though.
5695 CurOffs += padding;
5696 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005697#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005698
5699 NamedDecl *dcl = CurLayObj->second;
5700 if (dcl == 0)
5701 break; // reached end of structure.
5702
5703 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5704 // We expand the bases without their virtual bases since those are going
5705 // in the initial structure. Note that this differs from gcc which
5706 // expands virtual bases each time one is encountered in the hierarchy,
5707 // making the encoding type bigger than it really is.
5708 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005709 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005710#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005711 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005712#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005713 } else {
5714 FieldDecl *field = cast<FieldDecl>(dcl);
5715 if (FD) {
5716 S += '"';
5717 S += field->getNameAsString();
5718 S += '"';
5719 }
5720
5721 if (field->isBitField()) {
5722 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005723#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00005724 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005725#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005726 } else {
5727 QualType qt = field->getType();
5728 getLegacyIntegralTypeEncoding(qt);
5729 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5730 /*OutermostType*/false,
5731 /*EncodingProperty*/false,
5732 /*StructField*/true);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005733#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005734 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005735#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005736 }
5737 }
5738 }
5739}
5740
Mike Stump11289f42009-09-09 15:08:12 +00005741void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005742 std::string& S) const {
5743 if (QT & Decl::OBJC_TQ_In)
5744 S += 'n';
5745 if (QT & Decl::OBJC_TQ_Inout)
5746 S += 'N';
5747 if (QT & Decl::OBJC_TQ_Out)
5748 S += 'o';
5749 if (QT & Decl::OBJC_TQ_Bycopy)
5750 S += 'O';
5751 if (QT & Decl::OBJC_TQ_Byref)
5752 S += 'R';
5753 if (QT & Decl::OBJC_TQ_Oneway)
5754 S += 'V';
5755}
5756
Douglas Gregor3ea72692011-08-12 05:46:01 +00005757TypedefDecl *ASTContext::getObjCIdDecl() const {
5758 if (!ObjCIdDecl) {
5759 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5760 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005761 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00005762 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00005763 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005764}
5765
Douglas Gregor52e02802011-08-12 06:17:30 +00005766TypedefDecl *ASTContext::getObjCSelDecl() const {
5767 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005768 QualType T = getPointerType(ObjCBuiltinSelTy);
5769 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00005770 }
5771 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005772}
5773
Douglas Gregor0a586182011-08-12 05:59:41 +00005774TypedefDecl *ASTContext::getObjCClassDecl() const {
5775 if (!ObjCClassDecl) {
5776 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5777 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005778 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00005779 }
Douglas Gregor0a586182011-08-12 05:59:41 +00005780 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005781}
5782
Douglas Gregord53ae832012-01-17 18:09:05 +00005783ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5784 if (!ObjCProtocolClassDecl) {
5785 ObjCProtocolClassDecl
5786 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5787 SourceLocation(),
5788 &Idents.get("Protocol"),
5789 /*PrevDecl=*/0,
5790 SourceLocation(), true);
5791 }
5792
5793 return ObjCProtocolClassDecl;
5794}
5795
Meador Inge5d3fb222012-06-16 03:34:49 +00005796//===----------------------------------------------------------------------===//
5797// __builtin_va_list Construction Functions
5798//===----------------------------------------------------------------------===//
5799
5800static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5801 // typedef char* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005802 QualType T = Context->getPointerType(Context->CharTy);
5803 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005804}
5805
5806static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5807 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005808 QualType T = Context->getPointerType(Context->VoidTy);
5809 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005810}
5811
Tim Northover9bb857a2013-01-31 12:13:10 +00005812static TypedefDecl *
5813CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005814 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00005815 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005816 if (Context->getLangOpts().CPlusPlus) {
5817 // namespace std { struct __va_list {
5818 NamespaceDecl *NS;
5819 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5820 Context->getTranslationUnitDecl(),
5821 /*Inline*/false, SourceLocation(),
5822 SourceLocation(), &Context->Idents.get("std"),
5823 /*PrevDecl*/0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005824 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00005825 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00005826 }
5827
5828 VaListTagDecl->startDefinition();
5829
5830 const size_t NumFields = 5;
5831 QualType FieldTypes[NumFields];
5832 const char *FieldNames[NumFields];
5833
5834 // void *__stack;
5835 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5836 FieldNames[0] = "__stack";
5837
5838 // void *__gr_top;
5839 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5840 FieldNames[1] = "__gr_top";
5841
5842 // void *__vr_top;
5843 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5844 FieldNames[2] = "__vr_top";
5845
5846 // int __gr_offs;
5847 FieldTypes[3] = Context->IntTy;
5848 FieldNames[3] = "__gr_offs";
5849
5850 // int __vr_offs;
5851 FieldTypes[4] = Context->IntTy;
5852 FieldNames[4] = "__vr_offs";
5853
5854 // Create fields
5855 for (unsigned i = 0; i < NumFields; ++i) {
5856 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5857 VaListTagDecl,
5858 SourceLocation(),
5859 SourceLocation(),
5860 &Context->Idents.get(FieldNames[i]),
5861 FieldTypes[i], /*TInfo=*/0,
5862 /*BitWidth=*/0,
5863 /*Mutable=*/false,
5864 ICIS_NoInit);
5865 Field->setAccess(AS_public);
5866 VaListTagDecl->addDecl(Field);
5867 }
5868 VaListTagDecl->completeDefinition();
5869 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5870 Context->VaListTagTy = VaListTagType;
5871
5872 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005873 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005874}
5875
Meador Inge5d3fb222012-06-16 03:34:49 +00005876static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5877 // typedef struct __va_list_tag {
5878 RecordDecl *VaListTagDecl;
5879
Alp Toker2dea15b2013-12-17 01:22:38 +00005880 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005881 VaListTagDecl->startDefinition();
5882
5883 const size_t NumFields = 5;
5884 QualType FieldTypes[NumFields];
5885 const char *FieldNames[NumFields];
5886
5887 // unsigned char gpr;
5888 FieldTypes[0] = Context->UnsignedCharTy;
5889 FieldNames[0] = "gpr";
5890
5891 // unsigned char fpr;
5892 FieldTypes[1] = Context->UnsignedCharTy;
5893 FieldNames[1] = "fpr";
5894
5895 // unsigned short reserved;
5896 FieldTypes[2] = Context->UnsignedShortTy;
5897 FieldNames[2] = "reserved";
5898
5899 // void* overflow_arg_area;
5900 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5901 FieldNames[3] = "overflow_arg_area";
5902
5903 // void* reg_save_area;
5904 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5905 FieldNames[4] = "reg_save_area";
5906
5907 // Create fields
5908 for (unsigned i = 0; i < NumFields; ++i) {
5909 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5910 SourceLocation(),
5911 SourceLocation(),
5912 &Context->Idents.get(FieldNames[i]),
5913 FieldTypes[i], /*TInfo=*/0,
5914 /*BitWidth=*/0,
5915 /*Mutable=*/false,
5916 ICIS_NoInit);
5917 Field->setAccess(AS_public);
5918 VaListTagDecl->addDecl(Field);
5919 }
5920 VaListTagDecl->completeDefinition();
5921 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005922 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005923
5924 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00005925 TypedefDecl *VaListTagTypedefDecl =
5926 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
5927
Meador Inge5d3fb222012-06-16 03:34:49 +00005928 QualType VaListTagTypedefType =
5929 Context->getTypedefType(VaListTagTypedefDecl);
5930
5931 // typedef __va_list_tag __builtin_va_list[1];
5932 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5933 QualType VaListTagArrayType
5934 = Context->getConstantArrayType(VaListTagTypedefType,
5935 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005936 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005937}
5938
5939static TypedefDecl *
5940CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5941 // typedef struct __va_list_tag {
5942 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00005943 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005944 VaListTagDecl->startDefinition();
5945
5946 const size_t NumFields = 4;
5947 QualType FieldTypes[NumFields];
5948 const char *FieldNames[NumFields];
5949
5950 // unsigned gp_offset;
5951 FieldTypes[0] = Context->UnsignedIntTy;
5952 FieldNames[0] = "gp_offset";
5953
5954 // unsigned fp_offset;
5955 FieldTypes[1] = Context->UnsignedIntTy;
5956 FieldNames[1] = "fp_offset";
5957
5958 // void* overflow_arg_area;
5959 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5960 FieldNames[2] = "overflow_arg_area";
5961
5962 // void* reg_save_area;
5963 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5964 FieldNames[3] = "reg_save_area";
5965
5966 // Create fields
5967 for (unsigned i = 0; i < NumFields; ++i) {
5968 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5969 VaListTagDecl,
5970 SourceLocation(),
5971 SourceLocation(),
5972 &Context->Idents.get(FieldNames[i]),
5973 FieldTypes[i], /*TInfo=*/0,
5974 /*BitWidth=*/0,
5975 /*Mutable=*/false,
5976 ICIS_NoInit);
5977 Field->setAccess(AS_public);
5978 VaListTagDecl->addDecl(Field);
5979 }
5980 VaListTagDecl->completeDefinition();
5981 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005982 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005983
5984 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00005985 TypedefDecl *VaListTagTypedefDecl =
5986 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
5987
Meador Inge5d3fb222012-06-16 03:34:49 +00005988 QualType VaListTagTypedefType =
5989 Context->getTypedefType(VaListTagTypedefDecl);
5990
5991 // typedef __va_list_tag __builtin_va_list[1];
5992 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5993 QualType VaListTagArrayType
5994 = Context->getConstantArrayType(VaListTagTypedefType,
5995 Size, ArrayType::Normal,0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005996 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005997}
5998
5999static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6000 // typedef int __builtin_va_list[4];
6001 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6002 QualType IntArrayType
6003 = Context->getConstantArrayType(Context->IntTy,
6004 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006005 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006006}
6007
Logan Chien57086ce2012-10-10 06:56:20 +00006008static TypedefDecl *
6009CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006010 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006011 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006012 if (Context->getLangOpts().CPlusPlus) {
6013 // namespace std { struct __va_list {
6014 NamespaceDecl *NS;
6015 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6016 Context->getTranslationUnitDecl(),
6017 /*Inline*/false, SourceLocation(),
6018 SourceLocation(), &Context->Idents.get("std"),
6019 /*PrevDecl*/0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006020 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006021 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006022 }
6023
6024 VaListDecl->startDefinition();
6025
6026 // void * __ap;
6027 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6028 VaListDecl,
6029 SourceLocation(),
6030 SourceLocation(),
6031 &Context->Idents.get("__ap"),
6032 Context->getPointerType(Context->VoidTy),
6033 /*TInfo=*/0,
6034 /*BitWidth=*/0,
6035 /*Mutable=*/false,
6036 ICIS_NoInit);
6037 Field->setAccess(AS_public);
6038 VaListDecl->addDecl(Field);
6039
6040 // };
6041 VaListDecl->completeDefinition();
6042
6043 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006044 QualType T = Context->getRecordType(VaListDecl);
6045 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006046}
6047
Ulrich Weigand47445072013-05-06 16:26:41 +00006048static TypedefDecl *
6049CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6050 // typedef struct __va_list_tag {
6051 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006052 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006053 VaListTagDecl->startDefinition();
6054
6055 const size_t NumFields = 4;
6056 QualType FieldTypes[NumFields];
6057 const char *FieldNames[NumFields];
6058
6059 // long __gpr;
6060 FieldTypes[0] = Context->LongTy;
6061 FieldNames[0] = "__gpr";
6062
6063 // long __fpr;
6064 FieldTypes[1] = Context->LongTy;
6065 FieldNames[1] = "__fpr";
6066
6067 // void *__overflow_arg_area;
6068 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6069 FieldNames[2] = "__overflow_arg_area";
6070
6071 // void *__reg_save_area;
6072 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6073 FieldNames[3] = "__reg_save_area";
6074
6075 // Create fields
6076 for (unsigned i = 0; i < NumFields; ++i) {
6077 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6078 VaListTagDecl,
6079 SourceLocation(),
6080 SourceLocation(),
6081 &Context->Idents.get(FieldNames[i]),
6082 FieldTypes[i], /*TInfo=*/0,
6083 /*BitWidth=*/0,
6084 /*Mutable=*/false,
6085 ICIS_NoInit);
6086 Field->setAccess(AS_public);
6087 VaListTagDecl->addDecl(Field);
6088 }
6089 VaListTagDecl->completeDefinition();
6090 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6091 Context->VaListTagTy = VaListTagType;
6092
6093 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006094 TypedefDecl *VaListTagTypedefDecl =
6095 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006096 QualType VaListTagTypedefType =
6097 Context->getTypedefType(VaListTagTypedefDecl);
6098
6099 // typedef __va_list_tag __builtin_va_list[1];
6100 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6101 QualType VaListTagArrayType
6102 = Context->getConstantArrayType(VaListTagTypedefType,
6103 Size, ArrayType::Normal,0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006104
Alp Toker56b5cc92013-12-15 10:36:26 +00006105 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006106}
6107
Meador Inge5d3fb222012-06-16 03:34:49 +00006108static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6109 TargetInfo::BuiltinVaListKind Kind) {
6110 switch (Kind) {
6111 case TargetInfo::CharPtrBuiltinVaList:
6112 return CreateCharPtrBuiltinVaListDecl(Context);
6113 case TargetInfo::VoidPtrBuiltinVaList:
6114 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006115 case TargetInfo::AArch64ABIBuiltinVaList:
6116 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006117 case TargetInfo::PowerABIBuiltinVaList:
6118 return CreatePowerABIBuiltinVaListDecl(Context);
6119 case TargetInfo::X86_64ABIBuiltinVaList:
6120 return CreateX86_64ABIBuiltinVaListDecl(Context);
6121 case TargetInfo::PNaClABIBuiltinVaList:
6122 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006123 case TargetInfo::AAPCSABIBuiltinVaList:
6124 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006125 case TargetInfo::SystemZBuiltinVaList:
6126 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006127 }
6128
6129 llvm_unreachable("Unhandled __builtin_va_list type kind");
6130}
6131
6132TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006133 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006134 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006135 assert(BuiltinVaListDecl->isImplicit());
6136 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006137
6138 return BuiltinVaListDecl;
6139}
6140
Meador Ingecfb60902012-07-01 15:57:25 +00006141QualType ASTContext::getVaListTagType() const {
6142 // Force the creation of VaListTagTy by building the __builtin_va_list
6143 // declaration.
6144 if (VaListTagTy.isNull())
6145 (void) getBuiltinVaListDecl();
6146
6147 return VaListTagTy;
6148}
6149
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006150void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006151 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006152 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006153
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006154 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006155}
6156
John McCalld28ae272009-12-02 08:04:21 +00006157/// \brief Retrieve the template name that corresponds to a non-empty
6158/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006159TemplateName
6160ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6161 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006162 unsigned size = End - Begin;
6163 assert(size > 1 && "set is not overloaded!");
6164
6165 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6166 size * sizeof(FunctionTemplateDecl*));
6167 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6168
6169 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006170 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006171 NamedDecl *D = *I;
6172 assert(isa<FunctionTemplateDecl>(D) ||
6173 (isa<UsingShadowDecl>(D) &&
6174 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6175 *Storage++ = D;
6176 }
6177
6178 return TemplateName(OT);
6179}
6180
Douglas Gregordc572a32009-03-30 22:58:21 +00006181/// \brief Retrieve the template name that represents a qualified
6182/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006183TemplateName
6184ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6185 bool TemplateKeyword,
6186 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006187 assert(NNS && "Missing nested-name-specifier in qualified template name");
6188
Douglas Gregorc42075a2010-02-04 18:10:26 +00006189 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006190 llvm::FoldingSetNodeID ID;
6191 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6192
6193 void *InsertPos = 0;
6194 QualifiedTemplateName *QTN =
6195 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6196 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006197 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6198 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006199 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6200 }
6201
6202 return TemplateName(QTN);
6203}
6204
6205/// \brief Retrieve the template name that represents a dependent
6206/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006207TemplateName
6208ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6209 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006210 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006211 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006212
6213 llvm::FoldingSetNodeID ID;
6214 DependentTemplateName::Profile(ID, NNS, Name);
6215
6216 void *InsertPos = 0;
6217 DependentTemplateName *QTN =
6218 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6219
6220 if (QTN)
6221 return TemplateName(QTN);
6222
6223 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6224 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006225 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6226 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006227 } else {
6228 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006229 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6230 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006231 DependentTemplateName *CheckQTN =
6232 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6233 assert(!CheckQTN && "Dependent type name canonicalization broken");
6234 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006235 }
6236
6237 DependentTemplateNames.InsertNode(QTN, InsertPos);
6238 return TemplateName(QTN);
6239}
6240
Douglas Gregor71395fa2009-11-04 00:56:37 +00006241/// \brief Retrieve the template name that represents a dependent
6242/// template name such as \c MetaFun::template operator+.
6243TemplateName
6244ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006245 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006246 assert((!NNS || NNS->isDependent()) &&
6247 "Nested name specifier must be dependent");
6248
6249 llvm::FoldingSetNodeID ID;
6250 DependentTemplateName::Profile(ID, NNS, Operator);
6251
6252 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006253 DependentTemplateName *QTN
6254 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006255
6256 if (QTN)
6257 return TemplateName(QTN);
6258
6259 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6260 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006261 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6262 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006263 } else {
6264 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006265 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6266 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006267
6268 DependentTemplateName *CheckQTN
6269 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6270 assert(!CheckQTN && "Dependent template name canonicalization broken");
6271 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006272 }
6273
6274 DependentTemplateNames.InsertNode(QTN, InsertPos);
6275 return TemplateName(QTN);
6276}
6277
Douglas Gregor5590be02011-01-15 06:45:20 +00006278TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006279ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6280 TemplateName replacement) const {
6281 llvm::FoldingSetNodeID ID;
6282 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6283
6284 void *insertPos = 0;
6285 SubstTemplateTemplateParmStorage *subst
6286 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6287
6288 if (!subst) {
6289 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6290 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6291 }
6292
6293 return TemplateName(subst);
6294}
6295
6296TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006297ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6298 const TemplateArgument &ArgPack) const {
6299 ASTContext &Self = const_cast<ASTContext &>(*this);
6300 llvm::FoldingSetNodeID ID;
6301 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6302
6303 void *InsertPos = 0;
6304 SubstTemplateTemplateParmPackStorage *Subst
6305 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6306
6307 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006308 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006309 ArgPack.pack_size(),
6310 ArgPack.pack_begin());
6311 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6312 }
6313
6314 return TemplateName(Subst);
6315}
6316
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006317/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006318/// TargetInfo, produce the corresponding type. The unsigned @p Type
6319/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006320CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006321 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006322 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006323 case TargetInfo::SignedChar: return SignedCharTy;
6324 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006325 case TargetInfo::SignedShort: return ShortTy;
6326 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6327 case TargetInfo::SignedInt: return IntTy;
6328 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6329 case TargetInfo::SignedLong: return LongTy;
6330 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6331 case TargetInfo::SignedLongLong: return LongLongTy;
6332 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6333 }
6334
David Blaikie83d382b2011-09-23 05:06:16 +00006335 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006336}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006337
6338//===----------------------------------------------------------------------===//
6339// Type Predicates.
6340//===----------------------------------------------------------------------===//
6341
Fariborz Jahanian96207692009-02-18 21:49:28 +00006342/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6343/// garbage collection attribute.
6344///
John McCall553d45a2011-01-12 00:34:59 +00006345Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006346 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006347 return Qualifiers::GCNone;
6348
David Blaikiebbafb8a2012-03-11 07:00:24 +00006349 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006350 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6351
6352 // Default behaviour under objective-C's gc is for ObjC pointers
6353 // (or pointers to them) be treated as though they were declared
6354 // as __strong.
6355 if (GCAttrs == Qualifiers::GCNone) {
6356 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6357 return Qualifiers::Strong;
6358 else if (Ty->isPointerType())
6359 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6360 } else {
6361 // It's not valid to set GC attributes on anything that isn't a
6362 // pointer.
6363#ifndef NDEBUG
6364 QualType CT = Ty->getCanonicalTypeInternal();
6365 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6366 CT = AT->getElementType();
6367 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6368#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006369 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006370 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006371}
6372
Chris Lattner49af6a42008-04-07 06:51:04 +00006373//===----------------------------------------------------------------------===//
6374// Type Compatibility Testing
6375//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006376
Mike Stump11289f42009-09-09 15:08:12 +00006377/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006378/// compatible.
6379static bool areCompatVectorTypes(const VectorType *LHS,
6380 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006381 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006382 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006383 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006384}
6385
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006386bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6387 QualType SecondVec) {
6388 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6389 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6390
6391 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6392 return true;
6393
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006394 // Treat Neon vector types and most AltiVec vector types as if they are the
6395 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006396 const VectorType *First = FirstVec->getAs<VectorType>();
6397 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006398 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006399 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006400 First->getVectorKind() != VectorType::AltiVecPixel &&
6401 First->getVectorKind() != VectorType::AltiVecBool &&
6402 Second->getVectorKind() != VectorType::AltiVecPixel &&
6403 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006404 return true;
6405
6406 return false;
6407}
6408
Steve Naroff8e6aee52009-07-23 01:01:38 +00006409//===----------------------------------------------------------------------===//
6410// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6411//===----------------------------------------------------------------------===//
6412
6413/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6414/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006415bool
6416ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6417 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006418 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006419 return true;
6420 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6421 E = rProto->protocol_end(); PI != E; ++PI)
6422 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6423 return true;
6424 return false;
6425}
6426
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006427/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6428/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006429bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6430 QualType rhs) {
6431 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6432 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6433 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6434
6435 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6436 E = lhsQID->qual_end(); I != E; ++I) {
6437 bool match = false;
6438 ObjCProtocolDecl *lhsProto = *I;
6439 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6440 E = rhsOPT->qual_end(); J != E; ++J) {
6441 ObjCProtocolDecl *rhsProto = *J;
6442 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6443 match = true;
6444 break;
6445 }
6446 }
6447 if (!match)
6448 return false;
6449 }
6450 return true;
6451}
6452
Steve Naroff8e6aee52009-07-23 01:01:38 +00006453/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6454/// ObjCQualifiedIDType.
6455bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6456 bool compare) {
6457 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006458 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006459 lhs->isObjCIdType() || lhs->isObjCClassType())
6460 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006461 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006462 rhs->isObjCIdType() || rhs->isObjCClassType())
6463 return true;
6464
6465 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006466 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006467
Steve Naroff8e6aee52009-07-23 01:01:38 +00006468 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006469
Steve Naroff8e6aee52009-07-23 01:01:38 +00006470 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006471 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006472 // make sure we check the class hierarchy.
6473 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6474 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6475 E = lhsQID->qual_end(); I != E; ++I) {
6476 // when comparing an id<P> on lhs with a static type on rhs,
6477 // see if static class implements all of id's protocols, directly or
6478 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006479 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006480 return false;
6481 }
6482 }
6483 // If there are no qualifiers and no interface, we have an 'id'.
6484 return true;
6485 }
Mike Stump11289f42009-09-09 15:08:12 +00006486 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006487 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6488 E = lhsQID->qual_end(); I != E; ++I) {
6489 ObjCProtocolDecl *lhsProto = *I;
6490 bool match = false;
6491
6492 // when comparing an id<P> on lhs with a static type on rhs,
6493 // see if static class implements all of id's protocols, directly or
6494 // through its super class and categories.
6495 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6496 E = rhsOPT->qual_end(); J != E; ++J) {
6497 ObjCProtocolDecl *rhsProto = *J;
6498 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6499 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6500 match = true;
6501 break;
6502 }
6503 }
Mike Stump11289f42009-09-09 15:08:12 +00006504 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006505 // make sure we check the class hierarchy.
6506 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6507 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6508 E = lhsQID->qual_end(); I != E; ++I) {
6509 // when comparing an id<P> on lhs with a static type on rhs,
6510 // see if static class implements all of id's protocols, directly or
6511 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006512 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006513 match = true;
6514 break;
6515 }
6516 }
6517 }
6518 if (!match)
6519 return false;
6520 }
Mike Stump11289f42009-09-09 15:08:12 +00006521
Steve Naroff8e6aee52009-07-23 01:01:38 +00006522 return true;
6523 }
Mike Stump11289f42009-09-09 15:08:12 +00006524
Steve Naroff8e6aee52009-07-23 01:01:38 +00006525 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6526 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6527
Mike Stump11289f42009-09-09 15:08:12 +00006528 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006529 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006530 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006531 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6532 E = lhsOPT->qual_end(); I != E; ++I) {
6533 ObjCProtocolDecl *lhsProto = *I;
6534 bool match = false;
6535
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006536 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006537 // see if static class implements all of id's protocols, directly or
6538 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006539 // First, lhs protocols in the qualifier list must be found, direct
6540 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006541 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6542 E = rhsQID->qual_end(); J != E; ++J) {
6543 ObjCProtocolDecl *rhsProto = *J;
6544 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6545 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6546 match = true;
6547 break;
6548 }
6549 }
6550 if (!match)
6551 return false;
6552 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006553
6554 // Static class's protocols, or its super class or category protocols
6555 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6556 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6557 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6558 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6559 // This is rather dubious but matches gcc's behavior. If lhs has
6560 // no type qualifier and its class has no static protocol(s)
6561 // assume that it is mismatch.
6562 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6563 return false;
6564 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6565 LHSInheritedProtocols.begin(),
6566 E = LHSInheritedProtocols.end(); I != E; ++I) {
6567 bool match = false;
6568 ObjCProtocolDecl *lhsProto = (*I);
6569 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6570 E = rhsQID->qual_end(); J != E; ++J) {
6571 ObjCProtocolDecl *rhsProto = *J;
6572 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6573 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6574 match = true;
6575 break;
6576 }
6577 }
6578 if (!match)
6579 return false;
6580 }
6581 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006582 return true;
6583 }
6584 return false;
6585}
6586
Eli Friedman47f77112008-08-22 00:56:42 +00006587/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006588/// compatible for assignment from RHS to LHS. This handles validation of any
6589/// protocol qualifiers on the LHS or RHS.
6590///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006591bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6592 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006593 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6594 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6595
Steve Naroff1329fa02009-07-15 18:40:39 +00006596 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006597 if (LHS->isObjCUnqualifiedIdOrClass() ||
6598 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006599 return true;
6600
John McCall8b07ec22010-05-15 11:32:37 +00006601 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006602 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6603 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006604 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006605
6606 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6607 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6608 QualType(RHSOPT,0));
6609
John McCall8b07ec22010-05-15 11:32:37 +00006610 // If we have 2 user-defined types, fall into that path.
6611 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006612 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006613
Steve Naroff8e6aee52009-07-23 01:01:38 +00006614 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006615}
6616
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006617/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006618/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006619/// arguments in block literals. When passed as arguments, passing 'A*' where
6620/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6621/// not OK. For the return type, the opposite is not OK.
6622bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6623 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006624 const ObjCObjectPointerType *RHSOPT,
6625 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006626 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006627 return true;
6628
6629 if (LHSOPT->isObjCBuiltinType()) {
6630 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6631 }
6632
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006633 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006634 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6635 QualType(RHSOPT,0),
6636 false);
6637
6638 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6639 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6640 if (LHS && RHS) { // We have 2 user-defined types.
6641 if (LHS != RHS) {
6642 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006643 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006644 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006645 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006646 }
6647 else
6648 return true;
6649 }
6650 return false;
6651}
6652
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006653/// getIntersectionOfProtocols - This routine finds the intersection of set
6654/// of protocols inherited from two distinct objective-c pointer objects.
6655/// It is used to build composite qualifier list of the composite type of
6656/// the conditional expression involving two objective-c pointer objects.
6657static
6658void getIntersectionOfProtocols(ASTContext &Context,
6659 const ObjCObjectPointerType *LHSOPT,
6660 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006661 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006662
John McCall8b07ec22010-05-15 11:32:37 +00006663 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6664 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6665 assert(LHS->getInterface() && "LHS must have an interface base");
6666 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006667
6668 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6669 unsigned LHSNumProtocols = LHS->getNumProtocols();
6670 if (LHSNumProtocols > 0)
6671 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6672 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006673 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006674 Context.CollectInheritedProtocols(LHS->getInterface(),
6675 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006676 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6677 LHSInheritedProtocols.end());
6678 }
6679
6680 unsigned RHSNumProtocols = RHS->getNumProtocols();
6681 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006682 ObjCProtocolDecl **RHSProtocols =
6683 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006684 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6685 if (InheritedProtocolSet.count(RHSProtocols[i]))
6686 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006687 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006688 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006689 Context.CollectInheritedProtocols(RHS->getInterface(),
6690 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006691 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6692 RHSInheritedProtocols.begin(),
6693 E = RHSInheritedProtocols.end(); I != E; ++I)
6694 if (InheritedProtocolSet.count((*I)))
6695 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006696 }
6697}
6698
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006699/// areCommonBaseCompatible - Returns common base class of the two classes if
6700/// one found. Note that this is O'2 algorithm. But it will be called as the
6701/// last type comparison in a ?-exp of ObjC pointer types before a
6702/// warning is issued. So, its invokation is extremely rare.
6703QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006704 const ObjCObjectPointerType *Lptr,
6705 const ObjCObjectPointerType *Rptr) {
6706 const ObjCObjectType *LHS = Lptr->getObjectType();
6707 const ObjCObjectType *RHS = Rptr->getObjectType();
6708 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6709 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006710 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006711 return QualType();
6712
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006713 do {
John McCall8b07ec22010-05-15 11:32:37 +00006714 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006715 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006716 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006717 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6718
6719 QualType Result = QualType(LHS, 0);
6720 if (!Protocols.empty())
6721 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6722 Result = getObjCObjectPointerType(Result);
6723 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006724 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006725 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006726
6727 return QualType();
6728}
6729
John McCall8b07ec22010-05-15 11:32:37 +00006730bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6731 const ObjCObjectType *RHS) {
6732 assert(LHS->getInterface() && "LHS is not an interface type");
6733 assert(RHS->getInterface() && "RHS is not an interface type");
6734
Chris Lattner49af6a42008-04-07 06:51:04 +00006735 // Verify that the base decls are compatible: the RHS must be a subclass of
6736 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006737 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006738 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006739
Chris Lattner49af6a42008-04-07 06:51:04 +00006740 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6741 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006742 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006743 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006744
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006745 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6746 // more detailed analysis is required.
6747 if (RHS->getNumProtocols() == 0) {
6748 // OK, if LHS is a superclass of RHS *and*
6749 // this superclass is assignment compatible with LHS.
6750 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006751 bool IsSuperClass =
6752 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6753 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006754 // OK if conversion of LHS to SuperClass results in narrowing of types
6755 // ; i.e., SuperClass may implement at least one of the protocols
6756 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6757 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6758 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006759 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006760 // If super class has no protocols, it is not a match.
6761 if (SuperClassInheritedProtocols.empty())
6762 return false;
6763
6764 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6765 LHSPE = LHS->qual_end();
6766 LHSPI != LHSPE; LHSPI++) {
6767 bool SuperImplementsProtocol = false;
6768 ObjCProtocolDecl *LHSProto = (*LHSPI);
6769
6770 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6771 SuperClassInheritedProtocols.begin(),
6772 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6773 ObjCProtocolDecl *SuperClassProto = (*I);
6774 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6775 SuperImplementsProtocol = true;
6776 break;
6777 }
6778 }
6779 if (!SuperImplementsProtocol)
6780 return false;
6781 }
6782 return true;
6783 }
6784 return false;
6785 }
Mike Stump11289f42009-09-09 15:08:12 +00006786
John McCall8b07ec22010-05-15 11:32:37 +00006787 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6788 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006789 LHSPI != LHSPE; LHSPI++) {
6790 bool RHSImplementsProtocol = false;
6791
6792 // If the RHS doesn't implement the protocol on the left, the types
6793 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006794 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6795 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006796 RHSPI != RHSPE; RHSPI++) {
6797 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006798 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006799 break;
6800 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006801 }
6802 // FIXME: For better diagnostics, consider passing back the protocol name.
6803 if (!RHSImplementsProtocol)
6804 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006805 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006806 // The RHS implements all protocols listed on the LHS.
6807 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006808}
6809
Steve Naroffb7605152009-02-12 17:52:19 +00006810bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6811 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006812 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6813 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006814
Steve Naroff7cae42b2009-07-10 23:34:53 +00006815 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006816 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006817
6818 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6819 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006820}
6821
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006822bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6823 return canAssignObjCInterfaces(
6824 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6825 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6826}
6827
Mike Stump11289f42009-09-09 15:08:12 +00006828/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006829/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006830/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006831/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006832bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6833 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006834 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006835 return hasSameType(LHS, RHS);
6836
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006837 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006838}
6839
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006840bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006841 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006842}
6843
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006844bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6845 return !mergeTypes(LHS, RHS, true).isNull();
6846}
6847
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006848/// mergeTransparentUnionType - if T is a transparent union type and a member
6849/// of T is compatible with SubType, return the merged type, else return
6850/// QualType()
6851QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6852 bool OfBlockPointer,
6853 bool Unqualified) {
6854 if (const RecordType *UT = T->getAsUnionType()) {
6855 RecordDecl *UD = UT->getDecl();
6856 if (UD->hasAttr<TransparentUnionAttr>()) {
6857 for (RecordDecl::field_iterator it = UD->field_begin(),
6858 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006859 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006860 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6861 if (!MT.isNull())
6862 return MT;
6863 }
6864 }
6865 }
6866
6867 return QualType();
6868}
6869
Alp Toker9cacbab2014-01-20 20:26:09 +00006870/// mergeFunctionParameterTypes - merge two types which appear as function
6871/// parameter types
6872QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
6873 bool OfBlockPointer,
6874 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006875 // GNU extension: two types are compatible if they appear as a function
6876 // argument, one of the types is a transparent union type and the other
6877 // type is compatible with a union member
6878 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6879 Unqualified);
6880 if (!lmerge.isNull())
6881 return lmerge;
6882
6883 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6884 Unqualified);
6885 if (!rmerge.isNull())
6886 return rmerge;
6887
6888 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6889}
6890
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006891QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006892 bool OfBlockPointer,
6893 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006894 const FunctionType *lbase = lhs->getAs<FunctionType>();
6895 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006896 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6897 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006898 bool allLTypes = true;
6899 bool allRTypes = true;
6900
6901 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006902 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006903 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00006904 QualType RHS = rbase->getReturnType();
6905 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00006906 bool UnqualifiedResult = Unqualified;
6907 if (!UnqualifiedResult)
6908 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006909 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006910 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006911 else
Alp Toker314cc812014-01-25 16:55:45 +00006912 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00006913 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006914 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006915
6916 if (Unqualified)
6917 retType = retType.getUnqualifiedType();
6918
Alp Toker314cc812014-01-25 16:55:45 +00006919 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
6920 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006921 if (Unqualified) {
6922 LRetType = LRetType.getUnqualifiedType();
6923 RRetType = RRetType.getUnqualifiedType();
6924 }
6925
6926 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006927 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006928 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006929 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006930
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006931 // FIXME: double check this
6932 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6933 // rbase->getRegParmAttr() != 0 &&
6934 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006935 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6936 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006937
Douglas Gregor8c940862010-01-18 17:14:39 +00006938 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00006939 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00006940 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006941
John McCall8c6b56f2010-12-15 01:06:38 +00006942 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006943 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6944 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006945 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6946 return QualType();
6947
John McCall31168b02011-06-15 23:02:42 +00006948 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6949 return QualType();
6950
John McCall8c6b56f2010-12-15 01:06:38 +00006951 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6952 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006953
Rafael Espindola8778c282012-11-29 16:09:03 +00006954 if (lbaseInfo.getNoReturn() != NoReturn)
6955 allLTypes = false;
6956 if (rbaseInfo.getNoReturn() != NoReturn)
6957 allRTypes = false;
6958
John McCall31168b02011-06-15 23:02:42 +00006959 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006960
Eli Friedman47f77112008-08-22 00:56:42 +00006961 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006962 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6963 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00006964 // Compatible functions must have the same number of parameters
6965 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00006966 return QualType();
6967
6968 // Variadic and non-variadic functions aren't compatible
6969 if (lproto->isVariadic() != rproto->isVariadic())
6970 return QualType();
6971
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006972 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6973 return QualType();
6974
Fariborz Jahanian97676972011-09-28 21:52:05 +00006975 if (LangOpts.ObjCAutoRefCount &&
6976 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6977 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00006978
6979 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006980 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00006981 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
6982 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
6983 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
6984 QualType paramType = mergeFunctionParameterTypes(
6985 lParamType, rParamType, OfBlockPointer, Unqualified);
6986 if (paramType.isNull())
6987 return QualType();
6988
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006989 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00006990 paramType = paramType.getUnqualifiedType();
6991
6992 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006993 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00006994 lParamType = lParamType.getUnqualifiedType();
6995 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006996 }
Alp Toker601b22c2014-01-21 23:35:24 +00006997
6998 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00006999 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007000 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007001 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007002 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007003
Eli Friedman47f77112008-08-22 00:56:42 +00007004 if (allLTypes) return lhs;
7005 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007006
7007 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7008 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007009 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007010 }
7011
7012 if (lproto) allRTypes = false;
7013 if (rproto) allLTypes = false;
7014
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007015 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007016 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007017 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007018 if (proto->isVariadic()) return QualType();
7019 // Check that the types are compatible with the types that
7020 // would result from default argument promotions (C99 6.7.5.3p15).
7021 // The only types actually affected are promotable integer
7022 // types and floats, which would be passed as a different
7023 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007024 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7025 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007026
Eli Friedman448ce402012-08-30 00:44:15 +00007027 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007028 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007029 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7030 paramTy = Enum->getDecl()->getIntegerType();
7031 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007032 return QualType();
7033 }
Alp Toker601b22c2014-01-21 23:35:24 +00007034
7035 if (paramTy->isPromotableIntegerType() ||
7036 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007037 return QualType();
7038 }
7039
7040 if (allLTypes) return lhs;
7041 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007042
7043 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7044 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007045 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007046 }
7047
7048 if (allLTypes) return lhs;
7049 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007050 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007051}
7052
John McCall433c2e62013-03-21 00:10:07 +00007053/// Given that we have an enum type and a non-enum type, try to merge them.
7054static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7055 QualType other, bool isBlockReturnType) {
7056 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7057 // a signed integer type, or an unsigned integer type.
7058 // Compatibility is based on the underlying type, not the promotion
7059 // type.
7060 QualType underlyingType = ET->getDecl()->getIntegerType();
7061 if (underlyingType.isNull()) return QualType();
7062 if (Context.hasSameType(underlyingType, other))
7063 return other;
7064
7065 // In block return types, we're more permissive and accept any
7066 // integral type of the same size.
7067 if (isBlockReturnType && other->isIntegerType() &&
7068 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7069 return other;
7070
7071 return QualType();
7072}
7073
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007074QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007075 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007076 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007077 // C++ [expr]: If an expression initially has the type "reference to T", the
7078 // type is adjusted to "T" prior to any further analysis, the expression
7079 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007080 // expression is an lvalue unless the reference is an rvalue reference and
7081 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007082 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7083 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007084
7085 if (Unqualified) {
7086 LHS = LHS.getUnqualifiedType();
7087 RHS = RHS.getUnqualifiedType();
7088 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007089
Eli Friedman47f77112008-08-22 00:56:42 +00007090 QualType LHSCan = getCanonicalType(LHS),
7091 RHSCan = getCanonicalType(RHS);
7092
7093 // If two types are identical, they are compatible.
7094 if (LHSCan == RHSCan)
7095 return LHS;
7096
John McCall8ccfcb52009-09-24 19:53:00 +00007097 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007098 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7099 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007100 if (LQuals != RQuals) {
7101 // If any of these qualifiers are different, we have a type
7102 // mismatch.
7103 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007104 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7105 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007106 return QualType();
7107
7108 // Exactly one GC qualifier difference is allowed: __strong is
7109 // okay if the other type has no GC qualifier but is an Objective
7110 // C object pointer (i.e. implicitly strong by default). We fix
7111 // this by pretending that the unqualified type was actually
7112 // qualified __strong.
7113 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7114 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7115 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7116
7117 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7118 return QualType();
7119
7120 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7121 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7122 }
7123 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7124 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7125 }
Eli Friedman47f77112008-08-22 00:56:42 +00007126 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007127 }
7128
7129 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007130
Eli Friedmandcca6332009-06-01 01:22:52 +00007131 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7132 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007133
Chris Lattnerfd652912008-01-14 05:45:46 +00007134 // We want to consider the two function types to be the same for these
7135 // comparisons, just force one to the other.
7136 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7137 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007138
7139 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007140 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7141 LHSClass = Type::ConstantArray;
7142 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7143 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007144
John McCall8b07ec22010-05-15 11:32:37 +00007145 // ObjCInterfaces are just specialized ObjCObjects.
7146 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7147 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7148
Nate Begemance4d7fc2008-04-18 23:10:10 +00007149 // Canonicalize ExtVector -> Vector.
7150 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7151 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007152
Chris Lattner95554662008-04-07 05:43:21 +00007153 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007154 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007155 // Note that we only have special rules for turning block enum
7156 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007157 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007158 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007159 }
John McCall9dd450b2009-09-21 23:43:11 +00007160 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007161 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007162 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007163 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007164 if (OfBlockPointer && !BlockReturnType) {
7165 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7166 return LHS;
7167 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7168 return RHS;
7169 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007170
Eli Friedman47f77112008-08-22 00:56:42 +00007171 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007172 }
Eli Friedman47f77112008-08-22 00:56:42 +00007173
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007174 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007175 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007176#define TYPE(Class, Base)
7177#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007178#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007179#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7180#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7181#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007182 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007183
Richard Smith27d807c2013-04-30 13:56:41 +00007184 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007185 case Type::LValueReference:
7186 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007187 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007188 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007189
John McCall8b07ec22010-05-15 11:32:37 +00007190 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007191 case Type::IncompleteArray:
7192 case Type::VariableArray:
7193 case Type::FunctionProto:
7194 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007195 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007196
Chris Lattnerfd652912008-01-14 05:45:46 +00007197 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007198 {
7199 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007200 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7201 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007202 if (Unqualified) {
7203 LHSPointee = LHSPointee.getUnqualifiedType();
7204 RHSPointee = RHSPointee.getUnqualifiedType();
7205 }
7206 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7207 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007208 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007209 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007210 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007211 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007212 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007213 return getPointerType(ResultType);
7214 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007215 case Type::BlockPointer:
7216 {
7217 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007218 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7219 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007220 if (Unqualified) {
7221 LHSPointee = LHSPointee.getUnqualifiedType();
7222 RHSPointee = RHSPointee.getUnqualifiedType();
7223 }
7224 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7225 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007226 if (ResultType.isNull()) return QualType();
7227 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7228 return LHS;
7229 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7230 return RHS;
7231 return getBlockPointerType(ResultType);
7232 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007233 case Type::Atomic:
7234 {
7235 // Merge two pointer types, while trying to preserve typedef info
7236 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7237 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7238 if (Unqualified) {
7239 LHSValue = LHSValue.getUnqualifiedType();
7240 RHSValue = RHSValue.getUnqualifiedType();
7241 }
7242 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7243 Unqualified);
7244 if (ResultType.isNull()) return QualType();
7245 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7246 return LHS;
7247 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7248 return RHS;
7249 return getAtomicType(ResultType);
7250 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007251 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007252 {
7253 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7254 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7255 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7256 return QualType();
7257
7258 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7259 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007260 if (Unqualified) {
7261 LHSElem = LHSElem.getUnqualifiedType();
7262 RHSElem = RHSElem.getUnqualifiedType();
7263 }
7264
7265 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007266 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007267 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7268 return LHS;
7269 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7270 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007271 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7272 ArrayType::ArraySizeModifier(), 0);
7273 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7274 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007275 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7276 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007277 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7278 return LHS;
7279 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7280 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007281 if (LVAT) {
7282 // FIXME: This isn't correct! But tricky to implement because
7283 // the array's size has to be the size of LHS, but the type
7284 // has to be different.
7285 return LHS;
7286 }
7287 if (RVAT) {
7288 // FIXME: This isn't correct! But tricky to implement because
7289 // the array's size has to be the size of RHS, but the type
7290 // has to be different.
7291 return RHS;
7292 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007293 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7294 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007295 return getIncompleteArrayType(ResultType,
7296 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007297 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007298 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007299 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007300 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007301 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007302 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007303 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007304 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007305 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007306 case Type::Complex:
7307 // Distinct complex types are incompatible.
7308 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007309 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007310 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007311 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7312 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007313 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007314 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007315 case Type::ObjCObject: {
7316 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007317 // FIXME: This should be type compatibility, e.g. whether
7318 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007319 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7320 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7321 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007322 return LHS;
7323
Eli Friedman47f77112008-08-22 00:56:42 +00007324 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007325 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007326 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007327 if (OfBlockPointer) {
7328 if (canAssignObjCInterfacesInBlockPointer(
7329 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007330 RHS->getAs<ObjCObjectPointerType>(),
7331 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007332 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007333 return QualType();
7334 }
John McCall9dd450b2009-09-21 23:43:11 +00007335 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7336 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007337 return LHS;
7338
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007339 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007340 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007341 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007342
David Blaikie8a40f702012-01-17 06:56:22 +00007343 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007344}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007345
Fariborz Jahanian97676972011-09-28 21:52:05 +00007346bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7347 const FunctionProtoType *FromFunctionType,
7348 const FunctionProtoType *ToFunctionType) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007349 if (FromFunctionType->hasAnyConsumedParams() !=
7350 ToFunctionType->hasAnyConsumedParams())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007351 return false;
7352 FunctionProtoType::ExtProtoInfo FromEPI =
7353 FromFunctionType->getExtProtoInfo();
7354 FunctionProtoType::ExtProtoInfo ToEPI =
7355 ToFunctionType->getExtProtoInfo();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007356 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
Alp Toker601b22c2014-01-21 23:35:24 +00007357 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7358 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
Fariborz Jahanian97676972011-09-28 21:52:05 +00007359 return false;
7360 }
7361 return true;
7362}
7363
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007364/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7365/// 'RHS' attributes and returns the merged version; including for function
7366/// return types.
7367QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7368 QualType LHSCan = getCanonicalType(LHS),
7369 RHSCan = getCanonicalType(RHS);
7370 // If two types are identical, they are compatible.
7371 if (LHSCan == RHSCan)
7372 return LHS;
7373 if (RHSCan->isFunctionType()) {
7374 if (!LHSCan->isFunctionType())
7375 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007376 QualType OldReturnType =
7377 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007378 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007379 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007380 QualType ResReturnType =
7381 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7382 if (ResReturnType.isNull())
7383 return QualType();
7384 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7385 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7386 // In either case, use OldReturnType to build the new function type.
7387 const FunctionType *F = LHS->getAs<FunctionType>();
7388 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007389 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7390 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007391 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007392 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007393 return ResultType;
7394 }
7395 }
7396 return QualType();
7397 }
7398
7399 // If the qualifiers are different, the types can still be merged.
7400 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7401 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7402 if (LQuals != RQuals) {
7403 // If any of these qualifiers are different, we have a type mismatch.
7404 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7405 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7406 return QualType();
7407
7408 // Exactly one GC qualifier difference is allowed: __strong is
7409 // okay if the other type has no GC qualifier but is an Objective
7410 // C object pointer (i.e. implicitly strong by default). We fix
7411 // this by pretending that the unqualified type was actually
7412 // qualified __strong.
7413 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7414 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7415 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7416
7417 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7418 return QualType();
7419
7420 if (GC_L == Qualifiers::Strong)
7421 return LHS;
7422 if (GC_R == Qualifiers::Strong)
7423 return RHS;
7424 return QualType();
7425 }
7426
7427 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7428 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7429 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7430 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7431 if (ResQT == LHSBaseQT)
7432 return LHS;
7433 if (ResQT == RHSBaseQT)
7434 return RHS;
7435 }
7436 return QualType();
7437}
7438
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007439//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007440// Integer Predicates
7441//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007442
Jay Foad39c79802011-01-12 09:06:06 +00007443unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007444 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007445 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007446 if (T->isBooleanType())
7447 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007448 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007449 return (unsigned)getTypeSize(T);
7450}
7451
Abramo Bagnara13640492012-09-09 10:21:24 +00007452QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007453 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007454
7455 // Turn <4 x signed int> -> <4 x unsigned int>
7456 if (const VectorType *VTy = T->getAs<VectorType>())
7457 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007458 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007459
7460 // For enums, we return the unsigned version of the base type.
7461 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007462 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007463
7464 const BuiltinType *BTy = T->getAs<BuiltinType>();
7465 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007466 switch (BTy->getKind()) {
7467 case BuiltinType::Char_S:
7468 case BuiltinType::SChar:
7469 return UnsignedCharTy;
7470 case BuiltinType::Short:
7471 return UnsignedShortTy;
7472 case BuiltinType::Int:
7473 return UnsignedIntTy;
7474 case BuiltinType::Long:
7475 return UnsignedLongTy;
7476 case BuiltinType::LongLong:
7477 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007478 case BuiltinType::Int128:
7479 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007480 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007481 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007482 }
7483}
7484
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007485ASTMutationListener::~ASTMutationListener() { }
7486
Richard Smith1fa5d642013-05-11 05:45:24 +00007487void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7488 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007489
7490//===----------------------------------------------------------------------===//
7491// Builtin Type Computation
7492//===----------------------------------------------------------------------===//
7493
7494/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007495/// pointer over the consumed characters. This returns the resultant type. If
7496/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7497/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7498/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007499///
7500/// RequiresICE is filled in on return to indicate whether the value is required
7501/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007502static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007503 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007504 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007505 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007506 // Modifiers.
7507 int HowLong = 0;
7508 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007509 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007510
Chris Lattnerdc226c22010-10-01 22:42:38 +00007511 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007512 bool Done = false;
7513 while (!Done) {
7514 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007515 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007516 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007517 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007518 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007519 case 'S':
7520 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7521 assert(!Signed && "Can't use 'S' modifier multiple times!");
7522 Signed = true;
7523 break;
7524 case 'U':
7525 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7526 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7527 Unsigned = true;
7528 break;
7529 case 'L':
7530 assert(HowLong <= 2 && "Can't have LLLL modifier");
7531 ++HowLong;
7532 break;
7533 }
7534 }
7535
7536 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007537
Chris Lattnerecd79c62009-06-14 00:45:47 +00007538 // Read the base type.
7539 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007540 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007541 case 'v':
7542 assert(HowLong == 0 && !Signed && !Unsigned &&
7543 "Bad modifiers used with 'v'!");
7544 Type = Context.VoidTy;
7545 break;
Jack Carter24bef982013-08-15 15:16:57 +00007546 case 'h':
7547 assert(HowLong == 0 && !Signed && !Unsigned &&
7548 "Bad modifiers used with 'f'!");
7549 Type = Context.HalfTy;
7550 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007551 case 'f':
7552 assert(HowLong == 0 && !Signed && !Unsigned &&
7553 "Bad modifiers used with 'f'!");
7554 Type = Context.FloatTy;
7555 break;
7556 case 'd':
7557 assert(HowLong < 2 && !Signed && !Unsigned &&
7558 "Bad modifiers used with 'd'!");
7559 if (HowLong)
7560 Type = Context.LongDoubleTy;
7561 else
7562 Type = Context.DoubleTy;
7563 break;
7564 case 's':
7565 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7566 if (Unsigned)
7567 Type = Context.UnsignedShortTy;
7568 else
7569 Type = Context.ShortTy;
7570 break;
7571 case 'i':
7572 if (HowLong == 3)
7573 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7574 else if (HowLong == 2)
7575 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7576 else if (HowLong == 1)
7577 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7578 else
7579 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7580 break;
7581 case 'c':
7582 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7583 if (Signed)
7584 Type = Context.SignedCharTy;
7585 else if (Unsigned)
7586 Type = Context.UnsignedCharTy;
7587 else
7588 Type = Context.CharTy;
7589 break;
7590 case 'b': // boolean
7591 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7592 Type = Context.BoolTy;
7593 break;
7594 case 'z': // size_t.
7595 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7596 Type = Context.getSizeType();
7597 break;
7598 case 'F':
7599 Type = Context.getCFConstantStringType();
7600 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007601 case 'G':
7602 Type = Context.getObjCIdType();
7603 break;
7604 case 'H':
7605 Type = Context.getObjCSelType();
7606 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007607 case 'M':
7608 Type = Context.getObjCSuperType();
7609 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007610 case 'a':
7611 Type = Context.getBuiltinVaListType();
7612 assert(!Type.isNull() && "builtin va list type not initialized!");
7613 break;
7614 case 'A':
7615 // This is a "reference" to a va_list; however, what exactly
7616 // this means depends on how va_list is defined. There are two
7617 // different kinds of va_list: ones passed by value, and ones
7618 // passed by reference. An example of a by-value va_list is
7619 // x86, where va_list is a char*. An example of by-ref va_list
7620 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7621 // we want this argument to be a char*&; for x86-64, we want
7622 // it to be a __va_list_tag*.
7623 Type = Context.getBuiltinVaListType();
7624 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007625 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007626 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007627 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007628 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007629 break;
7630 case 'V': {
7631 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007632 unsigned NumElements = strtoul(Str, &End, 10);
7633 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007634 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007635
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007636 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7637 RequiresICE, false);
7638 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007639
7640 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007641 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007642 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007643 break;
7644 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007645 case 'E': {
7646 char *End;
7647
7648 unsigned NumElements = strtoul(Str, &End, 10);
7649 assert(End != Str && "Missing vector size");
7650
7651 Str = End;
7652
7653 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7654 false);
7655 Type = Context.getExtVectorType(ElementType, NumElements);
7656 break;
7657 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007658 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007659 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7660 false);
7661 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007662 Type = Context.getComplexType(ElementType);
7663 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007664 }
7665 case 'Y' : {
7666 Type = Context.getPointerDiffType();
7667 break;
7668 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007669 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007670 Type = Context.getFILEType();
7671 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007672 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007673 return QualType();
7674 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007675 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007676 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007677 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007678 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007679 else
7680 Type = Context.getjmp_bufType();
7681
Mike Stump2adb4da2009-07-28 23:47:15 +00007682 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007683 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007684 return QualType();
7685 }
7686 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007687 case 'K':
7688 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7689 Type = Context.getucontext_tType();
7690
7691 if (Type.isNull()) {
7692 Error = ASTContext::GE_Missing_ucontext;
7693 return QualType();
7694 }
7695 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007696 case 'p':
7697 Type = Context.getProcessIDType();
7698 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007699 }
Mike Stump11289f42009-09-09 15:08:12 +00007700
Chris Lattnerdc226c22010-10-01 22:42:38 +00007701 // If there are modifiers and if we're allowed to parse them, go for it.
7702 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007703 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007704 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007705 default: Done = true; --Str; break;
7706 case '*':
7707 case '&': {
7708 // Both pointers and references can have their pointee types
7709 // qualified with an address space.
7710 char *End;
7711 unsigned AddrSpace = strtoul(Str, &End, 10);
7712 if (End != Str && AddrSpace != 0) {
7713 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7714 Str = End;
7715 }
7716 if (c == '*')
7717 Type = Context.getPointerType(Type);
7718 else
7719 Type = Context.getLValueReferenceType(Type);
7720 break;
7721 }
7722 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7723 case 'C':
7724 Type = Type.withConst();
7725 break;
7726 case 'D':
7727 Type = Context.getVolatileType(Type);
7728 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007729 case 'R':
7730 Type = Type.withRestrict();
7731 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007732 }
7733 }
Chris Lattner84733392010-10-01 07:13:18 +00007734
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007735 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007736 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007737
Chris Lattnerecd79c62009-06-14 00:45:47 +00007738 return Type;
7739}
7740
7741/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007742QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007743 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007744 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007745 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007746
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007747 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007748
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007749 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007750 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007751 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7752 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007753 if (Error != GE_None)
7754 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007755
7756 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7757
Chris Lattnerecd79c62009-06-14 00:45:47 +00007758 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007759 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007760 if (Error != GE_None)
7761 return QualType();
7762
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007763 // If this argument is required to be an IntegerConstantExpression and the
7764 // caller cares, fill in the bitmask we return.
7765 if (RequiresICE && IntegerConstantArgs)
7766 *IntegerConstantArgs |= 1 << ArgTypes.size();
7767
Chris Lattnerecd79c62009-06-14 00:45:47 +00007768 // Do array -> pointer decay. The builtin should use the decayed type.
7769 if (Ty->isArrayType())
7770 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007771
Chris Lattnerecd79c62009-06-14 00:45:47 +00007772 ArgTypes.push_back(Ty);
7773 }
7774
7775 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7776 "'.' should only occur at end of builtin type list!");
7777
Reid Kleckner78af0702013-08-27 23:08:25 +00007778 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00007779 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7780
7781 bool Variadic = (TypeStr[0] == '.');
7782
7783 // We really shouldn't be making a no-proto type here, especially in C++.
7784 if (ArgTypes.empty() && Variadic)
7785 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007786
John McCalldb40c7f2010-12-14 08:05:40 +00007787 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007788 EPI.ExtInfo = EI;
7789 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007790
Jordan Rose5c382722013-03-08 21:51:21 +00007791 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007792}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007793
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007794GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007795 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007796 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007797
Rafael Espindola3ae00052013-05-13 00:12:11 +00007798 GVALinkage External = GVA_StrongExternal;
7799 switch (FD->getTemplateSpecializationKind()) {
7800 case TSK_Undeclared:
7801 case TSK_ExplicitSpecialization:
7802 External = GVA_StrongExternal;
7803 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007804
Rafael Espindola3ae00052013-05-13 00:12:11 +00007805 case TSK_ExplicitInstantiationDefinition:
7806 return GVA_ExplicitTemplateInstantiation;
7807
7808 case TSK_ExplicitInstantiationDeclaration:
7809 case TSK_ImplicitInstantiation:
7810 External = GVA_TemplateInstantiation;
7811 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007812 }
7813
7814 if (!FD->isInlined())
7815 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00007816
Alp Tokerbfa39342014-01-14 12:51:41 +00007817 if ((!getLangOpts().CPlusPlus && !getLangOpts().MSVCCompat) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00007818 FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007819 // GNU or C99 inline semantics. Determine whether this symbol should be
7820 // externally visible.
7821 if (FD->isInlineDefinitionExternallyVisible())
7822 return External;
7823
7824 // C99 inline semantics, where the symbol is not externally visible.
7825 return GVA_C99Inline;
7826 }
7827
7828 // C++0x [temp.explicit]p9:
7829 // [ Note: The intent is that an inline function that is the subject of
7830 // an explicit instantiation declaration will still be implicitly
7831 // instantiated when used so that the body can be considered for
7832 // inlining, but that no out-of-line copy of the inline function would be
7833 // generated in the translation unit. -- end note ]
7834 if (FD->getTemplateSpecializationKind()
7835 == TSK_ExplicitInstantiationDeclaration)
7836 return GVA_C99Inline;
7837
7838 return GVA_CXXInline;
7839}
7840
7841GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007842 if (!VD->isExternallyVisible())
7843 return GVA_Internal;
7844
Richard Smith8809a0c2013-09-27 20:14:12 +00007845 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007846 case TSK_Undeclared:
7847 case TSK_ExplicitSpecialization:
7848 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007849
Rafael Espindola3ae00052013-05-13 00:12:11 +00007850 case TSK_ExplicitInstantiationDeclaration:
7851 llvm_unreachable("Variable should not be instantiated");
7852 // Fall through to treat this like any other instantiation.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007853
Rafael Espindola3ae00052013-05-13 00:12:11 +00007854 case TSK_ExplicitInstantiationDefinition:
7855 return GVA_ExplicitTemplateInstantiation;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007856
Rafael Espindola3ae00052013-05-13 00:12:11 +00007857 case TSK_ImplicitInstantiation:
7858 return GVA_TemplateInstantiation;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007859 }
Rafael Espindola27699c82013-05-13 14:05:53 +00007860
7861 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007862}
7863
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007864bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007865 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7866 if (!VD->isFileVarDecl())
7867 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00007868 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7869 // We never need to emit an uninstantiated function template.
7870 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7871 return false;
7872 } else
7873 return false;
7874
7875 // If this is a member of a class template, we do not need to emit it.
7876 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007877 return false;
7878
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007879 // Weak references don't produce any output by themselves.
7880 if (D->hasAttr<WeakRefAttr>())
7881 return false;
7882
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007883 // Aliases and used decls are required.
7884 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7885 return true;
7886
7887 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7888 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007889 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007890 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007891
7892 // Constructors and destructors are required.
7893 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7894 return true;
7895
John McCall6bd2a892013-01-25 22:31:03 +00007896 // The key function for a class is required. This rule only comes
7897 // into play when inline functions can be key functions, though.
7898 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7899 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7900 const CXXRecordDecl *RD = MD->getParent();
7901 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7902 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7903 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7904 return true;
7905 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007906 }
7907 }
7908
7909 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7910
7911 // static, static inline, always_inline, and extern inline functions can
7912 // always be deferred. Normal inline functions can be deferred in C99/C++.
7913 // Implicit template instantiations can also be deferred in C++.
7914 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007915 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007916 return false;
7917 return true;
7918 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007919
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007920 const VarDecl *VD = cast<VarDecl>(D);
7921 assert(VD->isFileVarDecl() && "Expected file scoped var");
7922
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007923 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7924 return false;
7925
Richard Smitha0e5e542012-11-12 21:38:00 +00007926 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007927 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smitha0e5e542012-11-12 21:38:00 +00007928 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7929 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007930
Richard Smitha0e5e542012-11-12 21:38:00 +00007931 // Variables that have destruction with side-effects are required.
7932 if (VD->getType().isDestructedType())
7933 return true;
7934
7935 // Variables that have initialization with side-effects are required.
7936 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7937 return true;
7938
7939 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007940}
Charles Davis53c59df2010-08-16 03:33:14 +00007941
Reid Kleckner78af0702013-08-27 23:08:25 +00007942CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
7943 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00007944 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00007945 if (IsCXXMethod)
7946 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007947
Reid Kleckner78af0702013-08-27 23:08:25 +00007948 return (LangOpts.MRTD && !IsVariadic) ? CC_X86StdCall : CC_C;
Charles Davis99202b32010-11-09 18:04:24 +00007949}
7950
Jay Foad39c79802011-01-12 09:06:06 +00007951bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007952 // Pass through to the C++ ABI object
7953 return ABI->isNearlyEmpty(RD);
7954}
7955
Reid Kleckner96f8f932014-02-05 17:27:08 +00007956VTableContextBase *ASTContext::getVTableContext() {
7957 if (!VTContext.get()) {
7958 if (Target->getCXXABI().isMicrosoft())
7959 VTContext.reset(new MicrosoftVTableContext(*this));
7960 else
7961 VTContext.reset(new ItaniumVTableContext(*this));
7962 }
7963 return VTContext.get();
7964}
7965
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007966MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00007967 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00007968 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00007969 case TargetCXXABI::GenericItanium:
7970 case TargetCXXABI::GenericARM:
7971 case TargetCXXABI::iOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00007972 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00007973 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00007974 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007975 }
David Blaikie83d382b2011-09-23 05:06:16 +00007976 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007977}
7978
Charles Davis53c59df2010-08-16 03:33:14 +00007979CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007980
7981size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00007982 return ASTRecordLayouts.getMemorySize() +
7983 llvm::capacity_in_bytes(ObjCLayouts) +
7984 llvm::capacity_in_bytes(KeyFunctions) +
7985 llvm::capacity_in_bytes(ObjCImpls) +
7986 llvm::capacity_in_bytes(BlockVarCopyInits) +
7987 llvm::capacity_in_bytes(DeclAttrs) +
7988 llvm::capacity_in_bytes(TemplateOrInstantiation) +
7989 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
7990 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
7991 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
7992 llvm::capacity_in_bytes(OverriddenMethods) +
7993 llvm::capacity_in_bytes(Types) +
7994 llvm::capacity_in_bytes(VariableArrayTypes) +
7995 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007996}
Ted Kremenek540017e2011-10-06 05:00:56 +00007997
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007998/// getIntTypeForBitwidth -
7999/// sets integer QualTy according to specified details:
8000/// bitwidth, signed/unsigned.
8001/// Returns empty type if there is no appropriate target types.
8002QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8003 unsigned Signed) const {
8004 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8005 CanQualType QualTy = getFromTargetType(Ty);
8006 if (!QualTy && DestWidth == 128)
8007 return Signed ? Int128Ty : UnsignedInt128Ty;
8008 return QualTy;
8009}
8010
8011/// getRealTypeForBitwidth -
8012/// sets floating point QualTy according to specified bitwidth.
8013/// Returns empty type if there is no appropriate target types.
8014QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8015 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8016 switch (Ty) {
8017 case TargetInfo::Float:
8018 return FloatTy;
8019 case TargetInfo::Double:
8020 return DoubleTy;
8021 case TargetInfo::LongDouble:
8022 return LongDoubleTy;
8023 case TargetInfo::NoFloat:
8024 return QualType();
8025 }
8026
8027 llvm_unreachable("Unhandled TargetInfo::RealType value");
8028}
8029
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008030void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8031 if (Number > 1)
8032 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008033}
8034
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008035unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8036 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8037 MangleNumbers.find(ND);
8038 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008039}
8040
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008041MangleNumberingContext &
8042ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008043 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8044 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8045 if (!MCtx)
8046 MCtx = createMangleNumberingContext();
8047 return *MCtx;
8048}
8049
8050MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8051 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008052}
8053
Ted Kremenek540017e2011-10-06 05:00:56 +00008054void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8055 ParamIndices[D] = index;
8056}
8057
8058unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8059 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8060 assert(I != ParamIndices.end() &&
8061 "ParmIndices lacks entry set by ParmVarDecl");
8062 return I->second;
8063}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008064
Richard Smithe6c01442013-06-05 00:46:14 +00008065APValue *
8066ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8067 bool MayCreate) {
8068 assert(E && E->getStorageDuration() == SD_Static &&
8069 "don't need to cache the computed value for this temporary");
8070 if (MayCreate)
8071 return &MaterializedTemporaryValues[E];
8072
8073 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8074 MaterializedTemporaryValues.find(E);
8075 return I == MaterializedTemporaryValues.end() ? 0 : &I->second;
8076}
8077
Fariborz Jahanian615de762013-05-28 17:37:39 +00008078bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8079 const llvm::Triple &T = getTargetInfo().getTriple();
8080 if (!T.isOSDarwin())
8081 return false;
8082
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008083 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8084 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8085 return false;
8086
Fariborz Jahanian615de762013-05-28 17:37:39 +00008087 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8088 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8089 uint64_t Size = sizeChars.getQuantity();
8090 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8091 unsigned Align = alignChars.getQuantity();
8092 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8093 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8094}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008095
8096namespace {
8097
8098 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8099 /// parents as defined by the \c RecursiveASTVisitor.
8100 ///
8101 /// Note that the relationship described here is purely in terms of AST
8102 /// traversal - there are other relationships (for example declaration context)
8103 /// in the AST that are better modeled by special matchers.
8104 ///
8105 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8106 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8107
8108 public:
8109 /// \brief Builds and returns the translation unit's parent map.
8110 ///
8111 /// The caller takes ownership of the returned \c ParentMap.
8112 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8113 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8114 Visitor.TraverseDecl(&TU);
8115 return Visitor.Parents;
8116 }
8117
8118 private:
8119 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8120
8121 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8122 }
8123
8124 bool shouldVisitTemplateInstantiations() const {
8125 return true;
8126 }
8127 bool shouldVisitImplicitCode() const {
8128 return true;
8129 }
8130 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8131 // are not triggered during data recursion.
8132 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8133 return false;
8134 }
8135
8136 template <typename T>
8137 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
8138 if (Node == NULL)
8139 return true;
8140 if (ParentStack.size() > 0)
8141 // FIXME: Currently we add the same parent multiple times, for example
8142 // when we visit all subexpressions of template instantiations; this is
8143 // suboptimal, bug benign: the only way to visit those is with
8144 // hasAncestor / hasParent, and those do not create new matches.
8145 // The plan is to enable DynTypedNode to be storable in a map or hash
8146 // map. The main problem there is to implement hash functions /
8147 // comparison operators for all types that DynTypedNode supports that
8148 // do not have pointer identity.
8149 (*Parents)[Node].push_back(ParentStack.back());
8150 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8151 bool Result = (this ->* traverse) (Node);
8152 ParentStack.pop_back();
8153 return Result;
8154 }
8155
8156 bool TraverseDecl(Decl *DeclNode) {
8157 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8158 }
8159
8160 bool TraverseStmt(Stmt *StmtNode) {
8161 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8162 }
8163
8164 ASTContext::ParentMap *Parents;
8165 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8166
8167 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8168 };
8169
8170} // end namespace
8171
8172ASTContext::ParentVector
8173ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8174 assert(Node.getMemoizationData() &&
8175 "Invariant broken: only nodes that support memoization may be "
8176 "used in the parent map.");
8177 if (!AllParents) {
8178 // We always need to run over the whole translation unit, as
8179 // hasAncestor can escape any subtree.
8180 AllParents.reset(
8181 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8182 }
8183 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8184 if (I == AllParents->end()) {
8185 return ParentVector();
8186 }
8187 return I->second;
8188}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008189
8190bool
8191ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8192 const ObjCMethodDecl *MethodImpl) {
8193 // No point trying to match an unavailable/deprecated mothod.
8194 if (MethodDecl->hasAttr<UnavailableAttr>()
8195 || MethodDecl->hasAttr<DeprecatedAttr>())
8196 return false;
8197 if (MethodDecl->getObjCDeclQualifier() !=
8198 MethodImpl->getObjCDeclQualifier())
8199 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008200 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008201 return false;
8202
8203 if (MethodDecl->param_size() != MethodImpl->param_size())
8204 return false;
8205
8206 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8207 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8208 EF = MethodDecl->param_end();
8209 IM != EM && IF != EF; ++IM, ++IF) {
8210 const ParmVarDecl *DeclVar = (*IF);
8211 const ParmVarDecl *ImplVar = (*IM);
8212 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8213 return false;
8214 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8215 return false;
8216 }
8217 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8218
8219}