blob: 3af3bff040982f6e256c660bc0cf20e920d98f51 [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;
Aaron Ballman86c93902014-03-06 23:45:36 +0000335 for (auto I : D->redecls()) {
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000336 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
Aaron Ballman86c93902014-03-06 23:45:36 +0000337 RedeclComments.find(I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000338 if (Pos != RedeclComments.end()) {
339 const RawCommentAndCacheFlags &Raw = Pos->second;
340 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
341 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000342 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000343 break;
344 }
345 } else {
Aaron Ballman86c93902014-03-06 23:45:36 +0000346 RC = getRawCommentForDeclNoCache(I);
347 OriginalDeclForRC = I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000348 RawCommentAndCacheFlags Raw;
349 if (RC) {
350 Raw.setRaw(RC);
351 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
352 } else
353 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000354 Raw.setOriginalDecl(I);
355 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000356 if (RC)
357 break;
358 }
359 }
360
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000361 // If we found a comment, it should be a documentation comment.
362 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000363
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000364 if (OriginalDecl)
365 *OriginalDecl = OriginalDeclForRC;
366
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000367 // Update cache for every declaration in the redeclaration chain.
368 RawCommentAndCacheFlags Raw;
369 Raw.setRaw(RC);
370 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000371 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000372
Aaron Ballman86c93902014-03-06 23:45:36 +0000373 for (auto I : D->redecls()) {
374 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000375 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
376 R = Raw;
377 }
378
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000379 return RC;
380}
381
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000382static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
383 SmallVectorImpl<const NamedDecl *> &Redeclared) {
384 const DeclContext *DC = ObjCMethod->getDeclContext();
385 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
386 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
387 if (!ID)
388 return;
389 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000390 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000391 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000392 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000393 ObjCMethod->isInstanceMethod()))
394 Redeclared.push_back(RedeclaredMethod);
395 }
396 }
397}
398
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000399comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
400 const Decl *D) const {
401 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
402 ThisDeclInfo->CommentDecl = D;
403 ThisDeclInfo->IsFilled = false;
404 ThisDeclInfo->fill();
405 ThisDeclInfo->CommentDecl = FC->getDecl();
406 comments::FullComment *CFC =
407 new (*this) comments::FullComment(FC->getBlocks(),
408 ThisDeclInfo);
409 return CFC;
410
411}
412
Richard Smithb39b9d52013-05-21 05:24:00 +0000413comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
414 const RawComment *RC = getRawCommentForDeclNoCache(D);
415 return RC ? RC->parse(*this, 0, D) : 0;
416}
417
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000418comments::FullComment *ASTContext::getCommentForDecl(
419 const Decl *D,
420 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000421 if (D->isInvalidDecl())
422 return NULL;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000423 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000424
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000425 const Decl *Canonical = D->getCanonicalDecl();
426 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
427 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000428
429 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000430 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000431 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000432 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000433 return CFC;
434 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000435 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000436 }
437
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000438 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000439
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000440 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000441 if (!RC) {
442 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000443 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000444 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000445 if (OMD && OMD->isPropertyAccessor())
446 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
447 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
448 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000449 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000450 addRedeclaredMethods(OMD, Overridden);
451 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000452 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
453 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
454 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000455 }
Fariborz Jahanian6384fbb2013-05-02 15:44:16 +0000456 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000457 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000458 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000459 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000460 if (const TagType *TT = QT->getAs<TagType>())
461 if (const Decl *TD = TT->getDecl())
462 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000463 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000464 }
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000465 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
466 while (IC->getSuperClass()) {
467 IC = IC->getSuperClass();
468 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
469 return cloneFullComment(FC, D);
470 }
471 }
472 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
473 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
474 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
475 return cloneFullComment(FC, D);
476 }
477 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
478 if (!(RD = RD->getDefinition()))
479 return NULL;
480 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000481 for (const auto &I : RD->bases()) {
482 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000483 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000484 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000485 if (Ty.isNull())
486 continue;
487 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
488 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
489 continue;
490
491 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
492 return cloneFullComment(FC, D);
493 }
494 }
495 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000496 for (const auto &I : RD->vbases()) {
497 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000498 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000499 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000500 if (Ty.isNull())
501 continue;
502 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
503 if (!(VirtualBase= VirtualBase->getDefinition()))
504 continue;
505 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
506 return cloneFullComment(FC, D);
507 }
508 }
509 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000510 return NULL;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000511 }
512
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000513 // If the RawComment was attached to other redeclaration of this Decl, we
514 // should parse the comment in context of that other Decl. This is important
515 // because comments can contain references to parameter names which can be
516 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000517 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000518 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000519
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000520 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000521 ParsedComments[Canonical] = FC;
522 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000523}
524
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000525void
526ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
527 TemplateTemplateParmDecl *Parm) {
528 ID.AddInteger(Parm->getDepth());
529 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000530 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000531
532 TemplateParameterList *Params = Parm->getTemplateParameters();
533 ID.AddInteger(Params->size());
534 for (TemplateParameterList::const_iterator P = Params->begin(),
535 PEnd = Params->end();
536 P != PEnd; ++P) {
537 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
538 ID.AddInteger(0);
539 ID.AddBoolean(TTP->isParameterPack());
540 continue;
541 }
542
543 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
544 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000545 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000546 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000547 if (NTTP->isExpandedParameterPack()) {
548 ID.AddBoolean(true);
549 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000550 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
551 QualType T = NTTP->getExpansionType(I);
552 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
553 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000554 } else
555 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000556 continue;
557 }
558
559 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
560 ID.AddInteger(2);
561 Profile(ID, TTP);
562 }
563}
564
565TemplateTemplateParmDecl *
566ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000567 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000568 // Check if we already have a canonical template template parameter.
569 llvm::FoldingSetNodeID ID;
570 CanonicalTemplateTemplateParm::Profile(ID, TTP);
571 void *InsertPos = 0;
572 CanonicalTemplateTemplateParm *Canonical
573 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
574 if (Canonical)
575 return Canonical->getParam();
576
577 // Build a canonical template parameter list.
578 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000579 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000580 CanonParams.reserve(Params->size());
581 for (TemplateParameterList::const_iterator P = Params->begin(),
582 PEnd = Params->end();
583 P != PEnd; ++P) {
584 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
585 CanonParams.push_back(
586 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000587 SourceLocation(),
588 SourceLocation(),
589 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000590 TTP->getIndex(), 0, false,
591 TTP->isParameterPack()));
592 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000593 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
594 QualType T = getCanonicalType(NTTP->getType());
595 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
596 NonTypeTemplateParmDecl *Param;
597 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000598 SmallVector<QualType, 2> ExpandedTypes;
599 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000600 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
601 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
602 ExpandedTInfos.push_back(
603 getTrivialTypeSourceInfo(ExpandedTypes.back()));
604 }
605
606 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000607 SourceLocation(),
608 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000609 NTTP->getDepth(),
610 NTTP->getPosition(), 0,
611 T,
612 TInfo,
613 ExpandedTypes.data(),
614 ExpandedTypes.size(),
615 ExpandedTInfos.data());
616 } else {
617 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000618 SourceLocation(),
619 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000620 NTTP->getDepth(),
621 NTTP->getPosition(), 0,
622 T,
623 NTTP->isParameterPack(),
624 TInfo);
625 }
626 CanonParams.push_back(Param);
627
628 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000629 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
630 cast<TemplateTemplateParmDecl>(*P)));
631 }
632
633 TemplateTemplateParmDecl *CanonTTP
634 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
635 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000636 TTP->getPosition(),
637 TTP->isParameterPack(),
638 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000639 TemplateParameterList::Create(*this, SourceLocation(),
640 SourceLocation(),
641 CanonParams.data(),
642 CanonParams.size(),
643 SourceLocation()));
644
645 // Get the new insert position for the node we care about.
646 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
647 assert(Canonical == 0 && "Shouldn't be in the map!");
648 (void)Canonical;
649
650 // Create the canonical template template parameter entry.
651 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
652 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
653 return CanonTTP;
654}
655
Charles Davis53c59df2010-08-16 03:33:14 +0000656CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000657 if (!LangOpts.CPlusPlus) return 0;
658
John McCall359b8852013-01-25 22:30:49 +0000659 switch (T.getCXXABI().getKind()) {
660 case TargetCXXABI::GenericARM:
661 case TargetCXXABI::iOS:
John McCall86353412010-08-21 22:46:04 +0000662 return CreateARMCXXABI(*this);
Tim Northover9bb857a2013-01-31 12:13:10 +0000663 case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000664 case TargetCXXABI::GenericItanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000665 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000666 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000667 return CreateMicrosoftCXXABI(*this);
668 }
David Blaikie8a40f702012-01-17 06:56:22 +0000669 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000670}
671
Douglas Gregore8bbc122011-09-02 00:18:52 +0000672static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000673 const LangOptions &LOpts) {
674 if (LOpts.FakeAddressSpaceMap) {
675 // The fake address space map must have a distinct entry for each
676 // language-specific address space.
677 static const unsigned FakeAddrSpaceMap[] = {
678 1, // opencl_global
679 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000680 3, // opencl_constant
681 4, // cuda_device
682 5, // cuda_constant
683 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000684 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000685 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000686 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000687 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000688 }
689}
690
David Tweed31d09b02013-09-13 12:04:22 +0000691static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
692 const LangOptions &LangOpts) {
693 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000694 case LangOptions::ASMM_Target:
695 return TI.useAddressSpaceMapMangling();
696 case LangOptions::ASMM_On:
697 return true;
698 case LangOptions::ASMM_Off:
699 return false;
700 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000701 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000702}
703
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000704ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000705 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000706 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000707 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000708 unsigned size_reserve,
709 bool DelayInitialization)
710 : FunctionProtoTypes(this_()),
711 TemplateSpecializationTypes(this_()),
712 DependentTemplateSpecializationTypes(this_()),
713 SubstTemplateTemplateParmPacks(this_()),
714 GlobalNestedNameSpecifier(0),
Nico Webere1687c52013-06-20 21:44:55 +0000715 Int128Decl(0), UInt128Decl(0), Float128StubDecl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000716 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000717 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanianf2578572012-08-30 18:49:41 +0000718 BOOLDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000719 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000720 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000721 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
722 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
723 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000724 NullTypeSourceInfo(QualType()),
725 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000726 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000727 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000728 Idents(idents), Selectors(sels),
729 BuiltinInfo(builtins),
730 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000731 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000732 Comments(SM), CommentsLoaded(false),
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000733 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
Rafael Espindolace2168f2013-05-29 19:51:12 +0000734 LastSDM(0, 0)
Douglas Gregore8bbc122011-09-02 00:18:52 +0000735{
Mike Stump11289f42009-09-09 15:08:12 +0000736 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000737 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000738
739 if (!DelayInitialization) {
740 assert(t && "No target supplied for ASTContext initialization");
741 InitBuiltinTypes(*t);
742 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000743}
744
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000745ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000746 // Release the DenseMaps associated with DeclContext objects.
747 // FIXME: Is this the ideal solution?
748 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000749
Manuel Klimeka7328992013-06-03 13:51:33 +0000750 // Call all of the deallocation functions on all of their targets.
751 for (DeallocationMap::const_iterator I = Deallocations.begin(),
752 E = Deallocations.end(); I != E; ++I)
753 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
754 (I->first)((I->second)[J]);
755
Ted Kremenek076baeb2010-06-08 23:00:58 +0000756 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000757 // because they can contain DenseMaps.
758 for (llvm::DenseMap<const ObjCContainerDecl*,
759 const ASTRecordLayout*>::iterator
760 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
761 // Increment in loop to prevent using deallocated memory.
762 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
763 R->Destroy(*this);
764
Ted Kremenek076baeb2010-06-08 23:00:58 +0000765 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
766 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
767 // Increment in loop to prevent using deallocated memory.
768 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
769 R->Destroy(*this);
770 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000771
772 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
773 AEnd = DeclAttrs.end();
774 A != AEnd; ++A)
775 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000776
Reid Kleckner588c9372014-02-19 23:44:52 +0000777 llvm::DeleteContainerSeconds(MangleNumberingContexts);
Douglas Gregor561eceb2010-08-30 16:49:28 +0000778}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000779
Douglas Gregor1a809332010-05-23 18:26:36 +0000780void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimeka7328992013-06-03 13:51:33 +0000781 Deallocations[Callback].push_back(Data);
Douglas Gregor1a809332010-05-23 18:26:36 +0000782}
783
Mike Stump11289f42009-09-09 15:08:12 +0000784void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000785ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
786 ExternalSource = Source;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000787}
788
Chris Lattner4eb445d2007-01-26 01:27:23 +0000789void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000790 llvm::errs() << "\n*** AST Context Stats:\n";
791 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000792
Douglas Gregora30d0462009-05-26 14:40:08 +0000793 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000794#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000795#define ABSTRACT_TYPE(Name, Parent)
796#include "clang/AST/TypeNodes.def"
797 0 // Extra
798 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000799
Chris Lattner4eb445d2007-01-26 01:27:23 +0000800 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
801 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000802 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000803 }
804
Douglas Gregora30d0462009-05-26 14:40:08 +0000805 unsigned Idx = 0;
806 unsigned TotalBytes = 0;
807#define TYPE(Name, Parent) \
808 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000809 llvm::errs() << " " << counts[Idx] << " " << #Name \
810 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000811 TotalBytes += counts[Idx] * sizeof(Name##Type); \
812 ++Idx;
813#define ABSTRACT_TYPE(Name, Parent)
814#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000815
Chandler Carruth3c147a72011-07-04 05:32:14 +0000816 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
817
Douglas Gregor7454c562010-07-02 20:37:36 +0000818 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000819 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
820 << NumImplicitDefaultConstructors
821 << " implicit default constructors created\n";
822 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
823 << NumImplicitCopyConstructors
824 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000825 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000826 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
827 << NumImplicitMoveConstructors
828 << " implicit move constructors created\n";
829 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
830 << NumImplicitCopyAssignmentOperators
831 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000832 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000833 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
834 << NumImplicitMoveAssignmentOperators
835 << " implicit move assignment operators created\n";
836 llvm::errs() << NumImplicitDestructorsDeclared << "/"
837 << NumImplicitDestructors
838 << " implicit destructors created\n";
839
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000840 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000841 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000842 ExternalSource->PrintStats();
843 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000844
Douglas Gregor5b11d492010-07-25 17:53:33 +0000845 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000846}
847
Alp Toker2dea15b2013-12-17 01:22:38 +0000848RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
849 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000850 SourceLocation Loc;
851 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +0000852 if (getLangOpts().CPlusPlus)
853 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
854 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000855 else
Alp Toker2dea15b2013-12-17 01:22:38 +0000856 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
857 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000858 NewDecl->setImplicit();
859 return NewDecl;
860}
861
862TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
863 StringRef Name) const {
864 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
865 TypedefDecl *NewDecl = TypedefDecl::Create(
866 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
867 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
868 NewDecl->setImplicit();
869 return NewDecl;
870}
871
Douglas Gregor801c99d2011-08-12 06:49:56 +0000872TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000873 if (!Int128Decl)
874 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000875 return Int128Decl;
876}
877
878TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000879 if (!UInt128Decl)
880 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000881 return UInt128Decl;
882}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000883
Nico Webere1687c52013-06-20 21:44:55 +0000884TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber5b0b46f2013-06-21 01:29:36 +0000885 assert(LangOpts.CPlusPlus && "should only be called for c++");
Alp Toker56b5cc92013-12-15 10:36:26 +0000886 if (!Float128StubDecl)
Alp Toker2dea15b2013-12-17 01:22:38 +0000887 Float128StubDecl = buildImplicitRecord("__float128");
Alp Toker56b5cc92013-12-15 10:36:26 +0000888
Nico Webere1687c52013-06-20 21:44:55 +0000889 return Float128StubDecl;
890}
891
John McCall48f2d582009-10-23 23:03:21 +0000892void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000893 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000894 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000895 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000896}
897
Douglas Gregore8bbc122011-09-02 00:18:52 +0000898void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
899 assert((!this->Target || this->Target == &Target) &&
900 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000901 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000902
Douglas Gregore8bbc122011-09-02 00:18:52 +0000903 this->Target = &Target;
904
905 ABI.reset(createCXXABI(Target));
906 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +0000907 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000908
Chris Lattner970e54e2006-11-12 00:37:36 +0000909 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000910 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000911
Chris Lattner970e54e2006-11-12 00:37:36 +0000912 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000913 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000914 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000915 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000916 InitBuiltinType(CharTy, BuiltinType::Char_S);
917 else
918 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000919 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000920 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
921 InitBuiltinType(ShortTy, BuiltinType::Short);
922 InitBuiltinType(IntTy, BuiltinType::Int);
923 InitBuiltinType(LongTy, BuiltinType::Long);
924 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000925
Chris Lattner970e54e2006-11-12 00:37:36 +0000926 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000927 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
928 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
929 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
930 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
931 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000932
Chris Lattner970e54e2006-11-12 00:37:36 +0000933 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000934 InitBuiltinType(FloatTy, BuiltinType::Float);
935 InitBuiltinType(DoubleTy, BuiltinType::Double);
936 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000937
Chris Lattnerf122cef2009-04-30 02:43:43 +0000938 // GNU extension, 128-bit integers.
939 InitBuiltinType(Int128Ty, BuiltinType::Int128);
940 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
941
Hans Wennborg0d81e012013-05-10 10:08:40 +0000942 // C++ 3.9.1p5
943 if (TargetInfo::isTypeSigned(Target.getWCharType()))
944 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
945 else // -fshort-wchar makes wchar_t be unsigned.
946 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
947 if (LangOpts.CPlusPlus && LangOpts.WChar)
948 WideCharTy = WCharTy;
949 else {
950 // C99 (or C++ using -fno-wchar).
951 WideCharTy = getFromTargetType(Target.getWCharType());
952 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000953
James Molloy36365542012-05-04 10:55:22 +0000954 WIntTy = getFromTargetType(Target.getWIntType());
955
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000956 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
957 InitBuiltinType(Char16Ty, BuiltinType::Char16);
958 else // C99
959 Char16Ty = getFromTargetType(Target.getChar16Type());
960
961 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
962 InitBuiltinType(Char32Ty, BuiltinType::Char32);
963 else // C99
964 Char32Ty = getFromTargetType(Target.getChar32Type());
965
Douglas Gregor4619e432008-12-05 23:32:09 +0000966 // Placeholder type for type-dependent expressions whose type is
967 // completely unknown. No code should ever check a type against
968 // DependentTy and users should never see it; however, it is here to
969 // help diagnose failures to properly check for type-dependent
970 // expressions.
971 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000972
John McCall36e7fe32010-10-12 00:20:44 +0000973 // Placeholder type for functions.
974 InitBuiltinType(OverloadTy, BuiltinType::Overload);
975
John McCall0009fcc2011-04-26 20:42:42 +0000976 // Placeholder type for bound members.
977 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
978
John McCall526ab472011-10-25 17:37:35 +0000979 // Placeholder type for pseudo-objects.
980 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
981
John McCall31996342011-04-07 08:22:57 +0000982 // "any" type; useful for debugger-like clients.
983 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
984
John McCall8a6b59a2011-10-17 18:09:15 +0000985 // Placeholder type for unbridged ARC casts.
986 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
987
Eli Friedman34866c72012-08-31 00:14:07 +0000988 // Placeholder type for builtin functions.
989 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
990
Chris Lattner970e54e2006-11-12 00:37:36 +0000991 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000992 FloatComplexTy = getComplexType(FloatTy);
993 DoubleComplexTy = getComplexType(DoubleTy);
994 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000995
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000996 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000997 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
998 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000999 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001000
1001 if (LangOpts.OpenCL) {
1002 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1003 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1004 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1005 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1006 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
1007 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001008
Guy Benyei61054192013-02-07 10:55:47 +00001009 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001010 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001011 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001012
1013 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001014 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1015 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001016
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001017 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001018
1019 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001020
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001021 // void * type
1022 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001023
1024 // nullptr type (C++0x 2.14.7)
1025 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001026
1027 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1028 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001029
1030 // Builtin type used to help define __builtin_va_list.
1031 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +00001032}
1033
David Blaikie9c902b52011-09-25 23:23:43 +00001034DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001035 return SourceMgr.getDiagnostics();
1036}
1037
Douglas Gregor561eceb2010-08-30 16:49:28 +00001038AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1039 AttrVec *&Result = DeclAttrs[D];
1040 if (!Result) {
1041 void *Mem = Allocate(sizeof(AttrVec));
1042 Result = new (Mem) AttrVec;
1043 }
1044
1045 return *Result;
1046}
1047
1048/// \brief Erase the attributes corresponding to the given declaration.
1049void ASTContext::eraseDeclAttrs(const Decl *D) {
1050 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1051 if (Pos != DeclAttrs.end()) {
1052 Pos->second->~AttrVec();
1053 DeclAttrs.erase(Pos);
1054 }
1055}
1056
Larisse Voufo39a1e502013-08-06 01:03:05 +00001057// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001058MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001059ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001060 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001061 return getTemplateOrSpecializationInfo(Var)
1062 .dyn_cast<MemberSpecializationInfo *>();
1063}
1064
1065ASTContext::TemplateOrSpecializationInfo
1066ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1067 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1068 TemplateOrInstantiation.find(Var);
1069 if (Pos == TemplateOrInstantiation.end())
1070 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001071
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001072 return Pos->second;
1073}
1074
Mike Stump11289f42009-09-09 15:08:12 +00001075void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001076ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001077 TemplateSpecializationKind TSK,
1078 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001079 assert(Inst->isStaticDataMember() && "Not a static data member");
1080 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001081 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1082 Tmpl, TSK, PointOfInstantiation));
1083}
1084
1085void
1086ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1087 TemplateOrSpecializationInfo TSI) {
1088 assert(!TemplateOrInstantiation[Inst] &&
1089 "Already noted what the variable was instantiated from");
1090 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001091}
1092
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001093FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1094 const FunctionDecl *FD){
1095 assert(FD && "Specialization is 0");
1096 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001097 = ClassScopeSpecializationPattern.find(FD);
1098 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001099 return 0;
1100
1101 return Pos->second;
1102}
1103
1104void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1105 FunctionDecl *Pattern) {
1106 assert(FD && "Specialization is 0");
1107 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001108 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001109}
1110
John McCalle61f2ba2009-11-18 02:36:19 +00001111NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001112ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001113 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001114 = InstantiatedFromUsingDecl.find(UUD);
1115 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001116 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001117
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001118 return Pos->second;
1119}
1120
1121void
John McCallb96ec562009-12-04 22:46:56 +00001122ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1123 assert((isa<UsingDecl>(Pattern) ||
1124 isa<UnresolvedUsingValueDecl>(Pattern) ||
1125 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1126 "pattern decl is not a using decl");
1127 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1128 InstantiatedFromUsingDecl[Inst] = Pattern;
1129}
1130
1131UsingShadowDecl *
1132ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1133 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1134 = InstantiatedFromUsingShadowDecl.find(Inst);
1135 if (Pos == InstantiatedFromUsingShadowDecl.end())
1136 return 0;
1137
1138 return Pos->second;
1139}
1140
1141void
1142ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1143 UsingShadowDecl *Pattern) {
1144 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1145 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001146}
1147
Anders Carlsson5da84842009-09-01 04:26:58 +00001148FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1149 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1150 = InstantiatedFromUnnamedFieldDecl.find(Field);
1151 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1152 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001153
Anders Carlsson5da84842009-09-01 04:26:58 +00001154 return Pos->second;
1155}
1156
1157void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1158 FieldDecl *Tmpl) {
1159 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1160 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1161 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1162 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001163
Anders Carlsson5da84842009-09-01 04:26:58 +00001164 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1165}
1166
Douglas Gregor832940b2010-03-02 23:58:15 +00001167ASTContext::overridden_cxx_method_iterator
1168ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1169 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001170 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001171 if (Pos == OverriddenMethods.end())
1172 return 0;
1173
1174 return Pos->second.begin();
1175}
1176
1177ASTContext::overridden_cxx_method_iterator
1178ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1179 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001180 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001181 if (Pos == OverriddenMethods.end())
1182 return 0;
1183
1184 return Pos->second.end();
1185}
1186
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001187unsigned
1188ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1189 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001190 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001191 if (Pos == OverriddenMethods.end())
1192 return 0;
1193
1194 return Pos->second.size();
1195}
1196
Douglas Gregor832940b2010-03-02 23:58:15 +00001197void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1198 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001199 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001200 OverriddenMethods[Method].push_back(Overridden);
1201}
1202
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001203void ASTContext::getOverriddenMethods(
1204 const NamedDecl *D,
1205 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001206 assert(D);
1207
1208 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001209 Overridden.append(overridden_methods_begin(CXXMethod),
1210 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001211 return;
1212 }
1213
1214 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1215 if (!Method)
1216 return;
1217
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001218 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1219 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001220 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001221}
1222
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001223void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1224 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1225 assert(!Import->isFromASTFile() && "Non-local import declaration");
1226 if (!FirstLocalImport) {
1227 FirstLocalImport = Import;
1228 LastLocalImport = Import;
1229 return;
1230 }
1231
1232 LastLocalImport->NextLocalImport = Import;
1233 LastLocalImport = Import;
1234}
1235
Chris Lattner53cfe802007-07-18 17:52:12 +00001236//===----------------------------------------------------------------------===//
1237// Type Sizing and Analysis
1238//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001239
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001240/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1241/// scalar floating point type.
1242const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001243 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001244 assert(BT && "Not a floating point type!");
1245 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001246 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001247 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001248 case BuiltinType::Float: return Target->getFloatFormat();
1249 case BuiltinType::Double: return Target->getDoubleFormat();
1250 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001251 }
1252}
1253
Rafael Espindola71eccb32013-08-08 19:53:46 +00001254CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001255 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001256
John McCall94268702010-10-08 18:24:19 +00001257 bool UseAlignAttrOnly = false;
1258 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1259 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001260
John McCall94268702010-10-08 18:24:19 +00001261 // __attribute__((aligned)) can increase or decrease alignment
1262 // *except* on a struct or struct member, where it only increases
1263 // alignment unless 'packed' is also specified.
1264 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001265 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001266 // ignore that possibility; Sema should diagnose it.
1267 if (isa<FieldDecl>(D)) {
1268 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1269 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1270 } else {
1271 UseAlignAttrOnly = true;
1272 }
1273 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001274 else if (isa<FieldDecl>(D))
1275 UseAlignAttrOnly =
1276 D->hasAttr<PackedAttr>() ||
1277 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001278
John McCall4e819612011-01-20 07:57:12 +00001279 // If we're using the align attribute only, just ignore everything
1280 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001281 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001282 // do nothing
1283
John McCall94268702010-10-08 18:24:19 +00001284 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001285 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001286 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001287 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001288 T = RT->getPointeeType();
1289 else
1290 T = getPointerType(RT->getPointeeType());
1291 }
1292 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001293 // Adjust alignments of declarations with array type by the
1294 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001295 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001296 unsigned MinWidth = Target->getLargeArrayMinWidth();
1297 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001298 if (isa<VariableArrayType>(arrayType))
1299 Align = std::max(Align, Target->getLargeArrayAlign());
1300 else if (isa<ConstantArrayType>(arrayType) &&
1301 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1302 Align = std::max(Align, Target->getLargeArrayAlign());
1303 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001304
John McCall33ddac02011-01-19 10:06:00 +00001305 // Walk through any array types while we're at it.
1306 T = getBaseElementType(arrayType);
1307 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001308 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001309 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1310 if (VD->hasGlobalStorage())
1311 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1312 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001313 }
John McCall4e819612011-01-20 07:57:12 +00001314
1315 // Fields can be subject to extra alignment constraints, like if
1316 // the field is packed, the struct is packed, or the struct has a
1317 // a max-field-alignment constraint (#pragma pack). So calculate
1318 // the actual alignment of the field within the struct, and then
1319 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001320 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1321 const RecordDecl *Parent = Field->getParent();
1322 // We can only produce a sensible answer if the record is valid.
1323 if (!Parent->isInvalidDecl()) {
1324 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001325
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001326 // Start with the record's overall alignment.
1327 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001328
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001329 // Use the GCD of that and the offset within the record.
1330 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1331 if (Offset > 0) {
1332 // Alignment is always a power of 2, so the GCD will be a power of 2,
1333 // which means we get to do this crazy thing instead of Euclid's.
1334 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1335 if (LowBitOfOffset < FieldAlign)
1336 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1337 }
1338
1339 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001340 }
Charles Davis3fc51072010-02-23 04:52:00 +00001341 }
Chris Lattner68061312009-01-24 21:53:27 +00001342 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001343
Ken Dyckcc56c542011-01-15 18:38:59 +00001344 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001345}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001346
John McCallf1249922012-08-21 04:10:00 +00001347// getTypeInfoDataSizeInChars - Return the size of a type, in
1348// chars. If the type is a record, its data size is returned. This is
1349// the size of the memcpy that's performed when assigning this type
1350// using a trivial copy/move assignment operator.
1351std::pair<CharUnits, CharUnits>
1352ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1353 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1354
1355 // In C++, objects can sometimes be allocated into the tail padding
1356 // of a base-class subobject. We decide whether that's possible
1357 // during class layout, so here we can just trust the layout results.
1358 if (getLangOpts().CPlusPlus) {
1359 if (const RecordType *RT = T->getAs<RecordType>()) {
1360 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1361 sizeAndAlign.first = layout.getDataSize();
1362 }
1363 }
1364
1365 return sizeAndAlign;
1366}
1367
Richard Trieu04d2d942013-05-14 21:59:17 +00001368/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1369/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1370std::pair<CharUnits, CharUnits>
1371static getConstantArrayInfoInChars(const ASTContext &Context,
1372 const ConstantArrayType *CAT) {
1373 std::pair<CharUnits, CharUnits> EltInfo =
1374 Context.getTypeInfoInChars(CAT->getElementType());
1375 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001376 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1377 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001378 "Overflow in array type char size evaluation");
1379 uint64_t Width = EltInfo.first.getQuantity() * Size;
1380 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001381 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1382 Context.getTargetInfo().getPointerWidth(0) == 64)
1383 Width = llvm::RoundUpToAlignment(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001384 return std::make_pair(CharUnits::fromQuantity(Width),
1385 CharUnits::fromQuantity(Align));
1386}
1387
John McCall87fe5d52010-05-20 01:18:31 +00001388std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001389ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001390 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1391 return getConstantArrayInfoInChars(*this, CAT);
John McCall87fe5d52010-05-20 01:18:31 +00001392 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +00001393 return std::make_pair(toCharUnitsFromBits(Info.first),
1394 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +00001395}
1396
1397std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001398ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001399 return getTypeInfoInChars(T.getTypePtr());
1400}
1401
Daniel Dunbarc6475872012-03-09 04:12:54 +00001402std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1403 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1404 if (it != MemoizedTypeInfo.end())
1405 return it->second;
1406
1407 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1408 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1409 return Info;
1410}
1411
1412/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1413/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001414///
1415/// FIXME: Pointers into different addr spaces could have different sizes and
1416/// alignment requirements: getPointerInfo should take an AddrSpace, this
1417/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001418std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001419ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001420 uint64_t Width=0;
1421 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001422 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001423#define TYPE(Class, Base)
1424#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001425#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001426#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001427#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1428 case Type::Class: \
1429 assert(!T->isDependentType() && "should not see dependent types here"); \
1430 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001431#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001432 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001433
Chris Lattner355332d2007-07-13 22:27:08 +00001434 case Type::FunctionNoProto:
1435 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001436 // GCC extension: alignof(function) = 32 bits
1437 Width = 0;
1438 Align = 32;
1439 break;
1440
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001441 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001442 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001443 Width = 0;
1444 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1445 break;
1446
Steve Naroff5c131802007-08-30 01:06:46 +00001447 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001448 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001449
Chris Lattner37e05872008-03-05 18:54:05 +00001450 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001451 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001452 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1453 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001454 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001455 Align = EltInfo.second;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001456 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1457 getTargetInfo().getPointerWidth(0) == 64)
1458 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001459 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001460 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001461 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001462 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001463 const VectorType *VT = cast<VectorType>(T);
1464 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1465 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001466 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001467 // If the alignment is not a power of 2, round up to the next power of 2.
1468 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001469 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001470 Align = llvm::NextPowerOf2(Align);
1471 Width = llvm::RoundUpToAlignment(Width, Align);
1472 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001473 // Adjust the alignment based on the target max.
1474 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1475 if (TargetVectorAlign && TargetVectorAlign < Align)
1476 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001477 break;
1478 }
Chris Lattner647fb222007-07-18 18:26:58 +00001479
Chris Lattner7570e9c2008-03-08 08:52:55 +00001480 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001481 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001482 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001483 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001484 // GCC extension: alignof(void) = 8 bits.
1485 Width = 0;
1486 Align = 8;
1487 break;
1488
Chris Lattner6a4f7452007-12-19 19:23:28 +00001489 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001490 Width = Target->getBoolWidth();
1491 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001492 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001493 case BuiltinType::Char_S:
1494 case BuiltinType::Char_U:
1495 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001496 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001497 Width = Target->getCharWidth();
1498 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001499 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001500 case BuiltinType::WChar_S:
1501 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001502 Width = Target->getWCharWidth();
1503 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001504 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001505 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001506 Width = Target->getChar16Width();
1507 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001508 break;
1509 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001510 Width = Target->getChar32Width();
1511 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001512 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001513 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001514 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001515 Width = Target->getShortWidth();
1516 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001517 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001518 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001519 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001520 Width = Target->getIntWidth();
1521 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001522 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001523 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001524 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001525 Width = Target->getLongWidth();
1526 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001527 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001528 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001529 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001530 Width = Target->getLongLongWidth();
1531 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001532 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001533 case BuiltinType::Int128:
1534 case BuiltinType::UInt128:
1535 Width = 128;
1536 Align = 128; // int128_t is 128-bit aligned on all targets.
1537 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001538 case BuiltinType::Half:
1539 Width = Target->getHalfWidth();
1540 Align = Target->getHalfAlign();
1541 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001542 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001543 Width = Target->getFloatWidth();
1544 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001545 break;
1546 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001547 Width = Target->getDoubleWidth();
1548 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001549 break;
1550 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001551 Width = Target->getLongDoubleWidth();
1552 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001553 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001554 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001555 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1556 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001557 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001558 case BuiltinType::ObjCId:
1559 case BuiltinType::ObjCClass:
1560 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001561 Width = Target->getPointerWidth(0);
1562 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001563 break;
Guy Benyei61054192013-02-07 10:55:47 +00001564 case BuiltinType::OCLSampler:
1565 // Samplers are modeled as integers.
1566 Width = Target->getIntWidth();
1567 Align = Target->getIntAlign();
1568 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001569 case BuiltinType::OCLEvent:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001570 case BuiltinType::OCLImage1d:
1571 case BuiltinType::OCLImage1dArray:
1572 case BuiltinType::OCLImage1dBuffer:
1573 case BuiltinType::OCLImage2d:
1574 case BuiltinType::OCLImage2dArray:
1575 case BuiltinType::OCLImage3d:
1576 // Currently these types are pointers to opaque types.
1577 Width = Target->getPointerWidth(0);
1578 Align = Target->getPointerAlign(0);
1579 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001580 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001581 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001582 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001583 Width = Target->getPointerWidth(0);
1584 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001585 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001586 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001587 unsigned AS = getTargetAddressSpace(
1588 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001589 Width = Target->getPointerWidth(AS);
1590 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001591 break;
1592 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001593 case Type::LValueReference:
1594 case Type::RValueReference: {
1595 // alignof and sizeof should never enter this code path here, so we go
1596 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001597 unsigned AS = getTargetAddressSpace(
1598 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001599 Width = Target->getPointerWidth(AS);
1600 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001601 break;
1602 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001603 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001604 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001605 Width = Target->getPointerWidth(AS);
1606 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001607 break;
1608 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001609 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001610 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001611 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001612 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001613 }
Chris Lattner647fb222007-07-18 18:26:58 +00001614 case Type::Complex: {
1615 // Complex types have the same alignment as their elements, but twice the
1616 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001617 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001618 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001619 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001620 Align = EltInfo.second;
1621 break;
1622 }
John McCall8b07ec22010-05-15 11:32:37 +00001623 case Type::ObjCObject:
1624 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001625 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001626 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001627 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001628 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001629 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001630 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001631 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001632 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001633 break;
1634 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001635 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001636 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001637 const TagType *TT = cast<TagType>(T);
1638
1639 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001640 Width = 8;
1641 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001642 break;
1643 }
Mike Stump11289f42009-09-09 15:08:12 +00001644
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001645 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001646 return getTypeInfo(ET->getDecl()->getIntegerType());
1647
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001648 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001649 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001650 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001651 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001652 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001653 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001654
Chris Lattner63d2b362009-10-22 05:17:15 +00001655 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001656 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1657 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001658
Richard Smith30482bc2011-02-20 03:19:35 +00001659 case Type::Auto: {
1660 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001661 assert(!A->getDeducedType().isNull() &&
1662 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001663 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001664 }
1665
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001666 case Type::Paren:
1667 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1668
Douglas Gregoref462e62009-04-30 17:32:17 +00001669 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001670 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001671 std::pair<uint64_t, unsigned> Info
1672 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001673 // If the typedef has an aligned attribute on it, it overrides any computed
1674 // alignment we have. This violates the GCC documentation (which says that
1675 // attribute(aligned) can only round up) but matches its implementation.
1676 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1677 Align = AttrAlign;
1678 else
1679 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001680 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001681 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001682 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001683
Abramo Bagnara6150c882010-05-11 21:36:43 +00001684 case Type::Elaborated:
1685 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001686
John McCall81904512011-01-06 01:58:22 +00001687 case Type::Attributed:
1688 return getTypeInfo(
1689 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1690
Eli Friedman0dfb8892011-10-06 23:00:33 +00001691 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001692 // Start with the base type information.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001693 std::pair<uint64_t, unsigned> Info
1694 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1695 Width = Info.first;
1696 Align = Info.second;
John McCalla8ec7eb2013-03-07 21:37:17 +00001697
1698 // If the size of the type doesn't exceed the platform's max
1699 // atomic promotion width, make the size and alignment more
1700 // favorable to atomic operations:
1701 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1702 // Round the size up to a power of 2.
1703 if (!llvm::isPowerOf2_64(Width))
1704 Width = llvm::NextPowerOf2(Width);
1705
1706 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001707 Align = static_cast<unsigned>(Width);
1708 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001709 }
1710
Douglas Gregoref462e62009-04-30 17:32:17 +00001711 }
Mike Stump11289f42009-09-09 15:08:12 +00001712
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001713 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001714 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001715}
1716
Ken Dyckcc56c542011-01-15 18:38:59 +00001717/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1718CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1719 return CharUnits::fromQuantity(BitSize / getCharWidth());
1720}
1721
Ken Dyckb0fcc592011-02-11 01:54:29 +00001722/// toBits - Convert a size in characters to a size in characters.
1723int64_t ASTContext::toBits(CharUnits CharSize) const {
1724 return CharSize.getQuantity() * getCharWidth();
1725}
1726
Ken Dyck8c89d592009-12-22 14:23:30 +00001727/// getTypeSizeInChars - Return the size of the specified type, in characters.
1728/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001729CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001730 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001731}
Jay Foad39c79802011-01-12 09:06:06 +00001732CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001733 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001734}
1735
Ken Dycka6046ab2010-01-26 17:25:18 +00001736/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001737/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001738CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001739 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001740}
Jay Foad39c79802011-01-12 09:06:06 +00001741CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001742 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001743}
1744
Chris Lattnera3402cd2009-01-27 18:08:34 +00001745/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1746/// type for the current target in bits. This can be different than the ABI
1747/// alignment in cases where it is beneficial for performance to overalign
1748/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001749unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001750 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001751
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001752 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1753 return ABIAlign; // Never overalign on XCore.
1754
David Majnemer8b6bd572014-02-24 23:34:17 +00001755 const TypedefType *TT = T->getAs<TypedefType>();
1756
Eli Friedman7ab09572009-05-25 21:27:19 +00001757 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00001758 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001759 T = CT->getElementType().getTypePtr();
1760 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001761 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1762 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00001763 // Don't increase the alignment if an alignment attribute was specified on a
1764 // typedef declaration.
1765 if (!TT || !TT->getDecl()->getMaxAlignment())
1766 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00001767
Chris Lattnera3402cd2009-01-27 18:08:34 +00001768 return ABIAlign;
1769}
1770
Ulrich Weigandfa806422013-05-06 16:23:57 +00001771/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1772/// to a global variable of the specified type.
1773unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1774 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1775}
1776
1777/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1778/// should be given to a global variable of the specified type.
1779CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1780 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1781}
1782
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001783/// DeepCollectObjCIvars -
1784/// This routine first collects all declared, but not synthesized, ivars in
1785/// super class and then collects all ivars, including those synthesized for
1786/// current class. This routine is used for implementation of current class
1787/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001788///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001789void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1790 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001791 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001792 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1793 DeepCollectObjCIvars(SuperClass, false, Ivars);
1794 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00001795 for (const auto *I : OI->ivars())
1796 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001797 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001798 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001799 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001800 Iv= Iv->getNextIvar())
1801 Ivars.push_back(Iv);
1802 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001803}
1804
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001805/// CollectInheritedProtocols - Collect all protocols in current class and
1806/// those inherited by it.
1807void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001808 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001809 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001810 // We can use protocol_iterator here instead of
1811 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001812 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001813 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001814 for (auto *P : Proto->protocols()) {
1815 Protocols.insert(P->getCanonicalDecl());
1816 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001817 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001818 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001819
1820 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00001821 for (const auto *Cat : OI->visible_categories())
1822 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001823
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001824 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1825 while (SD) {
1826 CollectInheritedProtocols(SD, Protocols);
1827 SD = SD->getSuperClass();
1828 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001829 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00001830 for (auto *Proto : OC->protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001831 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001832 for (const auto *P : Proto->protocols())
1833 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001834 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001835 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001836 for (auto *Proto : OP->protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001837 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001838 for (const auto *P : Proto->protocols())
1839 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001840 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001841 }
1842}
1843
Jay Foad39c79802011-01-12 09:06:06 +00001844unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001845 unsigned count = 0;
1846 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00001847 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001848 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001849
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001850 // Count ivar defined in this class's implementation. This
1851 // includes synthesized ivars.
1852 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001853 count += ImplDecl->ivar_size();
1854
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001855 return count;
1856}
1857
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001858bool ASTContext::isSentinelNullExpr(const Expr *E) {
1859 if (!E)
1860 return false;
1861
1862 // nullptr_t is always treated as null.
1863 if (E->getType()->isNullPtrType()) return true;
1864
1865 if (E->getType()->isAnyPointerType() &&
1866 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1867 Expr::NPC_ValueDependentIsNull))
1868 return true;
1869
1870 // Unfortunately, __null has type 'int'.
1871 if (isa<GNUNullExpr>(E)) return true;
1872
1873 return false;
1874}
1875
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001876/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1877ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1878 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1879 I = ObjCImpls.find(D);
1880 if (I != ObjCImpls.end())
1881 return cast<ObjCImplementationDecl>(I->second);
1882 return 0;
1883}
1884/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1885ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1886 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1887 I = ObjCImpls.find(D);
1888 if (I != ObjCImpls.end())
1889 return cast<ObjCCategoryImplDecl>(I->second);
1890 return 0;
1891}
1892
1893/// \brief Set the implementation of ObjCInterfaceDecl.
1894void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1895 ObjCImplementationDecl *ImplD) {
1896 assert(IFaceD && ImplD && "Passed null params");
1897 ObjCImpls[IFaceD] = ImplD;
1898}
1899/// \brief Set the implementation of ObjCCategoryDecl.
1900void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1901 ObjCCategoryImplDecl *ImplD) {
1902 assert(CatD && ImplD && "Passed null params");
1903 ObjCImpls[CatD] = ImplD;
1904}
1905
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001906const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1907 const NamedDecl *ND) const {
1908 if (const ObjCInterfaceDecl *ID =
1909 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001910 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001911 if (const ObjCCategoryDecl *CD =
1912 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001913 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001914 if (const ObjCImplDecl *IMD =
1915 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001916 return IMD->getClassInterface();
1917
1918 return 0;
1919}
1920
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001921/// \brief Get the copy initialization expression of VarDecl,or NULL if
1922/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001923Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001924 assert(VD && "Passed null params");
1925 assert(VD->hasAttr<BlocksAttr>() &&
1926 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001927 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001928 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001929 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1930}
1931
1932/// \brief Set the copy inialization expression of a block var decl.
1933void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1934 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001935 assert(VD->hasAttr<BlocksAttr>() &&
1936 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001937 BlockVarCopyInits[VD] = Init;
1938}
1939
John McCallbcd03502009-12-07 02:54:59 +00001940TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001941 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001942 if (!DataSize)
1943 DataSize = TypeLoc::getFullDataSizeForType(T);
1944 else
1945 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001946 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001947
John McCallbcd03502009-12-07 02:54:59 +00001948 TypeSourceInfo *TInfo =
1949 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1950 new (TInfo) TypeSourceInfo(T);
1951 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001952}
1953
John McCallbcd03502009-12-07 02:54:59 +00001954TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001955 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001956 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001957 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001958 return DI;
1959}
1960
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001961const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001962ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001963 return getObjCLayout(D, 0);
1964}
1965
1966const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001967ASTContext::getASTObjCImplementationLayout(
1968 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001969 return getObjCLayout(D->getClassInterface(), D);
1970}
1971
Chris Lattner983a8bb2007-07-13 22:13:22 +00001972//===----------------------------------------------------------------------===//
1973// Type creation/memoization methods
1974//===----------------------------------------------------------------------===//
1975
Jay Foad39c79802011-01-12 09:06:06 +00001976QualType
John McCall33ddac02011-01-19 10:06:00 +00001977ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1978 unsigned fastQuals = quals.getFastQualifiers();
1979 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001980
1981 // Check if we've already instantiated this type.
1982 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001983 ExtQuals::Profile(ID, baseType, quals);
1984 void *insertPos = 0;
1985 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1986 assert(eq->getQualifiers() == quals);
1987 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001988 }
1989
John McCall33ddac02011-01-19 10:06:00 +00001990 // If the base type is not canonical, make the appropriate canonical type.
1991 QualType canon;
1992 if (!baseType->isCanonicalUnqualified()) {
1993 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001994 canonSplit.Quals.addConsistentQualifiers(quals);
1995 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001996
1997 // Re-find the insert position.
1998 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1999 }
2000
2001 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2002 ExtQualNodes.InsertNode(eq, insertPos);
2003 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002004}
2005
Jay Foad39c79802011-01-12 09:06:06 +00002006QualType
2007ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002008 QualType CanT = getCanonicalType(T);
2009 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002010 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002011
John McCall8ccfcb52009-09-24 19:53:00 +00002012 // If we are composing extended qualifiers together, merge together
2013 // into one ExtQuals node.
2014 QualifierCollector Quals;
2015 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002016
John McCall8ccfcb52009-09-24 19:53:00 +00002017 // If this type already has an address space specified, it cannot get
2018 // another one.
2019 assert(!Quals.hasAddressSpace() &&
2020 "Type cannot be in multiple addr spaces!");
2021 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002022
John McCall8ccfcb52009-09-24 19:53:00 +00002023 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002024}
2025
Chris Lattnerd60183d2009-02-18 22:53:11 +00002026QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002027 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002028 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002029 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002030 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002031
John McCall53fa7142010-12-24 02:08:15 +00002032 if (const PointerType *ptr = T->getAs<PointerType>()) {
2033 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002034 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002035 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2036 return getPointerType(ResultType);
2037 }
2038 }
Mike Stump11289f42009-09-09 15:08:12 +00002039
John McCall8ccfcb52009-09-24 19:53:00 +00002040 // If we are composing extended qualifiers together, merge together
2041 // into one ExtQuals node.
2042 QualifierCollector Quals;
2043 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002044
John McCall8ccfcb52009-09-24 19:53:00 +00002045 // If this type already has an ObjCGC specified, it cannot get
2046 // another one.
2047 assert(!Quals.hasObjCGCAttr() &&
2048 "Type cannot have multiple ObjCGCs!");
2049 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002050
John McCall8ccfcb52009-09-24 19:53:00 +00002051 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002052}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002053
John McCall4f5019e2010-12-19 02:44:49 +00002054const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2055 FunctionType::ExtInfo Info) {
2056 if (T->getExtInfo() == Info)
2057 return T;
2058
2059 QualType Result;
2060 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002061 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002062 } else {
2063 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2064 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2065 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002066 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002067 }
2068
2069 return cast<FunctionType>(Result.getTypePtr());
2070}
2071
Richard Smith2a7d4812013-05-04 07:00:32 +00002072void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2073 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002074 FD = FD->getMostRecentDecl();
2075 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002076 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2077 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002078 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002079 if (FunctionDecl *Next = FD->getPreviousDecl())
2080 FD = Next;
2081 else
2082 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002083 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002084 if (ASTMutationListener *L = getASTMutationListener())
2085 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002086}
2087
Chris Lattnerc6395932007-06-22 20:56:16 +00002088/// getComplexType - Return the uniqued reference to the type for a complex
2089/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002090QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002091 // Unique pointers, to guarantee there is only one pointer of a particular
2092 // structure.
2093 llvm::FoldingSetNodeID ID;
2094 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002095
Chris Lattnerc6395932007-06-22 20:56:16 +00002096 void *InsertPos = 0;
2097 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2098 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002099
Chris Lattnerc6395932007-06-22 20:56:16 +00002100 // If the pointee type isn't canonical, this won't be a canonical type either,
2101 // so fill in the canonical type field.
2102 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002103 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002104 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002105
Chris Lattnerc6395932007-06-22 20:56:16 +00002106 // Get the new insert position for the node we care about.
2107 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002108 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002109 }
John McCall90d1c2d2009-09-24 23:30:46 +00002110 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002111 Types.push_back(New);
2112 ComplexTypes.InsertNode(New, InsertPos);
2113 return QualType(New, 0);
2114}
2115
Chris Lattner970e54e2006-11-12 00:37:36 +00002116/// getPointerType - Return the uniqued reference to the type for a pointer to
2117/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002118QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002119 // Unique pointers, to guarantee there is only one pointer of a particular
2120 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002121 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002122 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002123
Chris Lattner67521df2007-01-27 01:29:36 +00002124 void *InsertPos = 0;
2125 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002126 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002127
Chris Lattner7ccecb92006-11-12 08:50:50 +00002128 // If the pointee type isn't canonical, this won't be a canonical type either,
2129 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002130 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002131 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002132 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002133
Bob Wilsonc8541f22013-03-15 17:12:43 +00002134 // Get the new insert position for the node we care about.
2135 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2136 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2137 }
John McCall90d1c2d2009-09-24 23:30:46 +00002138 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002139 Types.push_back(New);
2140 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002141 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002142}
2143
Reid Kleckner0503a872013-12-05 01:23:43 +00002144QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2145 llvm::FoldingSetNodeID ID;
2146 AdjustedType::Profile(ID, Orig, New);
2147 void *InsertPos = 0;
2148 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2149 if (AT)
2150 return QualType(AT, 0);
2151
2152 QualType Canonical = getCanonicalType(New);
2153
2154 // Get the new insert position for the node we care about.
2155 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2156 assert(AT == 0 && "Shouldn't be in the map!");
2157
2158 AT = new (*this, TypeAlignment)
2159 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2160 Types.push_back(AT);
2161 AdjustedTypes.InsertNode(AT, InsertPos);
2162 return QualType(AT, 0);
2163}
2164
Reid Kleckner8a365022013-06-24 17:51:48 +00002165QualType ASTContext::getDecayedType(QualType T) const {
2166 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2167
Reid Kleckner8a365022013-06-24 17:51:48 +00002168 QualType Decayed;
2169
2170 // C99 6.7.5.3p7:
2171 // A declaration of a parameter as "array of type" shall be
2172 // adjusted to "qualified pointer to type", where the type
2173 // qualifiers (if any) are those specified within the [ and ] of
2174 // the array type derivation.
2175 if (T->isArrayType())
2176 Decayed = getArrayDecayedType(T);
2177
2178 // C99 6.7.5.3p8:
2179 // A declaration of a parameter as "function returning type"
2180 // shall be adjusted to "pointer to function returning type", as
2181 // in 6.3.2.1.
2182 if (T->isFunctionType())
2183 Decayed = getPointerType(T);
2184
Reid Kleckner0503a872013-12-05 01:23:43 +00002185 llvm::FoldingSetNodeID ID;
2186 AdjustedType::Profile(ID, T, Decayed);
2187 void *InsertPos = 0;
2188 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2189 if (AT)
2190 return QualType(AT, 0);
2191
Reid Kleckner8a365022013-06-24 17:51:48 +00002192 QualType Canonical = getCanonicalType(Decayed);
2193
2194 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002195 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2196 assert(AT == 0 && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002197
Reid Kleckner0503a872013-12-05 01:23:43 +00002198 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2199 Types.push_back(AT);
2200 AdjustedTypes.InsertNode(AT, InsertPos);
2201 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002202}
2203
Mike Stump11289f42009-09-09 15:08:12 +00002204/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002205/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002206QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002207 assert(T->isFunctionType() && "block of function types only");
2208 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002209 // structure.
2210 llvm::FoldingSetNodeID ID;
2211 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002212
Steve Naroffec33ed92008-08-27 16:04:49 +00002213 void *InsertPos = 0;
2214 if (BlockPointerType *PT =
2215 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2216 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002217
2218 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002219 // type either so fill in the canonical type field.
2220 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002221 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002222 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002223
Steve Naroffec33ed92008-08-27 16:04:49 +00002224 // Get the new insert position for the node we care about.
2225 BlockPointerType *NewIP =
2226 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002227 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002228 }
John McCall90d1c2d2009-09-24 23:30:46 +00002229 BlockPointerType *New
2230 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002231 Types.push_back(New);
2232 BlockPointerTypes.InsertNode(New, InsertPos);
2233 return QualType(New, 0);
2234}
2235
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002236/// getLValueReferenceType - Return the uniqued reference to the type for an
2237/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002238QualType
2239ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002240 assert(getCanonicalType(T) != OverloadTy &&
2241 "Unresolved overloaded function type");
2242
Bill Wendling3708c182007-05-27 10:15:43 +00002243 // Unique pointers, to guarantee there is only one pointer of a particular
2244 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002245 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002246 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002247
2248 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002249 if (LValueReferenceType *RT =
2250 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002251 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002252
John McCallfc93cf92009-10-22 22:37:11 +00002253 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2254
Bill Wendling3708c182007-05-27 10:15:43 +00002255 // If the referencee type isn't canonical, this won't be a canonical type
2256 // either, so fill in the canonical type field.
2257 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002258 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2259 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2260 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002261
Bill Wendling3708c182007-05-27 10:15:43 +00002262 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002263 LValueReferenceType *NewIP =
2264 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002265 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002266 }
2267
John McCall90d1c2d2009-09-24 23:30:46 +00002268 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002269 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2270 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002271 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002272 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002273
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002274 return QualType(New, 0);
2275}
2276
2277/// getRValueReferenceType - Return the uniqued reference to the type for an
2278/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002279QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002280 // Unique pointers, to guarantee there is only one pointer of a particular
2281 // structure.
2282 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002283 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002284
2285 void *InsertPos = 0;
2286 if (RValueReferenceType *RT =
2287 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2288 return QualType(RT, 0);
2289
John McCallfc93cf92009-10-22 22:37:11 +00002290 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2291
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002292 // If the referencee type isn't canonical, this won't be a canonical type
2293 // either, so fill in the canonical type field.
2294 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002295 if (InnerRef || !T.isCanonical()) {
2296 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2297 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002298
2299 // Get the new insert position for the node we care about.
2300 RValueReferenceType *NewIP =
2301 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002302 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002303 }
2304
John McCall90d1c2d2009-09-24 23:30:46 +00002305 RValueReferenceType *New
2306 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002307 Types.push_back(New);
2308 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002309 return QualType(New, 0);
2310}
2311
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002312/// getMemberPointerType - Return the uniqued reference to the type for a
2313/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002314QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002315 // Unique pointers, to guarantee there is only one pointer of a particular
2316 // structure.
2317 llvm::FoldingSetNodeID ID;
2318 MemberPointerType::Profile(ID, T, Cls);
2319
2320 void *InsertPos = 0;
2321 if (MemberPointerType *PT =
2322 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2323 return QualType(PT, 0);
2324
2325 // If the pointee or class type isn't canonical, this won't be a canonical
2326 // type either, so fill in the canonical type field.
2327 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002328 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002329 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2330
2331 // Get the new insert position for the node we care about.
2332 MemberPointerType *NewIP =
2333 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002334 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002335 }
John McCall90d1c2d2009-09-24 23:30:46 +00002336 MemberPointerType *New
2337 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002338 Types.push_back(New);
2339 MemberPointerTypes.InsertNode(New, InsertPos);
2340 return QualType(New, 0);
2341}
2342
Mike Stump11289f42009-09-09 15:08:12 +00002343/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002344/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002345QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002346 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002347 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002348 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002349 assert((EltTy->isDependentType() ||
2350 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002351 "Constant array of VLAs is illegal!");
2352
Chris Lattnere2df3f92009-05-13 04:12:56 +00002353 // Convert the array size into a canonical width matching the pointer size for
2354 // the target.
2355 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002356 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002357 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002358
Chris Lattner23b7eb62007-06-15 23:05:46 +00002359 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002360 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002361
Chris Lattner36f8e652007-01-27 08:31:04 +00002362 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002363 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002364 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002365 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002366
John McCall33ddac02011-01-19 10:06:00 +00002367 // If the element type isn't canonical or has qualifiers, this won't
2368 // be a canonical type either, so fill in the canonical type field.
2369 QualType Canon;
2370 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2371 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002372 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002373 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002374 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002375
Chris Lattner36f8e652007-01-27 08:31:04 +00002376 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002377 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002378 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002379 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002380 }
Mike Stump11289f42009-09-09 15:08:12 +00002381
John McCall90d1c2d2009-09-24 23:30:46 +00002382 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002383 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002384 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002385 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002386 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002387}
2388
John McCall06549462011-01-18 08:40:38 +00002389/// getVariableArrayDecayedType - Turns the given type, which may be
2390/// variably-modified, into the corresponding type with all the known
2391/// sizes replaced with [*].
2392QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2393 // Vastly most common case.
2394 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002395
John McCall06549462011-01-18 08:40:38 +00002396 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002397
John McCall06549462011-01-18 08:40:38 +00002398 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002399 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002400 switch (ty->getTypeClass()) {
2401#define TYPE(Class, Base)
2402#define ABSTRACT_TYPE(Class, Base)
2403#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2404#include "clang/AST/TypeNodes.def"
2405 llvm_unreachable("didn't desugar past all non-canonical types?");
2406
2407 // These types should never be variably-modified.
2408 case Type::Builtin:
2409 case Type::Complex:
2410 case Type::Vector:
2411 case Type::ExtVector:
2412 case Type::DependentSizedExtVector:
2413 case Type::ObjCObject:
2414 case Type::ObjCInterface:
2415 case Type::ObjCObjectPointer:
2416 case Type::Record:
2417 case Type::Enum:
2418 case Type::UnresolvedUsing:
2419 case Type::TypeOfExpr:
2420 case Type::TypeOf:
2421 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002422 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002423 case Type::DependentName:
2424 case Type::InjectedClassName:
2425 case Type::TemplateSpecialization:
2426 case Type::DependentTemplateSpecialization:
2427 case Type::TemplateTypeParm:
2428 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002429 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002430 case Type::PackExpansion:
2431 llvm_unreachable("type should never be variably-modified");
2432
2433 // These types can be variably-modified but should never need to
2434 // further decay.
2435 case Type::FunctionNoProto:
2436 case Type::FunctionProto:
2437 case Type::BlockPointer:
2438 case Type::MemberPointer:
2439 return type;
2440
2441 // These types can be variably-modified. All these modifications
2442 // preserve structure except as noted by comments.
2443 // TODO: if we ever care about optimizing VLAs, there are no-op
2444 // optimizations available here.
2445 case Type::Pointer:
2446 result = getPointerType(getVariableArrayDecayedType(
2447 cast<PointerType>(ty)->getPointeeType()));
2448 break;
2449
2450 case Type::LValueReference: {
2451 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2452 result = getLValueReferenceType(
2453 getVariableArrayDecayedType(lv->getPointeeType()),
2454 lv->isSpelledAsLValue());
2455 break;
2456 }
2457
2458 case Type::RValueReference: {
2459 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2460 result = getRValueReferenceType(
2461 getVariableArrayDecayedType(lv->getPointeeType()));
2462 break;
2463 }
2464
Eli Friedman0dfb8892011-10-06 23:00:33 +00002465 case Type::Atomic: {
2466 const AtomicType *at = cast<AtomicType>(ty);
2467 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2468 break;
2469 }
2470
John McCall06549462011-01-18 08:40:38 +00002471 case Type::ConstantArray: {
2472 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2473 result = getConstantArrayType(
2474 getVariableArrayDecayedType(cat->getElementType()),
2475 cat->getSize(),
2476 cat->getSizeModifier(),
2477 cat->getIndexTypeCVRQualifiers());
2478 break;
2479 }
2480
2481 case Type::DependentSizedArray: {
2482 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2483 result = getDependentSizedArrayType(
2484 getVariableArrayDecayedType(dat->getElementType()),
2485 dat->getSizeExpr(),
2486 dat->getSizeModifier(),
2487 dat->getIndexTypeCVRQualifiers(),
2488 dat->getBracketsRange());
2489 break;
2490 }
2491
2492 // Turn incomplete types into [*] types.
2493 case Type::IncompleteArray: {
2494 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2495 result = getVariableArrayType(
2496 getVariableArrayDecayedType(iat->getElementType()),
2497 /*size*/ 0,
2498 ArrayType::Normal,
2499 iat->getIndexTypeCVRQualifiers(),
2500 SourceRange());
2501 break;
2502 }
2503
2504 // Turn VLA types into [*] types.
2505 case Type::VariableArray: {
2506 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2507 result = getVariableArrayType(
2508 getVariableArrayDecayedType(vat->getElementType()),
2509 /*size*/ 0,
2510 ArrayType::Star,
2511 vat->getIndexTypeCVRQualifiers(),
2512 vat->getBracketsRange());
2513 break;
2514 }
2515 }
2516
2517 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002518 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002519}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002520
Steve Naroffcadebd02007-08-30 18:14:25 +00002521/// getVariableArrayType - Returns a non-unique reference to the type for a
2522/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002523QualType ASTContext::getVariableArrayType(QualType EltTy,
2524 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002525 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002526 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002527 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002528 // Since we don't unique expressions, it isn't possible to unique VLA's
2529 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002530 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002531
John McCall33ddac02011-01-19 10:06:00 +00002532 // Be sure to pull qualifiers off the element type.
2533 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2534 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002535 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002536 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002537 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002538 }
2539
John McCall90d1c2d2009-09-24 23:30:46 +00002540 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002541 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002542
2543 VariableArrayTypes.push_back(New);
2544 Types.push_back(New);
2545 return QualType(New, 0);
2546}
2547
Douglas Gregor4619e432008-12-05 23:32:09 +00002548/// getDependentSizedArrayType - Returns a non-unique reference to
2549/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002550/// type.
John McCall33ddac02011-01-19 10:06:00 +00002551QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2552 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002553 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002554 unsigned elementTypeQuals,
2555 SourceRange brackets) const {
2556 assert((!numElements || numElements->isTypeDependent() ||
2557 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002558 "Size must be type- or value-dependent!");
2559
John McCall33ddac02011-01-19 10:06:00 +00002560 // Dependently-sized array types that do not have a specified number
2561 // of elements will have their sizes deduced from a dependent
2562 // initializer. We do no canonicalization here at all, which is okay
2563 // because they can't be used in most locations.
2564 if (!numElements) {
2565 DependentSizedArrayType *newType
2566 = new (*this, TypeAlignment)
2567 DependentSizedArrayType(*this, elementType, QualType(),
2568 numElements, ASM, elementTypeQuals,
2569 brackets);
2570 Types.push_back(newType);
2571 return QualType(newType, 0);
2572 }
2573
2574 // Otherwise, we actually build a new type every time, but we
2575 // also build a canonical type.
2576
2577 SplitQualType canonElementType = getCanonicalType(elementType).split();
2578
2579 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002580 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002581 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002582 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002583 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002584
John McCall33ddac02011-01-19 10:06:00 +00002585 // Look for an existing type with these properties.
2586 DependentSizedArrayType *canonTy =
2587 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002588
John McCall33ddac02011-01-19 10:06:00 +00002589 // If we don't have one, build one.
2590 if (!canonTy) {
2591 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002592 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002593 QualType(), numElements, ASM, elementTypeQuals,
2594 brackets);
2595 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2596 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002597 }
2598
John McCall33ddac02011-01-19 10:06:00 +00002599 // Apply qualifiers from the element type to the array.
2600 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002601 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002602
John McCall33ddac02011-01-19 10:06:00 +00002603 // If we didn't need extra canonicalization for the element type,
2604 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002605 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002606 return canon;
2607
2608 // Otherwise, we need to build a type which follows the spelling
2609 // of the element type.
2610 DependentSizedArrayType *sugaredType
2611 = new (*this, TypeAlignment)
2612 DependentSizedArrayType(*this, elementType, canon, numElements,
2613 ASM, elementTypeQuals, brackets);
2614 Types.push_back(sugaredType);
2615 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002616}
2617
John McCall33ddac02011-01-19 10:06:00 +00002618QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002619 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002620 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002621 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002622 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002623
John McCall33ddac02011-01-19 10:06:00 +00002624 void *insertPos = 0;
2625 if (IncompleteArrayType *iat =
2626 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2627 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002628
2629 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002630 // either, so fill in the canonical type field. We also have to pull
2631 // qualifiers off the element type.
2632 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002633
John McCall33ddac02011-01-19 10:06:00 +00002634 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2635 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002636 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002637 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002638 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002639
2640 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002641 IncompleteArrayType *existing =
2642 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2643 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002644 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002645
John McCall33ddac02011-01-19 10:06:00 +00002646 IncompleteArrayType *newType = new (*this, TypeAlignment)
2647 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002648
John McCall33ddac02011-01-19 10:06:00 +00002649 IncompleteArrayTypes.InsertNode(newType, insertPos);
2650 Types.push_back(newType);
2651 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002652}
2653
Steve Naroff91fcddb2007-07-18 18:00:27 +00002654/// getVectorType - Return the unique reference to a vector type of
2655/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002656QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002657 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002658 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002659
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002660 // Check if we've already instantiated a vector of this type.
2661 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002662 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002663
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002664 void *InsertPos = 0;
2665 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2666 return QualType(VTP, 0);
2667
2668 // If the element type isn't canonical, this won't be a canonical type either,
2669 // so fill in the canonical type field.
2670 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002671 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002672 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002673
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002674 // Get the new insert position for the node we care about.
2675 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002676 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002677 }
John McCall90d1c2d2009-09-24 23:30:46 +00002678 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002679 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002680 VectorTypes.InsertNode(New, InsertPos);
2681 Types.push_back(New);
2682 return QualType(New, 0);
2683}
2684
Nate Begemance4d7fc2008-04-18 23:10:10 +00002685/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002686/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002687QualType
2688ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002689 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002690
Steve Naroff91fcddb2007-07-18 18:00:27 +00002691 // Check if we've already instantiated a vector of this type.
2692 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002693 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002694 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002695 void *InsertPos = 0;
2696 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2697 return QualType(VTP, 0);
2698
2699 // If the element type isn't canonical, this won't be a canonical type either,
2700 // so fill in the canonical type field.
2701 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002702 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002703 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002704
Steve Naroff91fcddb2007-07-18 18:00:27 +00002705 // Get the new insert position for the node we care about.
2706 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002707 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002708 }
John McCall90d1c2d2009-09-24 23:30:46 +00002709 ExtVectorType *New = new (*this, TypeAlignment)
2710 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002711 VectorTypes.InsertNode(New, InsertPos);
2712 Types.push_back(New);
2713 return QualType(New, 0);
2714}
2715
Jay Foad39c79802011-01-12 09:06:06 +00002716QualType
2717ASTContext::getDependentSizedExtVectorType(QualType vecType,
2718 Expr *SizeExpr,
2719 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002720 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002721 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002722 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002723
Douglas Gregor352169a2009-07-31 03:54:25 +00002724 void *InsertPos = 0;
2725 DependentSizedExtVectorType *Canon
2726 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2727 DependentSizedExtVectorType *New;
2728 if (Canon) {
2729 // We already have a canonical version of this array type; use it as
2730 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002731 New = new (*this, TypeAlignment)
2732 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2733 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002734 } else {
2735 QualType CanonVecTy = getCanonicalType(vecType);
2736 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002737 New = new (*this, TypeAlignment)
2738 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2739 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002740
2741 DependentSizedExtVectorType *CanonCheck
2742 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2743 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2744 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002745 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2746 } else {
2747 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2748 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002749 New = new (*this, TypeAlignment)
2750 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002751 }
2752 }
Mike Stump11289f42009-09-09 15:08:12 +00002753
Douglas Gregor758a8692009-06-17 21:51:59 +00002754 Types.push_back(New);
2755 return QualType(New, 0);
2756}
2757
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002758/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002759///
Jay Foad39c79802011-01-12 09:06:06 +00002760QualType
2761ASTContext::getFunctionNoProtoType(QualType ResultTy,
2762 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002763 const CallingConv CallConv = Info.getCC();
2764
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002765 // Unique functions, to guarantee there is only one function of a particular
2766 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002767 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002768 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002769
Chris Lattner47955de2007-01-27 08:37:20 +00002770 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002771 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002772 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002773 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002774
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002775 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002776 if (!ResultTy.isCanonical()) {
2777 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002778
Chris Lattner47955de2007-01-27 08:37:20 +00002779 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002780 FunctionNoProtoType *NewIP =
2781 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002782 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002783 }
Mike Stump11289f42009-09-09 15:08:12 +00002784
Roman Divacky65b88cd2011-03-01 17:40:53 +00002785 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002786 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002787 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002788 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002789 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002790 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002791}
2792
Douglas Gregorcd780372013-01-17 23:36:45 +00002793/// \brief Determine whether \p T is canonical as the result type of a function.
2794static bool isCanonicalResultType(QualType T) {
2795 return T.isCanonical() &&
2796 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2797 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2798}
2799
Jay Foad39c79802011-01-12 09:06:06 +00002800QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002801ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002802 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002803 size_t NumArgs = ArgArray.size();
2804
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002805 // Unique functions, to guarantee there is only one function of a particular
2806 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002807 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002808 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2809 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002810
2811 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002812 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002813 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002814 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002815
2816 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002817 bool isCanonical =
Douglas Gregorcd780372013-01-17 23:36:45 +00002818 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002819 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002820 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002821 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002822 isCanonical = false;
2823
2824 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002825 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002826 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002827 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002828 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002829 CanonicalArgs.reserve(NumArgs);
2830 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002831 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002832
John McCalldb40c7f2010-12-14 08:05:40 +00002833 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002834 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002835 CanonicalEPI.ExceptionSpecType = EST_None;
2836 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002837
Douglas Gregorcd780372013-01-17 23:36:45 +00002838 // Result types do not have ARC lifetime qualifiers.
2839 QualType CanResultTy = getCanonicalType(ResultTy);
2840 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2841 Qualifiers Qs = CanResultTy.getQualifiers();
2842 Qs.removeObjCLifetime();
2843 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2844 }
2845
Jordan Rose5c382722013-03-08 21:51:21 +00002846 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002847
Chris Lattnerfd4de792007-01-27 01:15:32 +00002848 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002849 FunctionProtoType *NewIP =
2850 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002851 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002852 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002853
John McCall31168b02011-06-15 23:02:42 +00002854 // FunctionProtoType objects are allocated with extra bytes after
2855 // them for three variable size arrays at the end:
2856 // - parameter types
2857 // - exception types
2858 // - consumed-arguments flags
2859 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002860 // expression, or information used to resolve the exception
2861 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002862 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002863 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002864 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002865 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002866 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002867 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002868 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002869 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002870 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2871 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002872 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002873 if (EPI.ConsumedParameters)
John McCall31168b02011-06-15 23:02:42 +00002874 Size += NumArgs * sizeof(bool);
2875
John McCalldb40c7f2010-12-14 08:05:40 +00002876 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002877 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00002878 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002879 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002880 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002881 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002882}
Chris Lattneref51c202006-11-10 07:17:23 +00002883
John McCalle78aac42010-03-10 03:28:59 +00002884#ifndef NDEBUG
2885static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2886 if (!isa<CXXRecordDecl>(D)) return false;
2887 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2888 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2889 return true;
2890 if (RD->getDescribedClassTemplate() &&
2891 !isa<ClassTemplateSpecializationDecl>(RD))
2892 return true;
2893 return false;
2894}
2895#endif
2896
2897/// getInjectedClassNameType - Return the unique reference to the
2898/// injected class name type for the specified templated declaration.
2899QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002900 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002901 assert(NeedsInjectedClassNameType(Decl));
2902 if (Decl->TypeForDecl) {
2903 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002904 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002905 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2906 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2907 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2908 } else {
John McCall424cec92011-01-19 06:33:43 +00002909 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002910 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002911 Decl->TypeForDecl = newType;
2912 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002913 }
2914 return QualType(Decl->TypeForDecl, 0);
2915}
2916
Douglas Gregor83a586e2008-04-13 21:07:44 +00002917/// getTypeDeclType - Return the unique reference to the type for the
2918/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002919QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002920 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002921 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002922
Richard Smithdda56e42011-04-15 14:24:37 +00002923 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002924 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002925
John McCall96f0b5f2010-03-10 06:48:02 +00002926 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2927 "Template type parameter types are always available.");
2928
John McCall81e38502010-02-16 03:57:14 +00002929 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00002930 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00002931 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002932 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002933 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00002934 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002935 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002936 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002937 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002938 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2939 Decl->TypeForDecl = newType;
2940 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002941 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002942 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002943
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002944 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002945}
2946
Chris Lattner32d920b2007-01-26 02:01:53 +00002947/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002948/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002949QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002950ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2951 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002952 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002953
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002954 if (Canonical.isNull())
2955 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002956 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002957 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002958 Decl->TypeForDecl = newType;
2959 Types.push_back(newType);
2960 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002961}
2962
Jay Foad39c79802011-01-12 09:06:06 +00002963QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002964 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2965
Douglas Gregorec9fd132012-01-14 16:38:05 +00002966 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002967 if (PrevDecl->TypeForDecl)
2968 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2969
John McCall424cec92011-01-19 06:33:43 +00002970 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2971 Decl->TypeForDecl = newType;
2972 Types.push_back(newType);
2973 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002974}
2975
Jay Foad39c79802011-01-12 09:06:06 +00002976QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002977 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2978
Douglas Gregorec9fd132012-01-14 16:38:05 +00002979 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002980 if (PrevDecl->TypeForDecl)
2981 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2982
John McCall424cec92011-01-19 06:33:43 +00002983 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2984 Decl->TypeForDecl = newType;
2985 Types.push_back(newType);
2986 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002987}
2988
John McCall81904512011-01-06 01:58:22 +00002989QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2990 QualType modifiedType,
2991 QualType equivalentType) {
2992 llvm::FoldingSetNodeID id;
2993 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2994
2995 void *insertPos = 0;
2996 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2997 if (type) return QualType(type, 0);
2998
2999 QualType canon = getCanonicalType(equivalentType);
3000 type = new (*this, TypeAlignment)
3001 AttributedType(canon, attrKind, modifiedType, equivalentType);
3002
3003 Types.push_back(type);
3004 AttributedTypes.InsertNode(type, insertPos);
3005
3006 return QualType(type, 0);
3007}
3008
3009
John McCallcebee162009-10-18 09:09:24 +00003010/// \brief Retrieve a substitution-result type.
3011QualType
3012ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003013 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003014 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003015 && "replacement types must always be canonical");
3016
3017 llvm::FoldingSetNodeID ID;
3018 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3019 void *InsertPos = 0;
3020 SubstTemplateTypeParmType *SubstParm
3021 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3022
3023 if (!SubstParm) {
3024 SubstParm = new (*this, TypeAlignment)
3025 SubstTemplateTypeParmType(Parm, Replacement);
3026 Types.push_back(SubstParm);
3027 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3028 }
3029
3030 return QualType(SubstParm, 0);
3031}
3032
Douglas Gregorada4b792011-01-14 02:55:32 +00003033/// \brief Retrieve a
3034QualType ASTContext::getSubstTemplateTypeParmPackType(
3035 const TemplateTypeParmType *Parm,
3036 const TemplateArgument &ArgPack) {
3037#ifndef NDEBUG
3038 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
3039 PEnd = ArgPack.pack_end();
3040 P != PEnd; ++P) {
3041 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3042 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
3043 }
3044#endif
3045
3046 llvm::FoldingSetNodeID ID;
3047 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3048 void *InsertPos = 0;
3049 if (SubstTemplateTypeParmPackType *SubstParm
3050 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3051 return QualType(SubstParm, 0);
3052
3053 QualType Canon;
3054 if (!Parm->isCanonicalUnqualified()) {
3055 Canon = getCanonicalType(QualType(Parm, 0));
3056 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3057 ArgPack);
3058 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3059 }
3060
3061 SubstTemplateTypeParmPackType *SubstParm
3062 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3063 ArgPack);
3064 Types.push_back(SubstParm);
3065 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3066 return QualType(SubstParm, 0);
3067}
3068
Douglas Gregoreff93e02009-02-05 23:33:38 +00003069/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003070/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003071/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003072QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003073 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003074 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003075 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003076 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003077 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003078 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003079 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3080
3081 if (TypeParm)
3082 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003083
Chandler Carruth08836322011-05-01 00:51:33 +00003084 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003085 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003086 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003087
3088 TemplateTypeParmType *TypeCheck
3089 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3090 assert(!TypeCheck && "Template type parameter canonical type broken");
3091 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003092 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003093 TypeParm = new (*this, TypeAlignment)
3094 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003095
3096 Types.push_back(TypeParm);
3097 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3098
3099 return QualType(TypeParm, 0);
3100}
3101
John McCalle78aac42010-03-10 03:28:59 +00003102TypeSourceInfo *
3103ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3104 SourceLocation NameLoc,
3105 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003106 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003107 assert(!Name.getAsDependentTemplateName() &&
3108 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003109 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003110
3111 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003112 TemplateSpecializationTypeLoc TL =
3113 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003114 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003115 TL.setTemplateNameLoc(NameLoc);
3116 TL.setLAngleLoc(Args.getLAngleLoc());
3117 TL.setRAngleLoc(Args.getRAngleLoc());
3118 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3119 TL.setArgLocInfo(i, Args[i].getLocInfo());
3120 return DI;
3121}
3122
Mike Stump11289f42009-09-09 15:08:12 +00003123QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003124ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003125 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003126 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003127 assert(!Template.getAsDependentTemplateName() &&
3128 "No dependent template names here!");
3129
John McCall6b51f282009-11-23 01:53:49 +00003130 unsigned NumArgs = Args.size();
3131
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003132 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003133 ArgVec.reserve(NumArgs);
3134 for (unsigned i = 0; i != NumArgs; ++i)
3135 ArgVec.push_back(Args[i].getArgument());
3136
John McCall2408e322010-04-27 00:57:59 +00003137 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003138 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003139}
3140
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003141#ifndef NDEBUG
3142static bool hasAnyPackExpansions(const TemplateArgument *Args,
3143 unsigned NumArgs) {
3144 for (unsigned I = 0; I != NumArgs; ++I)
3145 if (Args[I].isPackExpansion())
3146 return true;
3147
3148 return true;
3149}
3150#endif
3151
John McCall0ad16662009-10-29 08:12:44 +00003152QualType
3153ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003154 const TemplateArgument *Args,
3155 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003156 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003157 assert(!Template.getAsDependentTemplateName() &&
3158 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003159 // Look through qualified template names.
3160 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3161 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003162
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003163 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003164 Template.getAsTemplateDecl() &&
3165 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003166 QualType CanonType;
3167 if (!Underlying.isNull())
3168 CanonType = getCanonicalType(Underlying);
3169 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003170 // We can get here with an alias template when the specialization contains
3171 // a pack expansion that does not match up with a parameter pack.
3172 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3173 "Caller must compute aliased type");
3174 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003175 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3176 NumArgs);
3177 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003178
Douglas Gregora8e02e72009-07-28 23:00:59 +00003179 // Allocate the (non-canonical) template specialization type, but don't
3180 // try to unique it: these types typically have location information that
3181 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003182 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3183 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003184 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003185 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003186 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003187 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3188 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003189
Douglas Gregor8bf42052009-02-09 18:46:07 +00003190 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003191 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003192}
3193
Mike Stump11289f42009-09-09 15:08:12 +00003194QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003195ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3196 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003197 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003198 assert(!Template.getAsDependentTemplateName() &&
3199 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003200
Douglas Gregore29139c2011-03-03 17:04:51 +00003201 // Look through qualified template names.
3202 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3203 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003204
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003205 // Build the canonical template specialization type.
3206 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003207 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003208 CanonArgs.reserve(NumArgs);
3209 for (unsigned I = 0; I != NumArgs; ++I)
3210 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3211
3212 // Determine whether this canonical template specialization type already
3213 // exists.
3214 llvm::FoldingSetNodeID ID;
3215 TemplateSpecializationType::Profile(ID, CanonTemplate,
3216 CanonArgs.data(), NumArgs, *this);
3217
3218 void *InsertPos = 0;
3219 TemplateSpecializationType *Spec
3220 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3221
3222 if (!Spec) {
3223 // Allocate a new canonical template specialization type.
3224 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3225 sizeof(TemplateArgument) * NumArgs),
3226 TypeAlignment);
3227 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3228 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003229 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003230 Types.push_back(Spec);
3231 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3232 }
3233
3234 assert(Spec->isDependentType() &&
3235 "Non-dependent template-id type must have a canonical type");
3236 return QualType(Spec, 0);
3237}
3238
3239QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003240ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3241 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003242 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003243 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003244 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003245
3246 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003247 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003248 if (T)
3249 return QualType(T, 0);
3250
Douglas Gregorc42075a2010-02-04 18:10:26 +00003251 QualType Canon = NamedType;
3252 if (!Canon.isCanonical()) {
3253 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003254 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3255 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003256 (void)CheckT;
3257 }
3258
Abramo Bagnara6150c882010-05-11 21:36:43 +00003259 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003260 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003261 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003262 return QualType(T, 0);
3263}
3264
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003265QualType
Jay Foad39c79802011-01-12 09:06:06 +00003266ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003267 llvm::FoldingSetNodeID ID;
3268 ParenType::Profile(ID, InnerType);
3269
3270 void *InsertPos = 0;
3271 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3272 if (T)
3273 return QualType(T, 0);
3274
3275 QualType Canon = InnerType;
3276 if (!Canon.isCanonical()) {
3277 Canon = getCanonicalType(InnerType);
3278 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3279 assert(!CheckT && "Paren canonical type broken");
3280 (void)CheckT;
3281 }
3282
3283 T = new (*this) ParenType(InnerType, Canon);
3284 Types.push_back(T);
3285 ParenTypes.InsertNode(T, InsertPos);
3286 return QualType(T, 0);
3287}
3288
Douglas Gregor02085352010-03-31 20:19:30 +00003289QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3290 NestedNameSpecifier *NNS,
3291 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003292 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003293 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3294
3295 if (Canon.isNull()) {
3296 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003297 ElaboratedTypeKeyword CanonKeyword = Keyword;
3298 if (Keyword == ETK_None)
3299 CanonKeyword = ETK_Typename;
3300
3301 if (CanonNNS != NNS || CanonKeyword != Keyword)
3302 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003303 }
3304
3305 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003306 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003307
3308 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003309 DependentNameType *T
3310 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003311 if (T)
3312 return QualType(T, 0);
3313
Douglas Gregor02085352010-03-31 20:19:30 +00003314 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003315 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003316 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003317 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003318}
3319
Mike Stump11289f42009-09-09 15:08:12 +00003320QualType
John McCallc392f372010-06-11 00:33:02 +00003321ASTContext::getDependentTemplateSpecializationType(
3322 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003323 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003324 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003325 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003326 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003327 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003328 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3329 ArgCopy.push_back(Args[I].getArgument());
3330 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3331 ArgCopy.size(),
3332 ArgCopy.data());
3333}
3334
3335QualType
3336ASTContext::getDependentTemplateSpecializationType(
3337 ElaboratedTypeKeyword Keyword,
3338 NestedNameSpecifier *NNS,
3339 const IdentifierInfo *Name,
3340 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003341 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003342 assert((!NNS || NNS->isDependent()) &&
3343 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003344
Douglas Gregorc42075a2010-02-04 18:10:26 +00003345 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003346 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3347 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003348
3349 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00003350 DependentTemplateSpecializationType *T
3351 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003352 if (T)
3353 return QualType(T, 0);
3354
John McCallc392f372010-06-11 00:33:02 +00003355 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003356
John McCallc392f372010-06-11 00:33:02 +00003357 ElaboratedTypeKeyword CanonKeyword = Keyword;
3358 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3359
3360 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003361 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003362 for (unsigned I = 0; I != NumArgs; ++I) {
3363 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3364 if (!CanonArgs[I].structurallyEquals(Args[I]))
3365 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003366 }
3367
John McCallc392f372010-06-11 00:33:02 +00003368 QualType Canon;
3369 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3370 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3371 Name, NumArgs,
3372 CanonArgs.data());
3373
3374 // Find the insert position again.
3375 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3376 }
3377
3378 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3379 sizeof(TemplateArgument) * NumArgs),
3380 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003381 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003382 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003383 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003384 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003385 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003386}
3387
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003388QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003389 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003390 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003391 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003392
3393 assert(Pattern->containsUnexpandedParameterPack() &&
3394 "Pack expansions must expand one or more parameter packs");
3395 void *InsertPos = 0;
3396 PackExpansionType *T
3397 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3398 if (T)
3399 return QualType(T, 0);
3400
3401 QualType Canon;
3402 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003403 Canon = getCanonicalType(Pattern);
3404 // The canonical type might not contain an unexpanded parameter pack, if it
3405 // contains an alias template specialization which ignores one of its
3406 // parameters.
3407 if (Canon->containsUnexpandedParameterPack()) {
3408 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003409
Richard Smith68eea502012-07-16 00:20:35 +00003410 // Find the insert position again, in case we inserted an element into
3411 // PackExpansionTypes and invalidated our insert position.
3412 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3413 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003414 }
3415
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003416 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003417 Types.push_back(T);
3418 PackExpansionTypes.InsertNode(T, InsertPos);
3419 return QualType(T, 0);
3420}
3421
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003422/// CmpProtocolNames - Comparison predicate for sorting protocols
3423/// alphabetically.
3424static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3425 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003426 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003427}
3428
John McCall8b07ec22010-05-15 11:32:37 +00003429static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003430 unsigned NumProtocols) {
3431 if (NumProtocols == 0) return true;
3432
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003433 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3434 return false;
3435
John McCallfc93cf92009-10-22 22:37:11 +00003436 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003437 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3438 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003439 return false;
3440 return true;
3441}
3442
3443static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003444 unsigned &NumProtocols) {
3445 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003446
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003447 // Sort protocols, keyed by name.
3448 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3449
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003450 // Canonicalize.
3451 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3452 Protocols[I] = Protocols[I]->getCanonicalDecl();
3453
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003454 // Remove duplicates.
3455 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3456 NumProtocols = ProtocolsEnd-Protocols;
3457}
3458
John McCall8b07ec22010-05-15 11:32:37 +00003459QualType ASTContext::getObjCObjectType(QualType BaseType,
3460 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003461 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003462 // If the base type is an interface and there aren't any protocols
3463 // to add, then the interface type will do just fine.
3464 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3465 return BaseType;
3466
3467 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003468 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003469 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003470 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003471 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3472 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003473
John McCall8b07ec22010-05-15 11:32:37 +00003474 // Build the canonical type, which has the canonical base type and
3475 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003476 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003477 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3478 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3479 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003480 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003481 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003482 unsigned UniqueCount = NumProtocols;
3483
John McCallfc93cf92009-10-22 22:37:11 +00003484 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003485 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3486 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003487 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003488 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3489 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003490 }
3491
3492 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003493 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3494 }
3495
3496 unsigned Size = sizeof(ObjCObjectTypeImpl);
3497 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3498 void *Mem = Allocate(Size, TypeAlignment);
3499 ObjCObjectTypeImpl *T =
3500 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3501
3502 Types.push_back(T);
3503 ObjCObjectTypes.InsertNode(T, InsertPos);
3504 return QualType(T, 0);
3505}
3506
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003507/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3508/// protocol list adopt all protocols in QT's qualified-id protocol
3509/// list.
3510bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3511 ObjCInterfaceDecl *IC) {
3512 if (!QT->isObjCQualifiedIdType())
3513 return false;
3514
3515 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3516 // If both the right and left sides have qualifiers.
3517 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3518 E = OPT->qual_end(); I != E; ++I) {
3519 ObjCProtocolDecl *Proto = *I;
3520 if (!IC->ClassImplementsProtocol(Proto, false))
3521 return false;
3522 }
3523 return true;
3524 }
3525 return false;
3526}
3527
3528/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3529/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3530/// of protocols.
3531bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3532 ObjCInterfaceDecl *IDecl) {
3533 if (!QT->isObjCQualifiedIdType())
3534 return false;
3535 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3536 if (!OPT)
3537 return false;
3538 if (!IDecl->hasDefinition())
3539 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003540 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3541 CollectInheritedProtocols(IDecl, InheritedProtocols);
3542 if (InheritedProtocols.empty())
3543 return false;
3544
3545 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator PI =
3546 InheritedProtocols.begin(),
3547 E = InheritedProtocols.end(); PI != E; ++PI) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003548 // If both the right and left sides have qualifiers.
3549 bool Adopts = false;
3550 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3551 E = OPT->qual_end(); I != E; ++I) {
3552 ObjCProtocolDecl *Proto = *I;
3553 // return 'true' if '*PI' is in the inheritance hierarchy of Proto
3554 if ((Adopts = ProtocolCompatibleWithProtocol(*PI, Proto)))
3555 break;
3556 }
3557 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003558 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003559 }
3560 return true;
3561}
3562
John McCall8b07ec22010-05-15 11:32:37 +00003563/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3564/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003565QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003566 llvm::FoldingSetNodeID ID;
3567 ObjCObjectPointerType::Profile(ID, ObjectT);
3568
3569 void *InsertPos = 0;
3570 if (ObjCObjectPointerType *QT =
3571 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3572 return QualType(QT, 0);
3573
3574 // Find the canonical object type.
3575 QualType Canonical;
3576 if (!ObjectT.isCanonical()) {
3577 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3578
3579 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003580 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3581 }
3582
Douglas Gregorf85bee62010-02-08 22:59:26 +00003583 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003584 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3585 ObjCObjectPointerType *QType =
3586 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003587
Steve Narofffb4330f2009-06-17 22:40:22 +00003588 Types.push_back(QType);
3589 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003590 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003591}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003592
Douglas Gregor1c283312010-08-11 12:19:30 +00003593/// getObjCInterfaceType - Return the unique reference to the type for the
3594/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003595QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3596 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003597 if (Decl->TypeForDecl)
3598 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003599
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003600 if (PrevDecl) {
3601 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3602 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3603 return QualType(PrevDecl->TypeForDecl, 0);
3604 }
3605
Douglas Gregor7671e532011-12-16 16:34:57 +00003606 // Prefer the definition, if there is one.
3607 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3608 Decl = Def;
3609
Douglas Gregor1c283312010-08-11 12:19:30 +00003610 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3611 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3612 Decl->TypeForDecl = T;
3613 Types.push_back(T);
3614 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003615}
3616
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003617/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3618/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003619/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003620/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003621/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003622QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003623 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003624 if (tofExpr->isTypeDependent()) {
3625 llvm::FoldingSetNodeID ID;
3626 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003627
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003628 void *InsertPos = 0;
3629 DependentTypeOfExprType *Canon
3630 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3631 if (Canon) {
3632 // We already have a "canonical" version of an identical, dependent
3633 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003634 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003635 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003636 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003637 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003638 Canon
3639 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003640 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3641 toe = Canon;
3642 }
3643 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003644 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003645 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003646 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003647 Types.push_back(toe);
3648 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003649}
3650
Steve Naroffa773cd52007-08-01 18:02:17 +00003651/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3652/// TypeOfType AST's. The only motivation to unique these nodes would be
3653/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003654/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003655/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003656QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003657 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003658 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003659 Types.push_back(tot);
3660 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003661}
3662
Anders Carlssonad6bd352009-06-24 21:24:56 +00003663
Anders Carlsson81df7b82009-06-24 19:06:50 +00003664/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3665/// DecltypeType AST's. The only motivation to unique these nodes would be
3666/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003667/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003668/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003669QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003670 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003671
3672 // C++0x [temp.type]p2:
3673 // If an expression e involves a template parameter, decltype(e) denotes a
3674 // unique dependent type. Two such decltype-specifiers refer to the same
3675 // type only if their expressions are equivalent (14.5.6.1).
3676 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003677 llvm::FoldingSetNodeID ID;
3678 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003679
Douglas Gregora21f6c32009-07-30 23:36:40 +00003680 void *InsertPos = 0;
3681 DependentDecltypeType *Canon
3682 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3683 if (Canon) {
3684 // We already have a "canonical" version of an equivalent, dependent
3685 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003686 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003687 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003688 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003689 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003690 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003691 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3692 dt = Canon;
3693 }
3694 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003695 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3696 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003697 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003698 Types.push_back(dt);
3699 return QualType(dt, 0);
3700}
3701
Alexis Hunte852b102011-05-24 22:41:36 +00003702/// getUnaryTransformationType - We don't unique these, since the memory
3703/// savings are minimal and these are rare.
3704QualType ASTContext::getUnaryTransformType(QualType BaseType,
3705 QualType UnderlyingType,
3706 UnaryTransformType::UTTKind Kind)
3707 const {
3708 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003709 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3710 Kind,
3711 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003712 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003713 Types.push_back(Ty);
3714 return QualType(Ty, 0);
3715}
3716
Richard Smith2a7d4812013-05-04 07:00:32 +00003717/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3718/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3719/// canonical deduced-but-dependent 'auto' type.
3720QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003721 bool IsDependent) const {
3722 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003723 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003724
Richard Smith2a7d4812013-05-04 07:00:32 +00003725 // Look in the folding set for an existing type.
Richard Smithb2bc2e62011-02-21 20:05:19 +00003726 void *InsertPos = 0;
Richard Smith2a7d4812013-05-04 07:00:32 +00003727 llvm::FoldingSetNodeID ID;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003728 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003729 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3730 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003731
Richard Smith74aeef52013-04-26 16:15:35 +00003732 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003733 IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003734 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003735 Types.push_back(AT);
3736 if (InsertPos)
3737 AutoTypes.InsertNode(AT, InsertPos);
3738 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003739}
3740
Eli Friedman0dfb8892011-10-06 23:00:33 +00003741/// getAtomicType - Return the uniqued reference to the atomic type for
3742/// the given value type.
3743QualType ASTContext::getAtomicType(QualType T) const {
3744 // Unique pointers, to guarantee there is only one pointer of a particular
3745 // structure.
3746 llvm::FoldingSetNodeID ID;
3747 AtomicType::Profile(ID, T);
3748
3749 void *InsertPos = 0;
3750 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3751 return QualType(AT, 0);
3752
3753 // If the atomic value type isn't canonical, this won't be a canonical type
3754 // either, so fill in the canonical type field.
3755 QualType Canonical;
3756 if (!T.isCanonical()) {
3757 Canonical = getAtomicType(getCanonicalType(T));
3758
3759 // Get the new insert position for the node we care about.
3760 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3761 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3762 }
3763 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3764 Types.push_back(New);
3765 AtomicTypes.InsertNode(New, InsertPos);
3766 return QualType(New, 0);
3767}
3768
Richard Smith02e85f32011-04-14 22:09:26 +00003769/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3770QualType ASTContext::getAutoDeductType() const {
3771 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00003772 AutoDeductTy = QualType(
3773 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003774 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00003775 0);
Richard Smith02e85f32011-04-14 22:09:26 +00003776 return AutoDeductTy;
3777}
3778
3779/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3780QualType ASTContext::getAutoRRefDeductType() const {
3781 if (AutoRRefDeductTy.isNull())
3782 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3783 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3784 return AutoRRefDeductTy;
3785}
3786
Chris Lattnerfb072462007-01-23 05:45:31 +00003787/// getTagDeclType - Return the unique reference to the type for the
3788/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003789QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003790 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003791 // FIXME: What is the design on getTagDeclType when it requires casting
3792 // away const? mutable?
3793 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003794}
3795
Mike Stump11289f42009-09-09 15:08:12 +00003796/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3797/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3798/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003799CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003800 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003801}
Chris Lattnerfb072462007-01-23 05:45:31 +00003802
Hans Wennborg27541db2011-10-27 08:29:09 +00003803/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3804CanQualType ASTContext::getIntMaxType() const {
3805 return getFromTargetType(Target->getIntMaxType());
3806}
3807
3808/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3809CanQualType ASTContext::getUIntMaxType() const {
3810 return getFromTargetType(Target->getUIntMaxType());
3811}
3812
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003813/// getSignedWCharType - Return the type of "signed wchar_t".
3814/// Used when in C++, as a GCC extension.
3815QualType ASTContext::getSignedWCharType() const {
3816 // FIXME: derive from "Target" ?
3817 return WCharTy;
3818}
3819
3820/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3821/// Used when in C++, as a GCC extension.
3822QualType ASTContext::getUnsignedWCharType() const {
3823 // FIXME: derive from "Target" ?
3824 return UnsignedIntTy;
3825}
3826
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00003827QualType ASTContext::getIntPtrType() const {
3828 return getFromTargetType(Target->getIntPtrType());
3829}
3830
3831QualType ASTContext::getUIntPtrType() const {
3832 return getCorrespondingUnsignedType(getIntPtrType());
3833}
3834
Hans Wennborg27541db2011-10-27 08:29:09 +00003835/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003836/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3837QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003838 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003839}
3840
Eli Friedman4e91899e2012-11-27 02:58:24 +00003841/// \brief Return the unique type for "pid_t" defined in
3842/// <sys/types.h>. We need this to compute the correct type for vfork().
3843QualType ASTContext::getProcessIDType() const {
3844 return getFromTargetType(Target->getProcessIDType());
3845}
3846
Chris Lattnera21ad802008-04-02 05:18:44 +00003847//===----------------------------------------------------------------------===//
3848// Type Operators
3849//===----------------------------------------------------------------------===//
3850
Jay Foad39c79802011-01-12 09:06:06 +00003851CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003852 // Push qualifiers into arrays, and then discard any remaining
3853 // qualifiers.
3854 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003855 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003856 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003857 QualType Result;
3858 if (isa<ArrayType>(Ty)) {
3859 Result = getArrayDecayedType(QualType(Ty,0));
3860 } else if (isa<FunctionType>(Ty)) {
3861 Result = getPointerType(QualType(Ty, 0));
3862 } else {
3863 Result = QualType(Ty, 0);
3864 }
3865
3866 return CanQualType::CreateUnsafe(Result);
3867}
3868
John McCall6c9dd522011-01-18 07:41:22 +00003869QualType ASTContext::getUnqualifiedArrayType(QualType type,
3870 Qualifiers &quals) {
3871 SplitQualType splitType = type.getSplitUnqualifiedType();
3872
3873 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3874 // the unqualified desugared type and then drops it on the floor.
3875 // We then have to strip that sugar back off with
3876 // getUnqualifiedDesugaredType(), which is silly.
3877 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003878 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003879
3880 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003881 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003882 quals = splitType.Quals;
3883 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003884 }
3885
John McCall6c9dd522011-01-18 07:41:22 +00003886 // Otherwise, recurse on the array's element type.
3887 QualType elementType = AT->getElementType();
3888 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3889
3890 // If that didn't change the element type, AT has no qualifiers, so we
3891 // can just use the results in splitType.
3892 if (elementType == unqualElementType) {
3893 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003894 quals = splitType.Quals;
3895 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003896 }
3897
3898 // Otherwise, add in the qualifiers from the outermost type, then
3899 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003900 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003901
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003902 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003903 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003904 CAT->getSizeModifier(), 0);
3905 }
3906
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003907 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003908 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003909 }
3910
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003911 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003912 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003913 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003914 VAT->getSizeModifier(),
3915 VAT->getIndexTypeCVRQualifiers(),
3916 VAT->getBracketsRange());
3917 }
3918
3919 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003920 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003921 DSAT->getSizeModifier(), 0,
3922 SourceRange());
3923}
3924
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003925/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3926/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3927/// they point to and return true. If T1 and T2 aren't pointer types
3928/// or pointer-to-member types, or if they are not similar at this
3929/// level, returns false and leaves T1 and T2 unchanged. Top-level
3930/// qualifiers on T1 and T2 are ignored. This function will typically
3931/// be called in a loop that successively "unwraps" pointer and
3932/// pointer-to-member types to compare them at each level.
3933bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3934 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3935 *T2PtrType = T2->getAs<PointerType>();
3936 if (T1PtrType && T2PtrType) {
3937 T1 = T1PtrType->getPointeeType();
3938 T2 = T2PtrType->getPointeeType();
3939 return true;
3940 }
3941
3942 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3943 *T2MPType = T2->getAs<MemberPointerType>();
3944 if (T1MPType && T2MPType &&
3945 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3946 QualType(T2MPType->getClass(), 0))) {
3947 T1 = T1MPType->getPointeeType();
3948 T2 = T2MPType->getPointeeType();
3949 return true;
3950 }
3951
David Blaikiebbafb8a2012-03-11 07:00:24 +00003952 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003953 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3954 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3955 if (T1OPType && T2OPType) {
3956 T1 = T1OPType->getPointeeType();
3957 T2 = T2OPType->getPointeeType();
3958 return true;
3959 }
3960 }
3961
3962 // FIXME: Block pointers, too?
3963
3964 return false;
3965}
3966
Jay Foad39c79802011-01-12 09:06:06 +00003967DeclarationNameInfo
3968ASTContext::getNameForTemplate(TemplateName Name,
3969 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003970 switch (Name.getKind()) {
3971 case TemplateName::QualifiedTemplate:
3972 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003973 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003974 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3975 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003976
John McCalld9dfe3a2011-06-30 08:33:18 +00003977 case TemplateName::OverloadedTemplate: {
3978 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3979 // DNInfo work in progress: CHECKME: what about DNLoc?
3980 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3981 }
3982
3983 case TemplateName::DependentTemplate: {
3984 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003985 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003986 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003987 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3988 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003989 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003990 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3991 // DNInfo work in progress: FIXME: source locations?
3992 DeclarationNameLoc DNLoc;
3993 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3994 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3995 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003996 }
3997 }
3998
John McCalld9dfe3a2011-06-30 08:33:18 +00003999 case TemplateName::SubstTemplateTemplateParm: {
4000 SubstTemplateTemplateParmStorage *subst
4001 = Name.getAsSubstTemplateTemplateParm();
4002 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4003 NameLoc);
4004 }
4005
4006 case TemplateName::SubstTemplateTemplateParmPack: {
4007 SubstTemplateTemplateParmPackStorage *subst
4008 = Name.getAsSubstTemplateTemplateParmPack();
4009 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4010 NameLoc);
4011 }
4012 }
4013
4014 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004015}
4016
Jay Foad39c79802011-01-12 09:06:06 +00004017TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004018 switch (Name.getKind()) {
4019 case TemplateName::QualifiedTemplate:
4020 case TemplateName::Template: {
4021 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004022 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004023 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004024 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4025
4026 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004027 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004028 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004029
John McCalld9dfe3a2011-06-30 08:33:18 +00004030 case TemplateName::OverloadedTemplate:
4031 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004032
John McCalld9dfe3a2011-06-30 08:33:18 +00004033 case TemplateName::DependentTemplate: {
4034 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4035 assert(DTN && "Non-dependent template names must refer to template decls.");
4036 return DTN->CanonicalTemplateName;
4037 }
4038
4039 case TemplateName::SubstTemplateTemplateParm: {
4040 SubstTemplateTemplateParmStorage *subst
4041 = Name.getAsSubstTemplateTemplateParm();
4042 return getCanonicalTemplateName(subst->getReplacement());
4043 }
4044
4045 case TemplateName::SubstTemplateTemplateParmPack: {
4046 SubstTemplateTemplateParmPackStorage *subst
4047 = Name.getAsSubstTemplateTemplateParmPack();
4048 TemplateTemplateParmDecl *canonParameter
4049 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4050 TemplateArgument canonArgPack
4051 = getCanonicalTemplateArgument(subst->getArgumentPack());
4052 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4053 }
4054 }
4055
4056 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004057}
4058
Douglas Gregoradee3e32009-11-11 23:06:43 +00004059bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4060 X = getCanonicalTemplateName(X);
4061 Y = getCanonicalTemplateName(Y);
4062 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4063}
4064
Mike Stump11289f42009-09-09 15:08:12 +00004065TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004066ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004067 switch (Arg.getKind()) {
4068 case TemplateArgument::Null:
4069 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004070
Douglas Gregora8e02e72009-07-28 23:00:59 +00004071 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004072 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004073
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004074 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004075 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4076 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004077 }
Mike Stump11289f42009-09-09 15:08:12 +00004078
Eli Friedmanb826a002012-09-26 02:36:12 +00004079 case TemplateArgument::NullPtr:
4080 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4081 /*isNullPtr*/true);
4082
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004083 case TemplateArgument::Template:
4084 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004085
4086 case TemplateArgument::TemplateExpansion:
4087 return TemplateArgument(getCanonicalTemplateName(
4088 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004089 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004090
Douglas Gregora8e02e72009-07-28 23:00:59 +00004091 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004092 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004093
Douglas Gregora8e02e72009-07-28 23:00:59 +00004094 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004095 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004096
Douglas Gregora8e02e72009-07-28 23:00:59 +00004097 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004098 if (Arg.pack_size() == 0)
4099 return Arg;
4100
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004101 TemplateArgument *CanonArgs
4102 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004103 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004104 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004105 AEnd = Arg.pack_end();
4106 A != AEnd; (void)++A, ++Idx)
4107 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004108
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004109 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00004110 }
4111 }
4112
4113 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004114 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004115}
4116
Douglas Gregor333489b2009-03-27 23:10:48 +00004117NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004118ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004119 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00004120 return 0;
4121
4122 switch (NNS->getKind()) {
4123 case NestedNameSpecifier::Identifier:
4124 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004125 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004126 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4127 NNS->getAsIdentifier());
4128
4129 case NestedNameSpecifier::Namespace:
4130 // A namespace is canonical; build a nested-name-specifier with
4131 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004132 return NestedNameSpecifier::Create(*this, 0,
4133 NNS->getAsNamespace()->getOriginalNamespace());
4134
4135 case NestedNameSpecifier::NamespaceAlias:
4136 // A namespace is canonical; build a nested-name-specifier with
4137 // this namespace and no prefix.
4138 return NestedNameSpecifier::Create(*this, 0,
4139 NNS->getAsNamespaceAlias()->getNamespace()
4140 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004141
4142 case NestedNameSpecifier::TypeSpec:
4143 case NestedNameSpecifier::TypeSpecWithTemplate: {
4144 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004145
4146 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4147 // break it apart into its prefix and identifier, then reconsititute those
4148 // as the canonical nested-name-specifier. This is required to canonicalize
4149 // a dependent nested-name-specifier involving typedefs of dependent-name
4150 // types, e.g.,
4151 // typedef typename T::type T1;
4152 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004153 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4154 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004155 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004156
Eli Friedman5358a0a2012-03-03 04:09:56 +00004157 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4158 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4159 // first place?
John McCall33ddac02011-01-19 10:06:00 +00004160 return NestedNameSpecifier::Create(*this, 0, false,
4161 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004162 }
4163
4164 case NestedNameSpecifier::Global:
4165 // The global specifier is canonical and unique.
4166 return NNS;
4167 }
4168
David Blaikie8a40f702012-01-17 06:56:22 +00004169 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004170}
4171
Chris Lattner7adf0762008-08-04 07:31:14 +00004172
Jay Foad39c79802011-01-12 09:06:06 +00004173const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004174 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004175 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004176 // Handle the common positive case fast.
4177 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4178 return AT;
4179 }
Mike Stump11289f42009-09-09 15:08:12 +00004180
John McCall8ccfcb52009-09-24 19:53:00 +00004181 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004182 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00004183 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004184
John McCall8ccfcb52009-09-24 19:53:00 +00004185 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004186 // implements C99 6.7.3p8: "If the specification of an array type includes
4187 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004188
Chris Lattner7adf0762008-08-04 07:31:14 +00004189 // If we get here, we either have type qualifiers on the type, or we have
4190 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004191 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004192
John McCall33ddac02011-01-19 10:06:00 +00004193 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004194 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004195
Chris Lattner7adf0762008-08-04 07:31:14 +00004196 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004197 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00004198 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004199 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004200
Chris Lattner7adf0762008-08-04 07:31:14 +00004201 // Otherwise, we have an array and we have qualifiers on it. Push the
4202 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004203 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004204
Chris Lattner7adf0762008-08-04 07:31:14 +00004205 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4206 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4207 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004208 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004209 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4210 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4211 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004212 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004213
Mike Stump11289f42009-09-09 15:08:12 +00004214 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004215 = dyn_cast<DependentSizedArrayType>(ATy))
4216 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004217 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004218 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004219 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004220 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004221 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004222
Chris Lattner7adf0762008-08-04 07:31:14 +00004223 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004224 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004225 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004226 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004227 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004228 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004229}
4230
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004231QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004232 if (T->isArrayType() || T->isFunctionType())
4233 return getDecayedType(T);
4234 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004235}
4236
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004237QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004238 T = getVariableArrayDecayedType(T);
4239 T = getAdjustedParameterType(T);
4240 return T.getUnqualifiedType();
4241}
4242
Chris Lattnera21ad802008-04-02 05:18:44 +00004243/// getArrayDecayedType - Return the properly qualified result of decaying the
4244/// specified array type to a pointer. This operation is non-trivial when
4245/// handling typedefs etc. The canonical type of "T" must be an array type,
4246/// this returns a pointer to a properly qualified element of the array.
4247///
4248/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004249QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004250 // Get the element type with 'getAsArrayType' so that we don't lose any
4251 // typedefs in the element type of the array. This also handles propagation
4252 // of type qualifiers from the array type into the element type if present
4253 // (C99 6.7.3p8).
4254 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4255 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004256
Chris Lattner7adf0762008-08-04 07:31:14 +00004257 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004258
4259 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004260 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004261}
4262
John McCall33ddac02011-01-19 10:06:00 +00004263QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4264 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004265}
4266
John McCall33ddac02011-01-19 10:06:00 +00004267QualType ASTContext::getBaseElementType(QualType type) const {
4268 Qualifiers qs;
4269 while (true) {
4270 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004271 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004272 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004273
John McCall33ddac02011-01-19 10:06:00 +00004274 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004275 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004276 }
Mike Stump11289f42009-09-09 15:08:12 +00004277
John McCall33ddac02011-01-19 10:06:00 +00004278 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004279}
4280
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004281/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004282uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004283ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4284 uint64_t ElementCount = 1;
4285 do {
4286 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004287 CA = dyn_cast_or_null<ConstantArrayType>(
4288 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004289 } while (CA);
4290 return ElementCount;
4291}
4292
Steve Naroff0af91202007-04-27 21:51:21 +00004293/// getFloatingRank - Return a relative rank for floating point types.
4294/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004295static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004296 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004297 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004298
John McCall9dd450b2009-09-21 23:43:11 +00004299 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4300 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004301 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004302 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004303 case BuiltinType::Float: return FloatRank;
4304 case BuiltinType::Double: return DoubleRank;
4305 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004306 }
4307}
4308
Mike Stump11289f42009-09-09 15:08:12 +00004309/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4310/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004311/// 'typeDomain' is a real floating point or complex type.
4312/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004313QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4314 QualType Domain) const {
4315 FloatingRank EltRank = getFloatingRank(Size);
4316 if (Domain->isComplexType()) {
4317 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004318 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004319 case FloatRank: return FloatComplexTy;
4320 case DoubleRank: return DoubleComplexTy;
4321 case LongDoubleRank: return LongDoubleComplexTy;
4322 }
Steve Naroff0af91202007-04-27 21:51:21 +00004323 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004324
4325 assert(Domain->isRealFloatingType() && "Unknown domain!");
4326 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004327 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004328 case FloatRank: return FloatTy;
4329 case DoubleRank: return DoubleTy;
4330 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004331 }
David Blaikief47fa302012-01-17 02:30:50 +00004332 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004333}
4334
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004335/// getFloatingTypeOrder - Compare the rank of the two specified floating
4336/// point types, ignoring the domain of the type (i.e. 'double' ==
4337/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004338/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004339int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004340 FloatingRank LHSR = getFloatingRank(LHS);
4341 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004342
Chris Lattnerb90739d2008-04-06 23:38:49 +00004343 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004344 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004345 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004346 return 1;
4347 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004348}
4349
Chris Lattner76a00cf2008-04-06 22:59:24 +00004350/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4351/// routine will assert if passed a built-in type that isn't an integer or enum,
4352/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004353unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004354 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004355
Chris Lattner76a00cf2008-04-06 22:59:24 +00004356 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004357 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004358 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004359 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004360 case BuiltinType::Char_S:
4361 case BuiltinType::Char_U:
4362 case BuiltinType::SChar:
4363 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004364 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004365 case BuiltinType::Short:
4366 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004367 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004368 case BuiltinType::Int:
4369 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004370 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004371 case BuiltinType::Long:
4372 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004373 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004374 case BuiltinType::LongLong:
4375 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004376 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004377 case BuiltinType::Int128:
4378 case BuiltinType::UInt128:
4379 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004380 }
4381}
4382
Eli Friedman629ffb92009-08-20 04:21:42 +00004383/// \brief Whether this is a promotable bitfield reference according
4384/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4385///
4386/// \returns the type this bit-field will promote to, or NULL if no
4387/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004388QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004389 if (E->isTypeDependent() || E->isValueDependent())
4390 return QualType();
4391
John McCalld25db7e2013-05-06 21:39:12 +00004392 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004393 if (!Field)
4394 return QualType();
4395
4396 QualType FT = Field->getType();
4397
Richard Smithcaf33902011-10-10 18:28:20 +00004398 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004399 uint64_t IntSize = getTypeSize(IntTy);
4400 // GCC extension compatibility: if the bit-field size is less than or equal
4401 // to the size of int, it gets promoted no matter what its type is.
4402 // For instance, unsigned long bf : 4 gets promoted to signed int.
4403 if (BitWidth < IntSize)
4404 return IntTy;
4405
4406 if (BitWidth == IntSize)
4407 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4408
4409 // Types bigger than int are not subject to promotions, and therefore act
4410 // like the base type.
4411 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4412 // is ridiculous.
4413 return QualType();
4414}
4415
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004416/// getPromotedIntegerType - Returns the type that Promotable will
4417/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4418/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004419QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004420 assert(!Promotable.isNull());
4421 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004422 if (const EnumType *ET = Promotable->getAs<EnumType>())
4423 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004424
4425 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4426 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4427 // (3.9.1) can be converted to a prvalue of the first of the following
4428 // types that can represent all the values of its underlying type:
4429 // int, unsigned int, long int, unsigned long int, long long int, or
4430 // unsigned long long int [...]
4431 // FIXME: Is there some better way to compute this?
4432 if (BT->getKind() == BuiltinType::WChar_S ||
4433 BT->getKind() == BuiltinType::WChar_U ||
4434 BT->getKind() == BuiltinType::Char16 ||
4435 BT->getKind() == BuiltinType::Char32) {
4436 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4437 uint64_t FromSize = getTypeSize(BT);
4438 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4439 LongLongTy, UnsignedLongLongTy };
4440 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4441 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4442 if (FromSize < ToSize ||
4443 (FromSize == ToSize &&
4444 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4445 return PromoteTypes[Idx];
4446 }
4447 llvm_unreachable("char type should fit into long long");
4448 }
4449 }
4450
4451 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004452 if (Promotable->isSignedIntegerType())
4453 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004454 uint64_t PromotableSize = getIntWidth(Promotable);
4455 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004456 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4457 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4458}
4459
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004460/// \brief Recurses in pointer/array types until it finds an objc retainable
4461/// type and returns its ownership.
4462Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4463 while (!T.isNull()) {
4464 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4465 return T.getObjCLifetime();
4466 if (T->isArrayType())
4467 T = getBaseElementType(T);
4468 else if (const PointerType *PT = T->getAs<PointerType>())
4469 T = PT->getPointeeType();
4470 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004471 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004472 else
4473 break;
4474 }
4475
4476 return Qualifiers::OCL_None;
4477}
4478
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004479static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4480 // Incomplete enum types are not treated as integer types.
4481 // FIXME: In C++, enum types are never integer types.
4482 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4483 return ET->getDecl()->getIntegerType().getTypePtr();
4484 return NULL;
4485}
4486
Mike Stump11289f42009-09-09 15:08:12 +00004487/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004488/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004489/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004490int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004491 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4492 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004493
4494 // Unwrap enums to their underlying type.
4495 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4496 LHSC = getIntegerTypeForEnum(ET);
4497 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4498 RHSC = getIntegerTypeForEnum(ET);
4499
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004500 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004501
Chris Lattner76a00cf2008-04-06 22:59:24 +00004502 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4503 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004504
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004505 unsigned LHSRank = getIntegerRank(LHSC);
4506 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004507
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004508 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4509 if (LHSRank == RHSRank) return 0;
4510 return LHSRank > RHSRank ? 1 : -1;
4511 }
Mike Stump11289f42009-09-09 15:08:12 +00004512
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004513 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4514 if (LHSUnsigned) {
4515 // If the unsigned [LHS] type is larger, return it.
4516 if (LHSRank >= RHSRank)
4517 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004518
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004519 // If the signed type can represent all values of the unsigned type, it
4520 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004521 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004522 return -1;
4523 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004524
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004525 // If the unsigned [RHS] type is larger, return it.
4526 if (RHSRank >= LHSRank)
4527 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004528
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004529 // If the signed type can represent all values of the unsigned type, it
4530 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004531 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004532 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004533}
Anders Carlsson98f07902007-08-17 05:31:46 +00004534
Mike Stump11289f42009-09-09 15:08:12 +00004535// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004536QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004537 if (!CFConstantStringTypeDecl) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004538 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
John McCallae580fe2010-02-05 01:33:36 +00004539 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004540
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004541 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004542
Anders Carlsson98f07902007-08-17 05:31:46 +00004543 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004544 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004545 // int flags;
4546 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004547 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004548 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004549 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004550 FieldTypes[3] = LongTy;
4551
Anders Carlsson98f07902007-08-17 05:31:46 +00004552 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004553 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004554 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004555 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004556 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004557 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004558 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004559 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004560 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004561 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004562 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004563 }
4564
Douglas Gregord5058122010-02-11 01:19:42 +00004565 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004566 }
Mike Stump11289f42009-09-09 15:08:12 +00004567
Anders Carlsson98f07902007-08-17 05:31:46 +00004568 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004569}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004570
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004571QualType ASTContext::getObjCSuperType() const {
4572 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004573 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004574 TUDecl->addDecl(ObjCSuperTypeDecl);
4575 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4576 }
4577 return ObjCSuperType;
4578}
4579
Douglas Gregor512b0772009-04-23 22:29:11 +00004580void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004581 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004582 assert(Rec && "Invalid CFConstantStringType");
4583 CFConstantStringTypeDecl = Rec->getDecl();
4584}
4585
Jay Foad39c79802011-01-12 09:06:06 +00004586QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004587 if (BlockDescriptorType)
4588 return getTagDeclType(BlockDescriptorType);
4589
Alp Toker2dea15b2013-12-17 01:22:38 +00004590 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004591 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004592 RD = buildImplicitRecord("__block_descriptor");
4593 RD->startDefinition();
4594
Mike Stumpd0153282009-10-20 02:12:22 +00004595 QualType FieldTypes[] = {
4596 UnsignedLongTy,
4597 UnsignedLongTy,
4598 };
4599
Craig Topperd6d31ac2013-07-15 08:24:27 +00004600 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004601 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004602 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004603 };
4604
4605 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004606 FieldDecl *Field = FieldDecl::Create(
4607 *this, RD, SourceLocation(), SourceLocation(),
4608 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/0,
4609 /*BitWidth=*/0, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004610 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004611 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004612 }
4613
Alp Toker2dea15b2013-12-17 01:22:38 +00004614 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004615
Alp Toker2dea15b2013-12-17 01:22:38 +00004616 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004617
4618 return getTagDeclType(BlockDescriptorType);
4619}
4620
Jay Foad39c79802011-01-12 09:06:06 +00004621QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004622 if (BlockDescriptorExtendedType)
4623 return getTagDeclType(BlockDescriptorExtendedType);
4624
Alp Toker2dea15b2013-12-17 01:22:38 +00004625 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004626 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004627 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4628 RD->startDefinition();
4629
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004630 QualType FieldTypes[] = {
4631 UnsignedLongTy,
4632 UnsignedLongTy,
4633 getPointerType(VoidPtrTy),
4634 getPointerType(VoidPtrTy)
4635 };
4636
Craig Topperd6d31ac2013-07-15 08:24:27 +00004637 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004638 "reserved",
4639 "Size",
4640 "CopyFuncPtr",
4641 "DestroyFuncPtr"
4642 };
4643
4644 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004645 FieldDecl *Field = FieldDecl::Create(
4646 *this, RD, SourceLocation(), SourceLocation(),
4647 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/0,
4648 /*BitWidth=*/0,
4649 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004650 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004651 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004652 }
4653
Alp Toker2dea15b2013-12-17 01:22:38 +00004654 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004655
Alp Toker2dea15b2013-12-17 01:22:38 +00004656 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004657 return getTagDeclType(BlockDescriptorExtendedType);
4658}
4659
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004660/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4661/// requires copy/dispose. Note that this must match the logic
4662/// in buildByrefHelpers.
4663bool ASTContext::BlockRequiresCopying(QualType Ty,
4664 const VarDecl *D) {
4665 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4666 const Expr *copyExpr = getBlockVarCopyInits(D);
4667 if (!copyExpr && record->hasTrivialDestructor()) return false;
4668
Mike Stump94967902009-10-21 18:16:27 +00004669 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004670 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004671
4672 if (!Ty->isObjCRetainableType()) return false;
4673
4674 Qualifiers qs = Ty.getQualifiers();
4675
4676 // If we have lifetime, that dominates.
4677 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4678 assert(getLangOpts().ObjCAutoRefCount);
4679
4680 switch (lifetime) {
4681 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4682
4683 // These are just bits as far as the runtime is concerned.
4684 case Qualifiers::OCL_ExplicitNone:
4685 case Qualifiers::OCL_Autoreleasing:
4686 return false;
4687
4688 // Tell the runtime that this is ARC __weak, called by the
4689 // byref routines.
4690 case Qualifiers::OCL_Weak:
4691 // ARC __strong __block variables need to be retained.
4692 case Qualifiers::OCL_Strong:
4693 return true;
4694 }
4695 llvm_unreachable("fell out of lifetime switch!");
4696 }
4697 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4698 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004699}
4700
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004701bool ASTContext::getByrefLifetime(QualType Ty,
4702 Qualifiers::ObjCLifetime &LifeTime,
4703 bool &HasByrefExtendedLayout) const {
4704
4705 if (!getLangOpts().ObjC1 ||
4706 getLangOpts().getGC() != LangOptions::NonGC)
4707 return false;
4708
4709 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004710 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004711 HasByrefExtendedLayout = true;
4712 LifeTime = Qualifiers::OCL_None;
4713 }
4714 else if (getLangOpts().ObjCAutoRefCount)
4715 LifeTime = Ty.getObjCLifetime();
4716 // MRR.
4717 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4718 LifeTime = Qualifiers::OCL_ExplicitNone;
4719 else
4720 LifeTime = Qualifiers::OCL_None;
4721 return true;
4722}
4723
Douglas Gregorbab8a962011-09-08 01:46:34 +00004724TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4725 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00004726 ObjCInstanceTypeDecl =
4727 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00004728 return ObjCInstanceTypeDecl;
4729}
4730
Anders Carlsson18acd442007-10-29 06:33:42 +00004731// This returns true if a type has been typedefed to BOOL:
4732// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004733static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004734 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004735 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4736 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004737
Anders Carlssond8499822007-10-29 05:01:08 +00004738 return false;
4739}
4740
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004741/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004742/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004743CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004744 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4745 return CharUnits::Zero();
4746
Ken Dyck40775002010-01-11 17:06:35 +00004747 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004748
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004749 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004750 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004751 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004752 // Treat arrays as pointers, since that's how they're passed in.
4753 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004754 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004755 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004756}
4757
4758static inline
4759std::string charUnitsToString(const CharUnits &CU) {
4760 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004761}
4762
John McCall351762c2011-02-07 10:33:21 +00004763/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004764/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004765std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4766 std::string S;
4767
David Chisnall950a9512009-11-17 19:33:30 +00004768 const BlockDecl *Decl = Expr->getBlockDecl();
4769 QualType BlockTy =
4770 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4771 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004772 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00004773 getObjCEncodingForMethodParameter(
4774 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
4775 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004776 else
Alp Toker314cc812014-01-25 16:55:45 +00004777 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004778 // Compute size of all parameters.
4779 // Start with computing size of a pointer in number of bytes.
4780 // FIXME: There might(should) be a better way of doing this computation!
4781 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004782 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4783 CharUnits ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00004784 for (auto PI : Decl->params()) {
4785 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004786 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004787 if (sz.isZero())
4788 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004789 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004790 ParmOffset += sz;
4791 }
4792 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004793 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004794 // Block pointer and offset.
4795 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004796
4797 // Argument types.
4798 ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00004799 for (auto PVDecl : Decl->params()) {
David Chisnall950a9512009-11-17 19:33:30 +00004800 QualType PType = PVDecl->getOriginalType();
4801 if (const ArrayType *AT =
4802 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4803 // Use array's original type only if it has known number of
4804 // elements.
4805 if (!isa<ConstantArrayType>(AT))
4806 PType = PVDecl->getType();
4807 } else if (PType->isFunctionType())
4808 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004809 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004810 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4811 S, true /*Extended*/);
4812 else
4813 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004814 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004815 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004816 }
John McCall351762c2011-02-07 10:33:21 +00004817
4818 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004819}
4820
Douglas Gregora9d84932011-05-27 01:19:52 +00004821bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004822 std::string& S) {
4823 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00004824 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00004825 CharUnits ParmOffset;
4826 // Compute size of all parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00004827 for (auto PI : Decl->params()) {
4828 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00004829 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004830 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004831 continue;
4832
David Chisnall50e4eba2010-12-30 14:05:53 +00004833 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004834 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004835 ParmOffset += sz;
4836 }
4837 S += charUnitsToString(ParmOffset);
4838 ParmOffset = CharUnits::Zero();
4839
4840 // Argument types.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00004841 for (auto PVDecl : Decl->params()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00004842 QualType PType = PVDecl->getOriginalType();
4843 if (const ArrayType *AT =
4844 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4845 // Use array's original type only if it has known number of
4846 // elements.
4847 if (!isa<ConstantArrayType>(AT))
4848 PType = PVDecl->getType();
4849 } else if (PType->isFunctionType())
4850 PType = PVDecl->getType();
4851 getObjCEncodingForType(PType, S);
4852 S += charUnitsToString(ParmOffset);
4853 ParmOffset += getObjCEncodingTypeSize(PType);
4854 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004855
4856 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004857}
4858
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004859/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4860/// method parameter or return type. If Extended, include class names and
4861/// block object types.
4862void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4863 QualType T, std::string& S,
4864 bool Extended) const {
4865 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4866 getObjCEncodingForTypeQualifier(QT, S);
4867 // Encode parameter type.
4868 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4869 true /*OutermostType*/,
4870 false /*EncodingProperty*/,
4871 false /*StructField*/,
4872 Extended /*EncodeBlockParameters*/,
4873 Extended /*EncodeClassNames*/);
4874}
4875
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004876/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004877/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004878bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004879 std::string& S,
4880 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004881 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004882 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00004883 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4884 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004885 // Compute size of all parameters.
4886 // Start with computing size of a pointer in number of bytes.
4887 // FIXME: There might(should) be a better way of doing this computation!
4888 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004889 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004890 // The first two arguments (self and _cmd) are pointers; account for
4891 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004892 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004893 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004894 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004895 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004896 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004897 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004898 continue;
4899
Ken Dyck40775002010-01-11 17:06:35 +00004900 assert (sz.isPositive() &&
4901 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004902 ParmOffset += sz;
4903 }
Ken Dyck40775002010-01-11 17:06:35 +00004904 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004905 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004906 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004907
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004908 // Argument types.
4909 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004910 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004911 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004912 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004913 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004914 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004915 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4916 // Use array's original type only if it has known number of
4917 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004918 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004919 PType = PVDecl->getType();
4920 } else if (PType->isFunctionType())
4921 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004922 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4923 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004924 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004925 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004926 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004927
4928 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004929}
4930
Fariborz Jahaniandad96302014-01-22 19:02:20 +00004931ObjCPropertyImplDecl *
4932ASTContext::getObjCPropertyImplDeclForPropertyDecl(
4933 const ObjCPropertyDecl *PD,
4934 const Decl *Container) const {
4935 if (!Container)
4936 return 0;
4937 if (const ObjCCategoryImplDecl *CID =
4938 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00004939 for (auto *PID : CID->property_impls())
4940 if (PID->getPropertyDecl() == PD)
4941 return PID;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00004942 } else {
4943 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Aaron Ballmand85eff42014-03-14 15:02:45 +00004944 for (auto *PID : OID->property_impls())
Fariborz Jahaniandad96302014-01-22 19:02:20 +00004945 if (PID->getPropertyDecl() == PD)
4946 return PID;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00004947 }
4948 return 0;
4949}
4950
Daniel Dunbar4932b362008-08-28 04:38:10 +00004951/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004952/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004953/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4954/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004955/// Property attributes are stored as a comma-delimited C string. The simple
4956/// attributes readonly and bycopy are encoded as single characters. The
4957/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4958/// encoded as single characters, followed by an identifier. Property types
4959/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004960/// these attributes are defined by the following enumeration:
4961/// @code
4962/// enum PropertyAttributes {
4963/// kPropertyReadOnly = 'R', // property is read-only.
4964/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4965/// kPropertyByref = '&', // property is a reference to the value last assigned
4966/// kPropertyDynamic = 'D', // property is dynamic
4967/// kPropertyGetter = 'G', // followed by getter selector name
4968/// kPropertySetter = 'S', // followed by setter selector name
4969/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004970/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004971/// kPropertyWeak = 'W' // 'weak' property
4972/// kPropertyStrong = 'P' // property GC'able
4973/// kPropertyNonAtomic = 'N' // property non-atomic
4974/// };
4975/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004976void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004977 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004978 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004979 // Collect information from the property implementation decl(s).
4980 bool Dynamic = false;
4981 ObjCPropertyImplDecl *SynthesizePID = 0;
4982
Fariborz Jahaniandad96302014-01-22 19:02:20 +00004983 if (ObjCPropertyImplDecl *PropertyImpDecl =
4984 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
4985 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
4986 Dynamic = true;
4987 else
4988 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004989 }
4990
4991 // FIXME: This is not very efficient.
4992 S = "T";
4993
4994 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004995 // GCC has some special rules regarding encoding of properties which
4996 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004997 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004998 true /* outermost type */,
4999 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005000
5001 if (PD->isReadOnly()) {
5002 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005003 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5004 S += ",C";
5005 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5006 S += ",&";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005007 } else {
5008 switch (PD->getSetterKind()) {
5009 case ObjCPropertyDecl::Assign: break;
5010 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005011 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005012 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005013 }
5014 }
5015
5016 // It really isn't clear at all what this means, since properties
5017 // are "dynamic by default".
5018 if (Dynamic)
5019 S += ",D";
5020
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005021 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5022 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005023
Daniel Dunbar4932b362008-08-28 04:38:10 +00005024 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5025 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005026 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005027 }
5028
5029 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5030 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005031 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005032 }
5033
5034 if (SynthesizePID) {
5035 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5036 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005037 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005038 }
5039
5040 // FIXME: OBJCGC: weak & strong
5041}
5042
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005043/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005044/// Another legacy compatibility encoding: 32-bit longs are encoded as
5045/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005046/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5047///
5048void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005049 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005050 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005051 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005052 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005053 else
Jay Foad39c79802011-01-12 09:06:06 +00005054 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005055 PointeeTy = IntTy;
5056 }
5057 }
5058}
5059
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005060void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00005061 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005062 // We follow the behavior of gcc, expanding structures which are
5063 // directly pointed to, and expanding embedded structures. Note that
5064 // these rules are sufficient to prevent recursive encoding of the
5065 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005066 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00005067 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005068}
5069
John McCall393a78d2012-12-20 02:45:14 +00005070static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5071 BuiltinType::Kind kind) {
5072 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005073 case BuiltinType::Void: return 'v';
5074 case BuiltinType::Bool: return 'B';
5075 case BuiltinType::Char_U:
5076 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005077 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005078 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005079 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005080 case BuiltinType::UInt: return 'I';
5081 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005082 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005083 case BuiltinType::UInt128: return 'T';
5084 case BuiltinType::ULongLong: return 'Q';
5085 case BuiltinType::Char_S:
5086 case BuiltinType::SChar: return 'c';
5087 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005088 case BuiltinType::WChar_S:
5089 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005090 case BuiltinType::Int: return 'i';
5091 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005092 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005093 case BuiltinType::LongLong: return 'q';
5094 case BuiltinType::Int128: return 't';
5095 case BuiltinType::Float: return 'f';
5096 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005097 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005098 case BuiltinType::NullPtr: return '*'; // like char*
5099
5100 case BuiltinType::Half:
5101 // FIXME: potentially need @encodes for these!
5102 return ' ';
5103
5104 case BuiltinType::ObjCId:
5105 case BuiltinType::ObjCClass:
5106 case BuiltinType::ObjCSel:
5107 llvm_unreachable("@encoding ObjC primitive type");
5108
5109 // OpenCL and placeholder types don't need @encodings.
5110 case BuiltinType::OCLImage1d:
5111 case BuiltinType::OCLImage1dArray:
5112 case BuiltinType::OCLImage1dBuffer:
5113 case BuiltinType::OCLImage2d:
5114 case BuiltinType::OCLImage2dArray:
5115 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005116 case BuiltinType::OCLEvent:
Guy Benyei61054192013-02-07 10:55:47 +00005117 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005118 case BuiltinType::Dependent:
5119#define BUILTIN_TYPE(KIND, ID)
5120#define PLACEHOLDER_TYPE(KIND, ID) \
5121 case BuiltinType::KIND:
5122#include "clang/AST/BuiltinTypes.def"
5123 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005124 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005125 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005126}
5127
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005128static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5129 EnumDecl *Enum = ET->getDecl();
5130
5131 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5132 if (!Enum->isFixed())
5133 return 'i';
5134
5135 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005136 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5137 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005138}
5139
Jay Foad39c79802011-01-12 09:06:06 +00005140static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005141 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005142 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005143 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005144 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5145 // The GNU runtime requires more information; bitfields are encoded as b,
5146 // then the offset (in bits) of the first element, then the type of the
5147 // bitfield, then the size in bits. For example, in this structure:
5148 //
5149 // struct
5150 // {
5151 // int integer;
5152 // int flags:2;
5153 // };
5154 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5155 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5156 // information is not especially sensible, but we're stuck with it for
5157 // compatibility with GCC, although providing it breaks anything that
5158 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005159 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005160 const RecordDecl *RD = FD->getParent();
5161 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005162 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005163 if (const EnumType *ET = T->getAs<EnumType>())
5164 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005165 else {
5166 const BuiltinType *BT = T->castAs<BuiltinType>();
5167 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5168 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005169 }
Richard Smithcaf33902011-10-10 18:28:20 +00005170 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005171}
5172
Daniel Dunbar07d07852009-10-18 21:17:35 +00005173// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005174void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5175 bool ExpandPointedToStructures,
5176 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005177 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005178 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005179 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005180 bool StructField,
5181 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005182 bool EncodeClassNames,
5183 bool EncodePointerToObjCTypedef) const {
John McCall393a78d2012-12-20 02:45:14 +00005184 CanQualType CT = getCanonicalType(T);
5185 switch (CT->getTypeClass()) {
5186 case Type::Builtin:
5187 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005188 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005189 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005190 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5191 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5192 else
5193 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005194 return;
Mike Stump11289f42009-09-09 15:08:12 +00005195
John McCall393a78d2012-12-20 02:45:14 +00005196 case Type::Complex: {
5197 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005198 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00005199 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00005200 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005201 return;
5202 }
John McCall393a78d2012-12-20 02:45:14 +00005203
5204 case Type::Atomic: {
5205 const AtomicType *AT = T->castAs<AtomicType>();
5206 S += 'A';
5207 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5208 false, false);
5209 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005210 }
John McCall393a78d2012-12-20 02:45:14 +00005211
5212 // encoding for pointer or reference types.
5213 case Type::Pointer:
5214 case Type::LValueReference:
5215 case Type::RValueReference: {
5216 QualType PointeeTy;
5217 if (isa<PointerType>(CT)) {
5218 const PointerType *PT = T->castAs<PointerType>();
5219 if (PT->isObjCSelType()) {
5220 S += ':';
5221 return;
5222 }
5223 PointeeTy = PT->getPointeeType();
5224 } else {
5225 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5226 }
5227
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005228 bool isReadOnly = false;
5229 // For historical/compatibility reasons, the read-only qualifier of the
5230 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5231 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005232 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005233 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005234 if (OutermostType && T.isConstQualified()) {
5235 isReadOnly = true;
5236 S += 'r';
5237 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005238 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005239 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005240 while (P->getAs<PointerType>())
5241 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005242 if (P.isConstQualified()) {
5243 isReadOnly = true;
5244 S += 'r';
5245 }
5246 }
5247 if (isReadOnly) {
5248 // Another legacy compatibility encoding. Some ObjC qualifier and type
5249 // combinations need to be rearranged.
5250 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005251 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005252 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005253 }
Mike Stump11289f42009-09-09 15:08:12 +00005254
Anders Carlssond8499822007-10-29 05:01:08 +00005255 if (PointeeTy->isCharType()) {
5256 // char pointer types should be encoded as '*' unless it is a
5257 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005258 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005259 S += '*';
5260 return;
5261 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005262 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005263 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5264 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5265 S += '#';
5266 return;
5267 }
5268 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5269 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5270 S += '@';
5271 return;
5272 }
5273 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005274 }
Anders Carlssond8499822007-10-29 05:01:08 +00005275 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005276 getLegacyIntegralTypeEncoding(PointeeTy);
5277
Mike Stump11289f42009-09-09 15:08:12 +00005278 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005279 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005280 return;
5281 }
John McCall393a78d2012-12-20 02:45:14 +00005282
5283 case Type::ConstantArray:
5284 case Type::IncompleteArray:
5285 case Type::VariableArray: {
5286 const ArrayType *AT = cast<ArrayType>(CT);
5287
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005288 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005289 // Incomplete arrays are encoded as a pointer to the array element.
5290 S += '^';
5291
Mike Stump11289f42009-09-09 15:08:12 +00005292 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005293 false, ExpandStructures, FD);
5294 } else {
5295 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005296
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005297 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5298 S += llvm::utostr(CAT->getSize().getZExtValue());
5299 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005300 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005301 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5302 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005303 S += '0';
5304 }
Mike Stump11289f42009-09-09 15:08:12 +00005305
5306 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005307 false, ExpandStructures, FD);
5308 S += ']';
5309 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005310 return;
5311 }
Mike Stump11289f42009-09-09 15:08:12 +00005312
John McCall393a78d2012-12-20 02:45:14 +00005313 case Type::FunctionNoProto:
5314 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005315 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005316 return;
Mike Stump11289f42009-09-09 15:08:12 +00005317
John McCall393a78d2012-12-20 02:45:14 +00005318 case Type::Record: {
5319 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005320 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005321 // Anonymous structures print as '?'
5322 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5323 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005324 if (ClassTemplateSpecializationDecl *Spec
5325 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5326 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005327 llvm::raw_string_ostream OS(S);
5328 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005329 TemplateArgs.data(),
5330 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005331 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005332 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005333 } else {
5334 S += '?';
5335 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005336 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005337 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005338 if (!RDecl->isUnion()) {
5339 getObjCEncodingForStructureImpl(RDecl, S, FD);
5340 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005341 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005342 if (FD) {
5343 S += '"';
5344 S += Field->getNameAsString();
5345 S += '"';
5346 }
Mike Stump11289f42009-09-09 15:08:12 +00005347
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005348 // Special case bit-fields.
5349 if (Field->isBitField()) {
5350 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005351 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005352 } else {
5353 QualType qt = Field->getType();
5354 getLegacyIntegralTypeEncoding(qt);
5355 getObjCEncodingForTypeImpl(qt, S, false, true,
5356 FD, /*OutermostType*/false,
5357 /*EncodingProperty*/false,
5358 /*StructField*/true);
5359 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005360 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005361 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005362 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005363 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005364 return;
5365 }
Mike Stump11289f42009-09-09 15:08:12 +00005366
John McCall393a78d2012-12-20 02:45:14 +00005367 case Type::BlockPointer: {
5368 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005369 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005370 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005371 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005372
5373 S += '<';
5374 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005375 getObjCEncodingForTypeImpl(
5376 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5377 FD, false /* OutermostType */, EncodingProperty,
5378 false /* StructField */, EncodeBlockParameters, EncodeClassNames);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005379 // Block self
5380 S += "@?";
5381 // Block parameters
5382 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005383 for (const auto &I : FPT->param_types())
5384 getObjCEncodingForTypeImpl(
5385 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5386 false /* OutermostType */, EncodingProperty,
5387 false /* StructField */, EncodeBlockParameters, EncodeClassNames);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005388 }
5389 S += '>';
5390 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005391 return;
5392 }
Mike Stump11289f42009-09-09 15:08:12 +00005393
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005394 case Type::ObjCObject: {
5395 // hack to match legacy encoding of *id and *Class
5396 QualType Ty = getObjCObjectPointerType(CT);
5397 if (Ty->isObjCIdType()) {
5398 S += "{objc_object=}";
5399 return;
5400 }
5401 else if (Ty->isObjCClassType()) {
5402 S += "{objc_class=}";
5403 return;
5404 }
5405 }
5406
John McCall393a78d2012-12-20 02:45:14 +00005407 case Type::ObjCInterface: {
5408 // Ignore protocol qualifiers when mangling at this level.
5409 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005410
John McCall393a78d2012-12-20 02:45:14 +00005411 // The assumption seems to be that this assert will succeed
5412 // because nested levels will have filtered out 'id' and 'Class'.
5413 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005414 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005415 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005416 S += '{';
5417 const IdentifierInfo *II = OI->getIdentifier();
5418 S += II->getName();
5419 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005420 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005421 DeepCollectObjCIvars(OI, true, Ivars);
5422 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005423 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005424 if (Field->isBitField())
5425 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005426 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005427 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5428 false, false, false, false, false,
5429 EncodePointerToObjCTypedef);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005430 }
5431 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005432 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005433 }
Mike Stump11289f42009-09-09 15:08:12 +00005434
John McCall393a78d2012-12-20 02:45:14 +00005435 case Type::ObjCObjectPointer: {
5436 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005437 if (OPT->isObjCIdType()) {
5438 S += '@';
5439 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005440 }
Mike Stump11289f42009-09-09 15:08:12 +00005441
Steve Narofff0c86112009-10-28 22:03:49 +00005442 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5443 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5444 // Since this is a binary compatibility issue, need to consult with runtime
5445 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005446 S += '#';
5447 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005448 }
Mike Stump11289f42009-09-09 15:08:12 +00005449
Chris Lattnere7cabb92009-07-13 00:10:46 +00005450 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005451 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005452 ExpandPointedToStructures,
5453 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005454 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005455 // Note that we do extended encoding of protocol qualifer list
5456 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005457 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00005458 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5459 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005460 S += '<';
5461 S += (*I)->getNameAsString();
5462 S += '>';
5463 }
5464 S += '"';
5465 }
5466 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005467 }
Mike Stump11289f42009-09-09 15:08:12 +00005468
Chris Lattnere7cabb92009-07-13 00:10:46 +00005469 QualType PointeeTy = OPT->getPointeeType();
5470 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005471 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5472 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005473 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005474 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005475 // {...};
5476 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005477 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005478 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005479 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5480 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5481 DeepCollectObjCIvars(OI, true, Ivars);
5482 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5483 if (cast<FieldDecl>(Ivars[i]) == FD) {
5484 S += '{';
5485 S += OI->getIdentifier()->getName();
5486 S += '}';
5487 return;
5488 }
5489 }
5490 }
Mike Stump11289f42009-09-09 15:08:12 +00005491 getObjCEncodingForTypeImpl(PointeeTy, S,
5492 false, ExpandPointedToStructures,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005493 NULL,
5494 false, false, false, false, false,
5495 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005496 return;
5497 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005498
5499 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005500 if (OPT->getInterfaceDecl() &&
5501 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005502 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005503 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00005504 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5505 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005506 S += '<';
5507 S += (*I)->getNameAsString();
5508 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005509 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005510 S += '"';
5511 }
5512 return;
5513 }
Mike Stump11289f42009-09-09 15:08:12 +00005514
John McCalla9e6e8d2010-05-17 23:56:34 +00005515 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005516 // FIXME: we shoul do better than that. 'M' is available.
5517 case Type::MemberPointer:
John McCalla9e6e8d2010-05-17 23:56:34 +00005518 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005519
John McCall393a78d2012-12-20 02:45:14 +00005520 case Type::Vector:
5521 case Type::ExtVector:
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005522 // This matches gcc's encoding, even though technically it is
5523 // insufficient.
5524 // FIXME. We should do a better job than gcc.
5525 return;
John McCall393a78d2012-12-20 02:45:14 +00005526
Richard Smith27d807c2013-04-30 13:56:41 +00005527 case Type::Auto:
5528 // We could see an undeduced auto type here during error recovery.
5529 // Just ignore it.
5530 return;
5531
John McCall393a78d2012-12-20 02:45:14 +00005532#define ABSTRACT_TYPE(KIND, BASE)
5533#define TYPE(KIND, BASE)
5534#define DEPENDENT_TYPE(KIND, BASE) \
5535 case Type::KIND:
5536#define NON_CANONICAL_TYPE(KIND, BASE) \
5537 case Type::KIND:
5538#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5539 case Type::KIND:
5540#include "clang/AST/TypeNodes.def"
5541 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005542 }
John McCall393a78d2012-12-20 02:45:14 +00005543 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005544}
5545
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005546void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5547 std::string &S,
5548 const FieldDecl *FD,
5549 bool includeVBases) const {
5550 assert(RDecl && "Expected non-null RecordDecl");
5551 assert(!RDecl->isUnion() && "Should not be called for unions");
5552 if (!RDecl->getDefinition())
5553 return;
5554
5555 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5556 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5557 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5558
5559 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00005560 for (const auto &BI : CXXRec->bases()) {
5561 if (!BI.isVirtual()) {
5562 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005563 if (base->isEmpty())
5564 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005565 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005566 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5567 std::make_pair(offs, base));
5568 }
5569 }
5570 }
5571
5572 unsigned i = 0;
5573 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5574 FieldEnd = RDecl->field_end();
5575 Field != FieldEnd; ++Field, ++i) {
5576 uint64_t offs = layout.getFieldOffset(i);
5577 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005578 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005579 }
5580
5581 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005582 for (const auto &BI : CXXRec->vbases()) {
5583 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005584 if (base->isEmpty())
5585 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005586 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005587 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5588 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005589 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5590 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005591 }
5592 }
5593
5594 CharUnits size;
5595 if (CXXRec) {
5596 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5597 } else {
5598 size = layout.getSize();
5599 }
5600
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005601#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005602 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005603#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005604 std::multimap<uint64_t, NamedDecl *>::iterator
5605 CurLayObj = FieldOrBaseOffsets.begin();
5606
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005607 if (CXXRec && CXXRec->isDynamicClass() &&
5608 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005609 if (FD) {
5610 S += "\"_vptr$";
5611 std::string recname = CXXRec->getNameAsString();
5612 if (recname.empty()) recname = "?";
5613 S += recname;
5614 S += '"';
5615 }
5616 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005617#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005618 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005619#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005620 }
5621
5622 if (!RDecl->hasFlexibleArrayMember()) {
5623 // Mark the end of the structure.
5624 uint64_t offs = toBits(size);
5625 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5626 std::make_pair(offs, (NamedDecl*)0));
5627 }
5628
5629 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005630#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005631 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005632 if (CurOffs < CurLayObj->first) {
5633 uint64_t padding = CurLayObj->first - CurOffs;
5634 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5635 // packing/alignment of members is different that normal, in which case
5636 // the encoding will be out-of-sync with the real layout.
5637 // If the runtime switches to just consider the size of types without
5638 // taking into account alignment, we could make padding explicit in the
5639 // encoding (e.g. using arrays of chars). The encoding strings would be
5640 // longer then though.
5641 CurOffs += padding;
5642 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005643#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005644
5645 NamedDecl *dcl = CurLayObj->second;
5646 if (dcl == 0)
5647 break; // reached end of structure.
5648
5649 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5650 // We expand the bases without their virtual bases since those are going
5651 // in the initial structure. Note that this differs from gcc which
5652 // expands virtual bases each time one is encountered in the hierarchy,
5653 // making the encoding type bigger than it really is.
5654 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005655 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005656#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005657 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005658#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005659 } else {
5660 FieldDecl *field = cast<FieldDecl>(dcl);
5661 if (FD) {
5662 S += '"';
5663 S += field->getNameAsString();
5664 S += '"';
5665 }
5666
5667 if (field->isBitField()) {
5668 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005669#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00005670 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005671#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005672 } else {
5673 QualType qt = field->getType();
5674 getLegacyIntegralTypeEncoding(qt);
5675 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5676 /*OutermostType*/false,
5677 /*EncodingProperty*/false,
5678 /*StructField*/true);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005679#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005680 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005681#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005682 }
5683 }
5684 }
5685}
5686
Mike Stump11289f42009-09-09 15:08:12 +00005687void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005688 std::string& S) const {
5689 if (QT & Decl::OBJC_TQ_In)
5690 S += 'n';
5691 if (QT & Decl::OBJC_TQ_Inout)
5692 S += 'N';
5693 if (QT & Decl::OBJC_TQ_Out)
5694 S += 'o';
5695 if (QT & Decl::OBJC_TQ_Bycopy)
5696 S += 'O';
5697 if (QT & Decl::OBJC_TQ_Byref)
5698 S += 'R';
5699 if (QT & Decl::OBJC_TQ_Oneway)
5700 S += 'V';
5701}
5702
Douglas Gregor3ea72692011-08-12 05:46:01 +00005703TypedefDecl *ASTContext::getObjCIdDecl() const {
5704 if (!ObjCIdDecl) {
5705 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5706 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005707 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00005708 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00005709 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005710}
5711
Douglas Gregor52e02802011-08-12 06:17:30 +00005712TypedefDecl *ASTContext::getObjCSelDecl() const {
5713 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005714 QualType T = getPointerType(ObjCBuiltinSelTy);
5715 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00005716 }
5717 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005718}
5719
Douglas Gregor0a586182011-08-12 05:59:41 +00005720TypedefDecl *ASTContext::getObjCClassDecl() const {
5721 if (!ObjCClassDecl) {
5722 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5723 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005724 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00005725 }
Douglas Gregor0a586182011-08-12 05:59:41 +00005726 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005727}
5728
Douglas Gregord53ae832012-01-17 18:09:05 +00005729ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5730 if (!ObjCProtocolClassDecl) {
5731 ObjCProtocolClassDecl
5732 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5733 SourceLocation(),
5734 &Idents.get("Protocol"),
5735 /*PrevDecl=*/0,
5736 SourceLocation(), true);
5737 }
5738
5739 return ObjCProtocolClassDecl;
5740}
5741
Meador Inge5d3fb222012-06-16 03:34:49 +00005742//===----------------------------------------------------------------------===//
5743// __builtin_va_list Construction Functions
5744//===----------------------------------------------------------------------===//
5745
5746static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5747 // typedef char* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005748 QualType T = Context->getPointerType(Context->CharTy);
5749 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005750}
5751
5752static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5753 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005754 QualType T = Context->getPointerType(Context->VoidTy);
5755 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005756}
5757
Tim Northover9bb857a2013-01-31 12:13:10 +00005758static TypedefDecl *
5759CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005760 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00005761 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005762 if (Context->getLangOpts().CPlusPlus) {
5763 // namespace std { struct __va_list {
5764 NamespaceDecl *NS;
5765 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5766 Context->getTranslationUnitDecl(),
5767 /*Inline*/false, SourceLocation(),
5768 SourceLocation(), &Context->Idents.get("std"),
5769 /*PrevDecl*/0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005770 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00005771 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00005772 }
5773
5774 VaListTagDecl->startDefinition();
5775
5776 const size_t NumFields = 5;
5777 QualType FieldTypes[NumFields];
5778 const char *FieldNames[NumFields];
5779
5780 // void *__stack;
5781 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5782 FieldNames[0] = "__stack";
5783
5784 // void *__gr_top;
5785 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5786 FieldNames[1] = "__gr_top";
5787
5788 // void *__vr_top;
5789 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5790 FieldNames[2] = "__vr_top";
5791
5792 // int __gr_offs;
5793 FieldTypes[3] = Context->IntTy;
5794 FieldNames[3] = "__gr_offs";
5795
5796 // int __vr_offs;
5797 FieldTypes[4] = Context->IntTy;
5798 FieldNames[4] = "__vr_offs";
5799
5800 // Create fields
5801 for (unsigned i = 0; i < NumFields; ++i) {
5802 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5803 VaListTagDecl,
5804 SourceLocation(),
5805 SourceLocation(),
5806 &Context->Idents.get(FieldNames[i]),
5807 FieldTypes[i], /*TInfo=*/0,
5808 /*BitWidth=*/0,
5809 /*Mutable=*/false,
5810 ICIS_NoInit);
5811 Field->setAccess(AS_public);
5812 VaListTagDecl->addDecl(Field);
5813 }
5814 VaListTagDecl->completeDefinition();
5815 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5816 Context->VaListTagTy = VaListTagType;
5817
5818 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005819 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005820}
5821
Meador Inge5d3fb222012-06-16 03:34:49 +00005822static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5823 // typedef struct __va_list_tag {
5824 RecordDecl *VaListTagDecl;
5825
Alp Toker2dea15b2013-12-17 01:22:38 +00005826 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005827 VaListTagDecl->startDefinition();
5828
5829 const size_t NumFields = 5;
5830 QualType FieldTypes[NumFields];
5831 const char *FieldNames[NumFields];
5832
5833 // unsigned char gpr;
5834 FieldTypes[0] = Context->UnsignedCharTy;
5835 FieldNames[0] = "gpr";
5836
5837 // unsigned char fpr;
5838 FieldTypes[1] = Context->UnsignedCharTy;
5839 FieldNames[1] = "fpr";
5840
5841 // unsigned short reserved;
5842 FieldTypes[2] = Context->UnsignedShortTy;
5843 FieldNames[2] = "reserved";
5844
5845 // void* overflow_arg_area;
5846 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5847 FieldNames[3] = "overflow_arg_area";
5848
5849 // void* reg_save_area;
5850 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5851 FieldNames[4] = "reg_save_area";
5852
5853 // Create fields
5854 for (unsigned i = 0; i < NumFields; ++i) {
5855 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5856 SourceLocation(),
5857 SourceLocation(),
5858 &Context->Idents.get(FieldNames[i]),
5859 FieldTypes[i], /*TInfo=*/0,
5860 /*BitWidth=*/0,
5861 /*Mutable=*/false,
5862 ICIS_NoInit);
5863 Field->setAccess(AS_public);
5864 VaListTagDecl->addDecl(Field);
5865 }
5866 VaListTagDecl->completeDefinition();
5867 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005868 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005869
5870 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00005871 TypedefDecl *VaListTagTypedefDecl =
5872 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
5873
Meador Inge5d3fb222012-06-16 03:34:49 +00005874 QualType VaListTagTypedefType =
5875 Context->getTypedefType(VaListTagTypedefDecl);
5876
5877 // typedef __va_list_tag __builtin_va_list[1];
5878 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5879 QualType VaListTagArrayType
5880 = Context->getConstantArrayType(VaListTagTypedefType,
5881 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005882 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005883}
5884
5885static TypedefDecl *
5886CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5887 // typedef struct __va_list_tag {
5888 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00005889 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005890 VaListTagDecl->startDefinition();
5891
5892 const size_t NumFields = 4;
5893 QualType FieldTypes[NumFields];
5894 const char *FieldNames[NumFields];
5895
5896 // unsigned gp_offset;
5897 FieldTypes[0] = Context->UnsignedIntTy;
5898 FieldNames[0] = "gp_offset";
5899
5900 // unsigned fp_offset;
5901 FieldTypes[1] = Context->UnsignedIntTy;
5902 FieldNames[1] = "fp_offset";
5903
5904 // void* overflow_arg_area;
5905 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5906 FieldNames[2] = "overflow_arg_area";
5907
5908 // void* reg_save_area;
5909 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5910 FieldNames[3] = "reg_save_area";
5911
5912 // Create fields
5913 for (unsigned i = 0; i < NumFields; ++i) {
5914 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5915 VaListTagDecl,
5916 SourceLocation(),
5917 SourceLocation(),
5918 &Context->Idents.get(FieldNames[i]),
5919 FieldTypes[i], /*TInfo=*/0,
5920 /*BitWidth=*/0,
5921 /*Mutable=*/false,
5922 ICIS_NoInit);
5923 Field->setAccess(AS_public);
5924 VaListTagDecl->addDecl(Field);
5925 }
5926 VaListTagDecl->completeDefinition();
5927 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005928 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005929
5930 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00005931 TypedefDecl *VaListTagTypedefDecl =
5932 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
5933
Meador Inge5d3fb222012-06-16 03:34:49 +00005934 QualType VaListTagTypedefType =
5935 Context->getTypedefType(VaListTagTypedefDecl);
5936
5937 // typedef __va_list_tag __builtin_va_list[1];
5938 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5939 QualType VaListTagArrayType
5940 = Context->getConstantArrayType(VaListTagTypedefType,
5941 Size, ArrayType::Normal,0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005942 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005943}
5944
5945static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5946 // typedef int __builtin_va_list[4];
5947 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5948 QualType IntArrayType
5949 = Context->getConstantArrayType(Context->IntTy,
5950 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005951 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005952}
5953
Logan Chien57086ce2012-10-10 06:56:20 +00005954static TypedefDecl *
5955CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005956 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00005957 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00005958 if (Context->getLangOpts().CPlusPlus) {
5959 // namespace std { struct __va_list {
5960 NamespaceDecl *NS;
5961 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5962 Context->getTranslationUnitDecl(),
5963 /*Inline*/false, SourceLocation(),
5964 SourceLocation(), &Context->Idents.get("std"),
5965 /*PrevDecl*/0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005966 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00005967 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00005968 }
5969
5970 VaListDecl->startDefinition();
5971
5972 // void * __ap;
5973 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5974 VaListDecl,
5975 SourceLocation(),
5976 SourceLocation(),
5977 &Context->Idents.get("__ap"),
5978 Context->getPointerType(Context->VoidTy),
5979 /*TInfo=*/0,
5980 /*BitWidth=*/0,
5981 /*Mutable=*/false,
5982 ICIS_NoInit);
5983 Field->setAccess(AS_public);
5984 VaListDecl->addDecl(Field);
5985
5986 // };
5987 VaListDecl->completeDefinition();
5988
5989 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005990 QualType T = Context->getRecordType(VaListDecl);
5991 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00005992}
5993
Ulrich Weigand47445072013-05-06 16:26:41 +00005994static TypedefDecl *
5995CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
5996 // typedef struct __va_list_tag {
5997 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00005998 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00005999 VaListTagDecl->startDefinition();
6000
6001 const size_t NumFields = 4;
6002 QualType FieldTypes[NumFields];
6003 const char *FieldNames[NumFields];
6004
6005 // long __gpr;
6006 FieldTypes[0] = Context->LongTy;
6007 FieldNames[0] = "__gpr";
6008
6009 // long __fpr;
6010 FieldTypes[1] = Context->LongTy;
6011 FieldNames[1] = "__fpr";
6012
6013 // void *__overflow_arg_area;
6014 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6015 FieldNames[2] = "__overflow_arg_area";
6016
6017 // void *__reg_save_area;
6018 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6019 FieldNames[3] = "__reg_save_area";
6020
6021 // Create fields
6022 for (unsigned i = 0; i < NumFields; ++i) {
6023 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6024 VaListTagDecl,
6025 SourceLocation(),
6026 SourceLocation(),
6027 &Context->Idents.get(FieldNames[i]),
6028 FieldTypes[i], /*TInfo=*/0,
6029 /*BitWidth=*/0,
6030 /*Mutable=*/false,
6031 ICIS_NoInit);
6032 Field->setAccess(AS_public);
6033 VaListTagDecl->addDecl(Field);
6034 }
6035 VaListTagDecl->completeDefinition();
6036 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6037 Context->VaListTagTy = VaListTagType;
6038
6039 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006040 TypedefDecl *VaListTagTypedefDecl =
6041 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006042 QualType VaListTagTypedefType =
6043 Context->getTypedefType(VaListTagTypedefDecl);
6044
6045 // typedef __va_list_tag __builtin_va_list[1];
6046 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6047 QualType VaListTagArrayType
6048 = Context->getConstantArrayType(VaListTagTypedefType,
6049 Size, ArrayType::Normal,0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006050
Alp Toker56b5cc92013-12-15 10:36:26 +00006051 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006052}
6053
Meador Inge5d3fb222012-06-16 03:34:49 +00006054static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6055 TargetInfo::BuiltinVaListKind Kind) {
6056 switch (Kind) {
6057 case TargetInfo::CharPtrBuiltinVaList:
6058 return CreateCharPtrBuiltinVaListDecl(Context);
6059 case TargetInfo::VoidPtrBuiltinVaList:
6060 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006061 case TargetInfo::AArch64ABIBuiltinVaList:
6062 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006063 case TargetInfo::PowerABIBuiltinVaList:
6064 return CreatePowerABIBuiltinVaListDecl(Context);
6065 case TargetInfo::X86_64ABIBuiltinVaList:
6066 return CreateX86_64ABIBuiltinVaListDecl(Context);
6067 case TargetInfo::PNaClABIBuiltinVaList:
6068 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006069 case TargetInfo::AAPCSABIBuiltinVaList:
6070 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006071 case TargetInfo::SystemZBuiltinVaList:
6072 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006073 }
6074
6075 llvm_unreachable("Unhandled __builtin_va_list type kind");
6076}
6077
6078TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006079 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006080 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006081 assert(BuiltinVaListDecl->isImplicit());
6082 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006083
6084 return BuiltinVaListDecl;
6085}
6086
Meador Ingecfb60902012-07-01 15:57:25 +00006087QualType ASTContext::getVaListTagType() const {
6088 // Force the creation of VaListTagTy by building the __builtin_va_list
6089 // declaration.
6090 if (VaListTagTy.isNull())
6091 (void) getBuiltinVaListDecl();
6092
6093 return VaListTagTy;
6094}
6095
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006096void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006097 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006098 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006099
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006100 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006101}
6102
John McCalld28ae272009-12-02 08:04:21 +00006103/// \brief Retrieve the template name that corresponds to a non-empty
6104/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006105TemplateName
6106ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6107 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006108 unsigned size = End - Begin;
6109 assert(size > 1 && "set is not overloaded!");
6110
6111 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6112 size * sizeof(FunctionTemplateDecl*));
6113 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6114
6115 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006116 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006117 NamedDecl *D = *I;
6118 assert(isa<FunctionTemplateDecl>(D) ||
6119 (isa<UsingShadowDecl>(D) &&
6120 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6121 *Storage++ = D;
6122 }
6123
6124 return TemplateName(OT);
6125}
6126
Douglas Gregordc572a32009-03-30 22:58:21 +00006127/// \brief Retrieve the template name that represents a qualified
6128/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006129TemplateName
6130ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6131 bool TemplateKeyword,
6132 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006133 assert(NNS && "Missing nested-name-specifier in qualified template name");
6134
Douglas Gregorc42075a2010-02-04 18:10:26 +00006135 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006136 llvm::FoldingSetNodeID ID;
6137 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6138
6139 void *InsertPos = 0;
6140 QualifiedTemplateName *QTN =
6141 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6142 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006143 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6144 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006145 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6146 }
6147
6148 return TemplateName(QTN);
6149}
6150
6151/// \brief Retrieve the template name that represents a dependent
6152/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006153TemplateName
6154ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6155 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006156 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006157 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006158
6159 llvm::FoldingSetNodeID ID;
6160 DependentTemplateName::Profile(ID, NNS, Name);
6161
6162 void *InsertPos = 0;
6163 DependentTemplateName *QTN =
6164 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6165
6166 if (QTN)
6167 return TemplateName(QTN);
6168
6169 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6170 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006171 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6172 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006173 } else {
6174 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006175 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6176 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006177 DependentTemplateName *CheckQTN =
6178 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6179 assert(!CheckQTN && "Dependent type name canonicalization broken");
6180 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006181 }
6182
6183 DependentTemplateNames.InsertNode(QTN, InsertPos);
6184 return TemplateName(QTN);
6185}
6186
Douglas Gregor71395fa2009-11-04 00:56:37 +00006187/// \brief Retrieve the template name that represents a dependent
6188/// template name such as \c MetaFun::template operator+.
6189TemplateName
6190ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006191 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006192 assert((!NNS || NNS->isDependent()) &&
6193 "Nested name specifier must be dependent");
6194
6195 llvm::FoldingSetNodeID ID;
6196 DependentTemplateName::Profile(ID, NNS, Operator);
6197
6198 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006199 DependentTemplateName *QTN
6200 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006201
6202 if (QTN)
6203 return TemplateName(QTN);
6204
6205 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6206 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006207 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6208 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006209 } else {
6210 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006211 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6212 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006213
6214 DependentTemplateName *CheckQTN
6215 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6216 assert(!CheckQTN && "Dependent template name canonicalization broken");
6217 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006218 }
6219
6220 DependentTemplateNames.InsertNode(QTN, InsertPos);
6221 return TemplateName(QTN);
6222}
6223
Douglas Gregor5590be02011-01-15 06:45:20 +00006224TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006225ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6226 TemplateName replacement) const {
6227 llvm::FoldingSetNodeID ID;
6228 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6229
6230 void *insertPos = 0;
6231 SubstTemplateTemplateParmStorage *subst
6232 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6233
6234 if (!subst) {
6235 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6236 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6237 }
6238
6239 return TemplateName(subst);
6240}
6241
6242TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006243ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6244 const TemplateArgument &ArgPack) const {
6245 ASTContext &Self = const_cast<ASTContext &>(*this);
6246 llvm::FoldingSetNodeID ID;
6247 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6248
6249 void *InsertPos = 0;
6250 SubstTemplateTemplateParmPackStorage *Subst
6251 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6252
6253 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006254 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006255 ArgPack.pack_size(),
6256 ArgPack.pack_begin());
6257 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6258 }
6259
6260 return TemplateName(Subst);
6261}
6262
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006263/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006264/// TargetInfo, produce the corresponding type. The unsigned @p Type
6265/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006266CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006267 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006268 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006269 case TargetInfo::SignedChar: return SignedCharTy;
6270 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006271 case TargetInfo::SignedShort: return ShortTy;
6272 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6273 case TargetInfo::SignedInt: return IntTy;
6274 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6275 case TargetInfo::SignedLong: return LongTy;
6276 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6277 case TargetInfo::SignedLongLong: return LongLongTy;
6278 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6279 }
6280
David Blaikie83d382b2011-09-23 05:06:16 +00006281 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006282}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006283
6284//===----------------------------------------------------------------------===//
6285// Type Predicates.
6286//===----------------------------------------------------------------------===//
6287
Fariborz Jahanian96207692009-02-18 21:49:28 +00006288/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6289/// garbage collection attribute.
6290///
John McCall553d45a2011-01-12 00:34:59 +00006291Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006292 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006293 return Qualifiers::GCNone;
6294
David Blaikiebbafb8a2012-03-11 07:00:24 +00006295 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006296 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6297
6298 // Default behaviour under objective-C's gc is for ObjC pointers
6299 // (or pointers to them) be treated as though they were declared
6300 // as __strong.
6301 if (GCAttrs == Qualifiers::GCNone) {
6302 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6303 return Qualifiers::Strong;
6304 else if (Ty->isPointerType())
6305 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6306 } else {
6307 // It's not valid to set GC attributes on anything that isn't a
6308 // pointer.
6309#ifndef NDEBUG
6310 QualType CT = Ty->getCanonicalTypeInternal();
6311 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6312 CT = AT->getElementType();
6313 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6314#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006315 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006316 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006317}
6318
Chris Lattner49af6a42008-04-07 06:51:04 +00006319//===----------------------------------------------------------------------===//
6320// Type Compatibility Testing
6321//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006322
Mike Stump11289f42009-09-09 15:08:12 +00006323/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006324/// compatible.
6325static bool areCompatVectorTypes(const VectorType *LHS,
6326 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006327 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006328 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006329 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006330}
6331
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006332bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6333 QualType SecondVec) {
6334 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6335 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6336
6337 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6338 return true;
6339
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006340 // Treat Neon vector types and most AltiVec vector types as if they are the
6341 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006342 const VectorType *First = FirstVec->getAs<VectorType>();
6343 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006344 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006345 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006346 First->getVectorKind() != VectorType::AltiVecPixel &&
6347 First->getVectorKind() != VectorType::AltiVecBool &&
6348 Second->getVectorKind() != VectorType::AltiVecPixel &&
6349 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006350 return true;
6351
6352 return false;
6353}
6354
Steve Naroff8e6aee52009-07-23 01:01:38 +00006355//===----------------------------------------------------------------------===//
6356// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6357//===----------------------------------------------------------------------===//
6358
6359/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6360/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006361bool
6362ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6363 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006364 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006365 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006366 for (auto *PI : rProto->protocols())
6367 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006368 return true;
6369 return false;
6370}
6371
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006372/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6373/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006374bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6375 QualType rhs) {
6376 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6377 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6378 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6379
6380 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6381 E = lhsQID->qual_end(); I != E; ++I) {
6382 bool match = false;
6383 ObjCProtocolDecl *lhsProto = *I;
6384 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6385 E = rhsOPT->qual_end(); J != E; ++J) {
6386 ObjCProtocolDecl *rhsProto = *J;
6387 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6388 match = true;
6389 break;
6390 }
6391 }
6392 if (!match)
6393 return false;
6394 }
6395 return true;
6396}
6397
Steve Naroff8e6aee52009-07-23 01:01:38 +00006398/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6399/// ObjCQualifiedIDType.
6400bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6401 bool compare) {
6402 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006403 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006404 lhs->isObjCIdType() || lhs->isObjCClassType())
6405 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006406 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006407 rhs->isObjCIdType() || rhs->isObjCClassType())
6408 return true;
6409
6410 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006411 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006412
Steve Naroff8e6aee52009-07-23 01:01:38 +00006413 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006414
Steve Naroff8e6aee52009-07-23 01:01:38 +00006415 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006416 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006417 // make sure we check the class hierarchy.
6418 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6419 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6420 E = lhsQID->qual_end(); I != E; ++I) {
6421 // when comparing an id<P> on lhs with a static type on rhs,
6422 // see if static class implements all of id's protocols, directly or
6423 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006424 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006425 return false;
6426 }
6427 }
6428 // If there are no qualifiers and no interface, we have an 'id'.
6429 return true;
6430 }
Mike Stump11289f42009-09-09 15:08:12 +00006431 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006432 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6433 E = lhsQID->qual_end(); I != E; ++I) {
6434 ObjCProtocolDecl *lhsProto = *I;
6435 bool match = false;
6436
6437 // when comparing an id<P> on lhs with a static type on rhs,
6438 // see if static class implements all of id's protocols, directly or
6439 // through its super class and categories.
6440 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6441 E = rhsOPT->qual_end(); J != E; ++J) {
6442 ObjCProtocolDecl *rhsProto = *J;
6443 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6444 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6445 match = true;
6446 break;
6447 }
6448 }
Mike Stump11289f42009-09-09 15:08:12 +00006449 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006450 // make sure we check the class hierarchy.
6451 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6452 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6453 E = lhsQID->qual_end(); I != E; ++I) {
6454 // when comparing an id<P> on lhs with a static type on rhs,
6455 // see if static class implements all of id's protocols, directly or
6456 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006457 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006458 match = true;
6459 break;
6460 }
6461 }
6462 }
6463 if (!match)
6464 return false;
6465 }
Mike Stump11289f42009-09-09 15:08:12 +00006466
Steve Naroff8e6aee52009-07-23 01:01:38 +00006467 return true;
6468 }
Mike Stump11289f42009-09-09 15:08:12 +00006469
Steve Naroff8e6aee52009-07-23 01:01:38 +00006470 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6471 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6472
Mike Stump11289f42009-09-09 15:08:12 +00006473 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006474 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006475 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006476 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6477 E = lhsOPT->qual_end(); I != E; ++I) {
6478 ObjCProtocolDecl *lhsProto = *I;
6479 bool match = false;
6480
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006481 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006482 // see if static class implements all of id's protocols, directly or
6483 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006484 // First, lhs protocols in the qualifier list must be found, direct
6485 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006486 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6487 E = rhsQID->qual_end(); J != E; ++J) {
6488 ObjCProtocolDecl *rhsProto = *J;
6489 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6490 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6491 match = true;
6492 break;
6493 }
6494 }
6495 if (!match)
6496 return false;
6497 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006498
6499 // Static class's protocols, or its super class or category protocols
6500 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6501 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6502 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6503 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6504 // This is rather dubious but matches gcc's behavior. If lhs has
6505 // no type qualifier and its class has no static protocol(s)
6506 // assume that it is mismatch.
6507 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6508 return false;
6509 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6510 LHSInheritedProtocols.begin(),
6511 E = LHSInheritedProtocols.end(); I != E; ++I) {
6512 bool match = false;
6513 ObjCProtocolDecl *lhsProto = (*I);
6514 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6515 E = rhsQID->qual_end(); J != E; ++J) {
6516 ObjCProtocolDecl *rhsProto = *J;
6517 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6518 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6519 match = true;
6520 break;
6521 }
6522 }
6523 if (!match)
6524 return false;
6525 }
6526 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006527 return true;
6528 }
6529 return false;
6530}
6531
Eli Friedman47f77112008-08-22 00:56:42 +00006532/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006533/// compatible for assignment from RHS to LHS. This handles validation of any
6534/// protocol qualifiers on the LHS or RHS.
6535///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006536bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6537 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006538 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6539 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6540
Steve Naroff1329fa02009-07-15 18:40:39 +00006541 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006542 if (LHS->isObjCUnqualifiedIdOrClass() ||
6543 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006544 return true;
6545
John McCall8b07ec22010-05-15 11:32:37 +00006546 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006547 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6548 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006549 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006550
6551 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6552 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6553 QualType(RHSOPT,0));
6554
John McCall8b07ec22010-05-15 11:32:37 +00006555 // If we have 2 user-defined types, fall into that path.
6556 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006557 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006558
Steve Naroff8e6aee52009-07-23 01:01:38 +00006559 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006560}
6561
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006562/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006563/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006564/// arguments in block literals. When passed as arguments, passing 'A*' where
6565/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6566/// not OK. For the return type, the opposite is not OK.
6567bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6568 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006569 const ObjCObjectPointerType *RHSOPT,
6570 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006571 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006572 return true;
6573
6574 if (LHSOPT->isObjCBuiltinType()) {
6575 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6576 }
6577
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006578 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006579 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6580 QualType(RHSOPT,0),
6581 false);
6582
6583 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6584 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6585 if (LHS && RHS) { // We have 2 user-defined types.
6586 if (LHS != RHS) {
6587 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006588 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006589 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006590 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006591 }
6592 else
6593 return true;
6594 }
6595 return false;
6596}
6597
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006598/// getIntersectionOfProtocols - This routine finds the intersection of set
6599/// of protocols inherited from two distinct objective-c pointer objects.
6600/// It is used to build composite qualifier list of the composite type of
6601/// the conditional expression involving two objective-c pointer objects.
6602static
6603void getIntersectionOfProtocols(ASTContext &Context,
6604 const ObjCObjectPointerType *LHSOPT,
6605 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006606 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006607
John McCall8b07ec22010-05-15 11:32:37 +00006608 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6609 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6610 assert(LHS->getInterface() && "LHS must have an interface base");
6611 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006612
6613 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6614 unsigned LHSNumProtocols = LHS->getNumProtocols();
6615 if (LHSNumProtocols > 0)
6616 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6617 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006618 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006619 Context.CollectInheritedProtocols(LHS->getInterface(),
6620 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006621 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6622 LHSInheritedProtocols.end());
6623 }
6624
6625 unsigned RHSNumProtocols = RHS->getNumProtocols();
6626 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006627 ObjCProtocolDecl **RHSProtocols =
6628 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006629 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6630 if (InheritedProtocolSet.count(RHSProtocols[i]))
6631 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006632 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006633 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006634 Context.CollectInheritedProtocols(RHS->getInterface(),
6635 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006636 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6637 RHSInheritedProtocols.begin(),
6638 E = RHSInheritedProtocols.end(); I != E; ++I)
6639 if (InheritedProtocolSet.count((*I)))
6640 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006641 }
6642}
6643
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006644/// areCommonBaseCompatible - Returns common base class of the two classes if
6645/// one found. Note that this is O'2 algorithm. But it will be called as the
6646/// last type comparison in a ?-exp of ObjC pointer types before a
6647/// warning is issued. So, its invokation is extremely rare.
6648QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006649 const ObjCObjectPointerType *Lptr,
6650 const ObjCObjectPointerType *Rptr) {
6651 const ObjCObjectType *LHS = Lptr->getObjectType();
6652 const ObjCObjectType *RHS = Rptr->getObjectType();
6653 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6654 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006655 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006656 return QualType();
6657
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006658 do {
John McCall8b07ec22010-05-15 11:32:37 +00006659 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006660 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006661 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006662 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6663
6664 QualType Result = QualType(LHS, 0);
6665 if (!Protocols.empty())
6666 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6667 Result = getObjCObjectPointerType(Result);
6668 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006669 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006670 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006671
6672 return QualType();
6673}
6674
John McCall8b07ec22010-05-15 11:32:37 +00006675bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6676 const ObjCObjectType *RHS) {
6677 assert(LHS->getInterface() && "LHS is not an interface type");
6678 assert(RHS->getInterface() && "RHS is not an interface type");
6679
Chris Lattner49af6a42008-04-07 06:51:04 +00006680 // Verify that the base decls are compatible: the RHS must be a subclass of
6681 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006682 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006683 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006684
Chris Lattner49af6a42008-04-07 06:51:04 +00006685 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6686 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006687 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006688 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006689
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006690 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6691 // more detailed analysis is required.
6692 if (RHS->getNumProtocols() == 0) {
6693 // OK, if LHS is a superclass of RHS *and*
6694 // this superclass is assignment compatible with LHS.
6695 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006696 bool IsSuperClass =
6697 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6698 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006699 // OK if conversion of LHS to SuperClass results in narrowing of types
6700 // ; i.e., SuperClass may implement at least one of the protocols
6701 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6702 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6703 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006704 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006705 // If super class has no protocols, it is not a match.
6706 if (SuperClassInheritedProtocols.empty())
6707 return false;
6708
6709 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6710 LHSPE = LHS->qual_end();
6711 LHSPI != LHSPE; LHSPI++) {
6712 bool SuperImplementsProtocol = false;
6713 ObjCProtocolDecl *LHSProto = (*LHSPI);
6714
6715 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6716 SuperClassInheritedProtocols.begin(),
6717 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6718 ObjCProtocolDecl *SuperClassProto = (*I);
6719 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6720 SuperImplementsProtocol = true;
6721 break;
6722 }
6723 }
6724 if (!SuperImplementsProtocol)
6725 return false;
6726 }
6727 return true;
6728 }
6729 return false;
6730 }
Mike Stump11289f42009-09-09 15:08:12 +00006731
John McCall8b07ec22010-05-15 11:32:37 +00006732 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6733 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006734 LHSPI != LHSPE; LHSPI++) {
6735 bool RHSImplementsProtocol = false;
6736
6737 // If the RHS doesn't implement the protocol on the left, the types
6738 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006739 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6740 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006741 RHSPI != RHSPE; RHSPI++) {
6742 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006743 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006744 break;
6745 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006746 }
6747 // FIXME: For better diagnostics, consider passing back the protocol name.
6748 if (!RHSImplementsProtocol)
6749 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006750 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006751 // The RHS implements all protocols listed on the LHS.
6752 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006753}
6754
Steve Naroffb7605152009-02-12 17:52:19 +00006755bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6756 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006757 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6758 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006759
Steve Naroff7cae42b2009-07-10 23:34:53 +00006760 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006761 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006762
6763 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6764 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006765}
6766
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006767bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6768 return canAssignObjCInterfaces(
6769 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6770 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6771}
6772
Mike Stump11289f42009-09-09 15:08:12 +00006773/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006774/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006775/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006776/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006777bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6778 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006779 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006780 return hasSameType(LHS, RHS);
6781
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006782 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006783}
6784
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006785bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006786 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006787}
6788
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006789bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6790 return !mergeTypes(LHS, RHS, true).isNull();
6791}
6792
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006793/// mergeTransparentUnionType - if T is a transparent union type and a member
6794/// of T is compatible with SubType, return the merged type, else return
6795/// QualType()
6796QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6797 bool OfBlockPointer,
6798 bool Unqualified) {
6799 if (const RecordType *UT = T->getAsUnionType()) {
6800 RecordDecl *UD = UT->getDecl();
6801 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006802 for (const auto *I : UD->fields()) {
6803 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006804 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6805 if (!MT.isNull())
6806 return MT;
6807 }
6808 }
6809 }
6810
6811 return QualType();
6812}
6813
Alp Toker9cacbab2014-01-20 20:26:09 +00006814/// mergeFunctionParameterTypes - merge two types which appear as function
6815/// parameter types
6816QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
6817 bool OfBlockPointer,
6818 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006819 // GNU extension: two types are compatible if they appear as a function
6820 // argument, one of the types is a transparent union type and the other
6821 // type is compatible with a union member
6822 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6823 Unqualified);
6824 if (!lmerge.isNull())
6825 return lmerge;
6826
6827 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6828 Unqualified);
6829 if (!rmerge.isNull())
6830 return rmerge;
6831
6832 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6833}
6834
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006835QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006836 bool OfBlockPointer,
6837 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006838 const FunctionType *lbase = lhs->getAs<FunctionType>();
6839 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006840 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6841 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006842 bool allLTypes = true;
6843 bool allRTypes = true;
6844
6845 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006846 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006847 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00006848 QualType RHS = rbase->getReturnType();
6849 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00006850 bool UnqualifiedResult = Unqualified;
6851 if (!UnqualifiedResult)
6852 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006853 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006854 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006855 else
Alp Toker314cc812014-01-25 16:55:45 +00006856 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00006857 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006858 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006859
6860 if (Unqualified)
6861 retType = retType.getUnqualifiedType();
6862
Alp Toker314cc812014-01-25 16:55:45 +00006863 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
6864 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006865 if (Unqualified) {
6866 LRetType = LRetType.getUnqualifiedType();
6867 RRetType = RRetType.getUnqualifiedType();
6868 }
6869
6870 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006871 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006872 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006873 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006874
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006875 // FIXME: double check this
6876 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6877 // rbase->getRegParmAttr() != 0 &&
6878 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006879 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6880 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006881
Douglas Gregor8c940862010-01-18 17:14:39 +00006882 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00006883 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00006884 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006885
John McCall8c6b56f2010-12-15 01:06:38 +00006886 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006887 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6888 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006889 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6890 return QualType();
6891
John McCall31168b02011-06-15 23:02:42 +00006892 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6893 return QualType();
6894
John McCall8c6b56f2010-12-15 01:06:38 +00006895 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6896 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006897
Rafael Espindola8778c282012-11-29 16:09:03 +00006898 if (lbaseInfo.getNoReturn() != NoReturn)
6899 allLTypes = false;
6900 if (rbaseInfo.getNoReturn() != NoReturn)
6901 allRTypes = false;
6902
John McCall31168b02011-06-15 23:02:42 +00006903 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006904
Eli Friedman47f77112008-08-22 00:56:42 +00006905 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006906 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6907 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00006908 // Compatible functions must have the same number of parameters
6909 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00006910 return QualType();
6911
6912 // Variadic and non-variadic functions aren't compatible
6913 if (lproto->isVariadic() != rproto->isVariadic())
6914 return QualType();
6915
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006916 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6917 return QualType();
6918
Fariborz Jahanian97676972011-09-28 21:52:05 +00006919 if (LangOpts.ObjCAutoRefCount &&
6920 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6921 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00006922
6923 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006924 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00006925 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
6926 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
6927 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
6928 QualType paramType = mergeFunctionParameterTypes(
6929 lParamType, rParamType, OfBlockPointer, Unqualified);
6930 if (paramType.isNull())
6931 return QualType();
6932
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006933 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00006934 paramType = paramType.getUnqualifiedType();
6935
6936 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006937 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00006938 lParamType = lParamType.getUnqualifiedType();
6939 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006940 }
Alp Toker601b22c2014-01-21 23:35:24 +00006941
6942 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00006943 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00006944 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00006945 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006946 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006947
Eli Friedman47f77112008-08-22 00:56:42 +00006948 if (allLTypes) return lhs;
6949 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006950
6951 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6952 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00006953 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006954 }
6955
6956 if (lproto) allRTypes = false;
6957 if (rproto) allLTypes = false;
6958
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006959 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006960 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006961 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006962 if (proto->isVariadic()) return QualType();
6963 // Check that the types are compatible with the types that
6964 // would result from default argument promotions (C99 6.7.5.3p15).
6965 // The only types actually affected are promotable integer
6966 // types and floats, which would be passed as a different
6967 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00006968 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
6969 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00006970
Eli Friedman448ce402012-08-30 00:44:15 +00006971 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00006972 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00006973 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
6974 paramTy = Enum->getDecl()->getIntegerType();
6975 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00006976 return QualType();
6977 }
Alp Toker601b22c2014-01-21 23:35:24 +00006978
6979 if (paramTy->isPromotableIntegerType() ||
6980 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00006981 return QualType();
6982 }
6983
6984 if (allLTypes) return lhs;
6985 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006986
6987 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6988 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00006989 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006990 }
6991
6992 if (allLTypes) return lhs;
6993 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00006994 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00006995}
6996
John McCall433c2e62013-03-21 00:10:07 +00006997/// Given that we have an enum type and a non-enum type, try to merge them.
6998static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
6999 QualType other, bool isBlockReturnType) {
7000 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7001 // a signed integer type, or an unsigned integer type.
7002 // Compatibility is based on the underlying type, not the promotion
7003 // type.
7004 QualType underlyingType = ET->getDecl()->getIntegerType();
7005 if (underlyingType.isNull()) return QualType();
7006 if (Context.hasSameType(underlyingType, other))
7007 return other;
7008
7009 // In block return types, we're more permissive and accept any
7010 // integral type of the same size.
7011 if (isBlockReturnType && other->isIntegerType() &&
7012 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7013 return other;
7014
7015 return QualType();
7016}
7017
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007018QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007019 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007020 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007021 // C++ [expr]: If an expression initially has the type "reference to T", the
7022 // type is adjusted to "T" prior to any further analysis, the expression
7023 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007024 // expression is an lvalue unless the reference is an rvalue reference and
7025 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007026 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7027 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007028
7029 if (Unqualified) {
7030 LHS = LHS.getUnqualifiedType();
7031 RHS = RHS.getUnqualifiedType();
7032 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007033
Eli Friedman47f77112008-08-22 00:56:42 +00007034 QualType LHSCan = getCanonicalType(LHS),
7035 RHSCan = getCanonicalType(RHS);
7036
7037 // If two types are identical, they are compatible.
7038 if (LHSCan == RHSCan)
7039 return LHS;
7040
John McCall8ccfcb52009-09-24 19:53:00 +00007041 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007042 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7043 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007044 if (LQuals != RQuals) {
7045 // If any of these qualifiers are different, we have a type
7046 // mismatch.
7047 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007048 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7049 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007050 return QualType();
7051
7052 // Exactly one GC qualifier difference is allowed: __strong is
7053 // okay if the other type has no GC qualifier but is an Objective
7054 // C object pointer (i.e. implicitly strong by default). We fix
7055 // this by pretending that the unqualified type was actually
7056 // qualified __strong.
7057 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7058 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7059 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7060
7061 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7062 return QualType();
7063
7064 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7065 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7066 }
7067 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7068 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7069 }
Eli Friedman47f77112008-08-22 00:56:42 +00007070 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007071 }
7072
7073 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007074
Eli Friedmandcca6332009-06-01 01:22:52 +00007075 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7076 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007077
Chris Lattnerfd652912008-01-14 05:45:46 +00007078 // We want to consider the two function types to be the same for these
7079 // comparisons, just force one to the other.
7080 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7081 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007082
7083 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007084 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7085 LHSClass = Type::ConstantArray;
7086 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7087 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007088
John McCall8b07ec22010-05-15 11:32:37 +00007089 // ObjCInterfaces are just specialized ObjCObjects.
7090 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7091 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7092
Nate Begemance4d7fc2008-04-18 23:10:10 +00007093 // Canonicalize ExtVector -> Vector.
7094 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7095 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007096
Chris Lattner95554662008-04-07 05:43:21 +00007097 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007098 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007099 // Note that we only have special rules for turning block enum
7100 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007101 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007102 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007103 }
John McCall9dd450b2009-09-21 23:43:11 +00007104 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007105 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007106 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007107 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007108 if (OfBlockPointer && !BlockReturnType) {
7109 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7110 return LHS;
7111 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7112 return RHS;
7113 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007114
Eli Friedman47f77112008-08-22 00:56:42 +00007115 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007116 }
Eli Friedman47f77112008-08-22 00:56:42 +00007117
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007118 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007119 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007120#define TYPE(Class, Base)
7121#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007122#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007123#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7124#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7125#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007126 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007127
Richard Smith27d807c2013-04-30 13:56:41 +00007128 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007129 case Type::LValueReference:
7130 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007131 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007132 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007133
John McCall8b07ec22010-05-15 11:32:37 +00007134 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007135 case Type::IncompleteArray:
7136 case Type::VariableArray:
7137 case Type::FunctionProto:
7138 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007139 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007140
Chris Lattnerfd652912008-01-14 05:45:46 +00007141 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007142 {
7143 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007144 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7145 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007146 if (Unqualified) {
7147 LHSPointee = LHSPointee.getUnqualifiedType();
7148 RHSPointee = RHSPointee.getUnqualifiedType();
7149 }
7150 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7151 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007152 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007153 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007154 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007155 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007156 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007157 return getPointerType(ResultType);
7158 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007159 case Type::BlockPointer:
7160 {
7161 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007162 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7163 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007164 if (Unqualified) {
7165 LHSPointee = LHSPointee.getUnqualifiedType();
7166 RHSPointee = RHSPointee.getUnqualifiedType();
7167 }
7168 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7169 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007170 if (ResultType.isNull()) return QualType();
7171 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7172 return LHS;
7173 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7174 return RHS;
7175 return getBlockPointerType(ResultType);
7176 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007177 case Type::Atomic:
7178 {
7179 // Merge two pointer types, while trying to preserve typedef info
7180 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7181 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7182 if (Unqualified) {
7183 LHSValue = LHSValue.getUnqualifiedType();
7184 RHSValue = RHSValue.getUnqualifiedType();
7185 }
7186 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7187 Unqualified);
7188 if (ResultType.isNull()) return QualType();
7189 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7190 return LHS;
7191 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7192 return RHS;
7193 return getAtomicType(ResultType);
7194 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007195 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007196 {
7197 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7198 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7199 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7200 return QualType();
7201
7202 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7203 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007204 if (Unqualified) {
7205 LHSElem = LHSElem.getUnqualifiedType();
7206 RHSElem = RHSElem.getUnqualifiedType();
7207 }
7208
7209 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007210 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007211 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7212 return LHS;
7213 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7214 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007215 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7216 ArrayType::ArraySizeModifier(), 0);
7217 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7218 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007219 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7220 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007221 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7222 return LHS;
7223 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7224 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007225 if (LVAT) {
7226 // FIXME: This isn't correct! But tricky to implement because
7227 // the array's size has to be the size of LHS, but the type
7228 // has to be different.
7229 return LHS;
7230 }
7231 if (RVAT) {
7232 // FIXME: This isn't correct! But tricky to implement because
7233 // the array's size has to be the size of RHS, but the type
7234 // has to be different.
7235 return RHS;
7236 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007237 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7238 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007239 return getIncompleteArrayType(ResultType,
7240 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007241 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007242 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007243 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007244 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007245 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007246 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007247 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007248 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007249 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007250 case Type::Complex:
7251 // Distinct complex types are incompatible.
7252 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007253 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007254 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007255 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7256 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007257 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007258 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007259 case Type::ObjCObject: {
7260 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007261 // FIXME: This should be type compatibility, e.g. whether
7262 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007263 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7264 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7265 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007266 return LHS;
7267
Eli Friedman47f77112008-08-22 00:56:42 +00007268 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007269 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007270 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007271 if (OfBlockPointer) {
7272 if (canAssignObjCInterfacesInBlockPointer(
7273 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007274 RHS->getAs<ObjCObjectPointerType>(),
7275 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007276 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007277 return QualType();
7278 }
John McCall9dd450b2009-09-21 23:43:11 +00007279 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7280 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007281 return LHS;
7282
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007283 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007284 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007285 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007286
David Blaikie8a40f702012-01-17 06:56:22 +00007287 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007288}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007289
Fariborz Jahanian97676972011-09-28 21:52:05 +00007290bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7291 const FunctionProtoType *FromFunctionType,
7292 const FunctionProtoType *ToFunctionType) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007293 if (FromFunctionType->hasAnyConsumedParams() !=
7294 ToFunctionType->hasAnyConsumedParams())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007295 return false;
7296 FunctionProtoType::ExtProtoInfo FromEPI =
7297 FromFunctionType->getExtProtoInfo();
7298 FunctionProtoType::ExtProtoInfo ToEPI =
7299 ToFunctionType->getExtProtoInfo();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007300 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
Alp Toker601b22c2014-01-21 23:35:24 +00007301 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7302 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
Fariborz Jahanian97676972011-09-28 21:52:05 +00007303 return false;
7304 }
7305 return true;
7306}
7307
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007308/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7309/// 'RHS' attributes and returns the merged version; including for function
7310/// return types.
7311QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7312 QualType LHSCan = getCanonicalType(LHS),
7313 RHSCan = getCanonicalType(RHS);
7314 // If two types are identical, they are compatible.
7315 if (LHSCan == RHSCan)
7316 return LHS;
7317 if (RHSCan->isFunctionType()) {
7318 if (!LHSCan->isFunctionType())
7319 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007320 QualType OldReturnType =
7321 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007322 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007323 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007324 QualType ResReturnType =
7325 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7326 if (ResReturnType.isNull())
7327 return QualType();
7328 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7329 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7330 // In either case, use OldReturnType to build the new function type.
7331 const FunctionType *F = LHS->getAs<FunctionType>();
7332 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007333 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7334 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007335 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007336 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007337 return ResultType;
7338 }
7339 }
7340 return QualType();
7341 }
7342
7343 // If the qualifiers are different, the types can still be merged.
7344 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7345 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7346 if (LQuals != RQuals) {
7347 // If any of these qualifiers are different, we have a type mismatch.
7348 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7349 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7350 return QualType();
7351
7352 // Exactly one GC qualifier difference is allowed: __strong is
7353 // okay if the other type has no GC qualifier but is an Objective
7354 // C object pointer (i.e. implicitly strong by default). We fix
7355 // this by pretending that the unqualified type was actually
7356 // qualified __strong.
7357 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7358 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7359 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7360
7361 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7362 return QualType();
7363
7364 if (GC_L == Qualifiers::Strong)
7365 return LHS;
7366 if (GC_R == Qualifiers::Strong)
7367 return RHS;
7368 return QualType();
7369 }
7370
7371 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7372 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7373 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7374 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7375 if (ResQT == LHSBaseQT)
7376 return LHS;
7377 if (ResQT == RHSBaseQT)
7378 return RHS;
7379 }
7380 return QualType();
7381}
7382
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007383//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007384// Integer Predicates
7385//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007386
Jay Foad39c79802011-01-12 09:06:06 +00007387unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007388 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007389 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007390 if (T->isBooleanType())
7391 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007392 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007393 return (unsigned)getTypeSize(T);
7394}
7395
Abramo Bagnara13640492012-09-09 10:21:24 +00007396QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007397 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007398
7399 // Turn <4 x signed int> -> <4 x unsigned int>
7400 if (const VectorType *VTy = T->getAs<VectorType>())
7401 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007402 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007403
7404 // For enums, we return the unsigned version of the base type.
7405 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007406 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007407
7408 const BuiltinType *BTy = T->getAs<BuiltinType>();
7409 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007410 switch (BTy->getKind()) {
7411 case BuiltinType::Char_S:
7412 case BuiltinType::SChar:
7413 return UnsignedCharTy;
7414 case BuiltinType::Short:
7415 return UnsignedShortTy;
7416 case BuiltinType::Int:
7417 return UnsignedIntTy;
7418 case BuiltinType::Long:
7419 return UnsignedLongTy;
7420 case BuiltinType::LongLong:
7421 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007422 case BuiltinType::Int128:
7423 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007424 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007425 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007426 }
7427}
7428
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007429ASTMutationListener::~ASTMutationListener() { }
7430
Richard Smith1fa5d642013-05-11 05:45:24 +00007431void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7432 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007433
7434//===----------------------------------------------------------------------===//
7435// Builtin Type Computation
7436//===----------------------------------------------------------------------===//
7437
7438/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007439/// pointer over the consumed characters. This returns the resultant type. If
7440/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7441/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7442/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007443///
7444/// RequiresICE is filled in on return to indicate whether the value is required
7445/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007446static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007447 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007448 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007449 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007450 // Modifiers.
7451 int HowLong = 0;
7452 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007453 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007454
Chris Lattnerdc226c22010-10-01 22:42:38 +00007455 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007456 bool Done = false;
7457 while (!Done) {
7458 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007459 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007460 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007461 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007462 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007463 case 'S':
7464 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7465 assert(!Signed && "Can't use 'S' modifier multiple times!");
7466 Signed = true;
7467 break;
7468 case 'U':
7469 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7470 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7471 Unsigned = true;
7472 break;
7473 case 'L':
7474 assert(HowLong <= 2 && "Can't have LLLL modifier");
7475 ++HowLong;
7476 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00007477 case 'W':
7478 // This modifier represents int64 type.
7479 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7480 switch (Context.getTargetInfo().getInt64Type()) {
7481 default:
7482 llvm_unreachable("Unexpected integer type");
7483 case TargetInfo::SignedLong:
7484 HowLong = 1;
7485 break;
7486 case TargetInfo::SignedLongLong:
7487 HowLong = 2;
7488 break;
7489 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00007490 }
7491 }
7492
7493 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007494
Chris Lattnerecd79c62009-06-14 00:45:47 +00007495 // Read the base type.
7496 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007497 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007498 case 'v':
7499 assert(HowLong == 0 && !Signed && !Unsigned &&
7500 "Bad modifiers used with 'v'!");
7501 Type = Context.VoidTy;
7502 break;
Jack Carter24bef982013-08-15 15:16:57 +00007503 case 'h':
7504 assert(HowLong == 0 && !Signed && !Unsigned &&
7505 "Bad modifiers used with 'f'!");
7506 Type = Context.HalfTy;
7507 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007508 case 'f':
7509 assert(HowLong == 0 && !Signed && !Unsigned &&
7510 "Bad modifiers used with 'f'!");
7511 Type = Context.FloatTy;
7512 break;
7513 case 'd':
7514 assert(HowLong < 2 && !Signed && !Unsigned &&
7515 "Bad modifiers used with 'd'!");
7516 if (HowLong)
7517 Type = Context.LongDoubleTy;
7518 else
7519 Type = Context.DoubleTy;
7520 break;
7521 case 's':
7522 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7523 if (Unsigned)
7524 Type = Context.UnsignedShortTy;
7525 else
7526 Type = Context.ShortTy;
7527 break;
7528 case 'i':
7529 if (HowLong == 3)
7530 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7531 else if (HowLong == 2)
7532 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7533 else if (HowLong == 1)
7534 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7535 else
7536 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7537 break;
7538 case 'c':
7539 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7540 if (Signed)
7541 Type = Context.SignedCharTy;
7542 else if (Unsigned)
7543 Type = Context.UnsignedCharTy;
7544 else
7545 Type = Context.CharTy;
7546 break;
7547 case 'b': // boolean
7548 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7549 Type = Context.BoolTy;
7550 break;
7551 case 'z': // size_t.
7552 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7553 Type = Context.getSizeType();
7554 break;
7555 case 'F':
7556 Type = Context.getCFConstantStringType();
7557 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007558 case 'G':
7559 Type = Context.getObjCIdType();
7560 break;
7561 case 'H':
7562 Type = Context.getObjCSelType();
7563 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007564 case 'M':
7565 Type = Context.getObjCSuperType();
7566 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007567 case 'a':
7568 Type = Context.getBuiltinVaListType();
7569 assert(!Type.isNull() && "builtin va list type not initialized!");
7570 break;
7571 case 'A':
7572 // This is a "reference" to a va_list; however, what exactly
7573 // this means depends on how va_list is defined. There are two
7574 // different kinds of va_list: ones passed by value, and ones
7575 // passed by reference. An example of a by-value va_list is
7576 // x86, where va_list is a char*. An example of by-ref va_list
7577 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7578 // we want this argument to be a char*&; for x86-64, we want
7579 // it to be a __va_list_tag*.
7580 Type = Context.getBuiltinVaListType();
7581 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007582 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007583 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007584 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007585 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007586 break;
7587 case 'V': {
7588 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007589 unsigned NumElements = strtoul(Str, &End, 10);
7590 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007591 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007592
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007593 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7594 RequiresICE, false);
7595 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007596
7597 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007598 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007599 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007600 break;
7601 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007602 case 'E': {
7603 char *End;
7604
7605 unsigned NumElements = strtoul(Str, &End, 10);
7606 assert(End != Str && "Missing vector size");
7607
7608 Str = End;
7609
7610 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7611 false);
7612 Type = Context.getExtVectorType(ElementType, NumElements);
7613 break;
7614 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007615 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007616 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7617 false);
7618 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007619 Type = Context.getComplexType(ElementType);
7620 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007621 }
7622 case 'Y' : {
7623 Type = Context.getPointerDiffType();
7624 break;
7625 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007626 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007627 Type = Context.getFILEType();
7628 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007629 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007630 return QualType();
7631 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007632 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007633 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007634 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007635 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007636 else
7637 Type = Context.getjmp_bufType();
7638
Mike Stump2adb4da2009-07-28 23:47:15 +00007639 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007640 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007641 return QualType();
7642 }
7643 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007644 case 'K':
7645 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7646 Type = Context.getucontext_tType();
7647
7648 if (Type.isNull()) {
7649 Error = ASTContext::GE_Missing_ucontext;
7650 return QualType();
7651 }
7652 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007653 case 'p':
7654 Type = Context.getProcessIDType();
7655 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007656 }
Mike Stump11289f42009-09-09 15:08:12 +00007657
Chris Lattnerdc226c22010-10-01 22:42:38 +00007658 // If there are modifiers and if we're allowed to parse them, go for it.
7659 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007660 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007661 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007662 default: Done = true; --Str; break;
7663 case '*':
7664 case '&': {
7665 // Both pointers and references can have their pointee types
7666 // qualified with an address space.
7667 char *End;
7668 unsigned AddrSpace = strtoul(Str, &End, 10);
7669 if (End != Str && AddrSpace != 0) {
7670 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7671 Str = End;
7672 }
7673 if (c == '*')
7674 Type = Context.getPointerType(Type);
7675 else
7676 Type = Context.getLValueReferenceType(Type);
7677 break;
7678 }
7679 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7680 case 'C':
7681 Type = Type.withConst();
7682 break;
7683 case 'D':
7684 Type = Context.getVolatileType(Type);
7685 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007686 case 'R':
7687 Type = Type.withRestrict();
7688 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007689 }
7690 }
Chris Lattner84733392010-10-01 07:13:18 +00007691
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007692 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007693 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007694
Chris Lattnerecd79c62009-06-14 00:45:47 +00007695 return Type;
7696}
7697
7698/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007699QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007700 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007701 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007702 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007703
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007704 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007705
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007706 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007707 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007708 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7709 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007710 if (Error != GE_None)
7711 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007712
7713 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7714
Chris Lattnerecd79c62009-06-14 00:45:47 +00007715 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007716 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007717 if (Error != GE_None)
7718 return QualType();
7719
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007720 // If this argument is required to be an IntegerConstantExpression and the
7721 // caller cares, fill in the bitmask we return.
7722 if (RequiresICE && IntegerConstantArgs)
7723 *IntegerConstantArgs |= 1 << ArgTypes.size();
7724
Chris Lattnerecd79c62009-06-14 00:45:47 +00007725 // Do array -> pointer decay. The builtin should use the decayed type.
7726 if (Ty->isArrayType())
7727 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007728
Chris Lattnerecd79c62009-06-14 00:45:47 +00007729 ArgTypes.push_back(Ty);
7730 }
7731
7732 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7733 "'.' should only occur at end of builtin type list!");
7734
Reid Kleckner78af0702013-08-27 23:08:25 +00007735 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00007736 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7737
7738 bool Variadic = (TypeStr[0] == '.');
7739
7740 // We really shouldn't be making a no-proto type here, especially in C++.
7741 if (ArgTypes.empty() && Variadic)
7742 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007743
John McCalldb40c7f2010-12-14 08:05:40 +00007744 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007745 EPI.ExtInfo = EI;
7746 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007747
Jordan Rose5c382722013-03-08 21:51:21 +00007748 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007749}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007750
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007751GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007752 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007753 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007754
Rafael Espindola3ae00052013-05-13 00:12:11 +00007755 GVALinkage External = GVA_StrongExternal;
7756 switch (FD->getTemplateSpecializationKind()) {
7757 case TSK_Undeclared:
7758 case TSK_ExplicitSpecialization:
7759 External = GVA_StrongExternal;
7760 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007761
Rafael Espindola3ae00052013-05-13 00:12:11 +00007762 case TSK_ExplicitInstantiationDefinition:
7763 return GVA_ExplicitTemplateInstantiation;
7764
7765 case TSK_ExplicitInstantiationDeclaration:
7766 case TSK_ImplicitInstantiation:
7767 External = GVA_TemplateInstantiation;
7768 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007769 }
7770
7771 if (!FD->isInlined())
7772 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00007773
Alp Tokerbfa39342014-01-14 12:51:41 +00007774 if ((!getLangOpts().CPlusPlus && !getLangOpts().MSVCCompat) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00007775 FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007776 // GNU or C99 inline semantics. Determine whether this symbol should be
7777 // externally visible.
7778 if (FD->isInlineDefinitionExternallyVisible())
7779 return External;
7780
7781 // C99 inline semantics, where the symbol is not externally visible.
7782 return GVA_C99Inline;
7783 }
7784
7785 // C++0x [temp.explicit]p9:
7786 // [ Note: The intent is that an inline function that is the subject of
7787 // an explicit instantiation declaration will still be implicitly
7788 // instantiated when used so that the body can be considered for
7789 // inlining, but that no out-of-line copy of the inline function would be
7790 // generated in the translation unit. -- end note ]
7791 if (FD->getTemplateSpecializationKind()
7792 == TSK_ExplicitInstantiationDeclaration)
7793 return GVA_C99Inline;
7794
7795 return GVA_CXXInline;
7796}
7797
7798GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007799 if (!VD->isExternallyVisible())
7800 return GVA_Internal;
7801
Richard Smith8809a0c2013-09-27 20:14:12 +00007802 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007803 case TSK_Undeclared:
7804 case TSK_ExplicitSpecialization:
7805 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007806
Rafael Espindola3ae00052013-05-13 00:12:11 +00007807 case TSK_ExplicitInstantiationDeclaration:
7808 llvm_unreachable("Variable should not be instantiated");
7809 // Fall through to treat this like any other instantiation.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007810
Rafael Espindola3ae00052013-05-13 00:12:11 +00007811 case TSK_ExplicitInstantiationDefinition:
7812 return GVA_ExplicitTemplateInstantiation;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007813
Rafael Espindola3ae00052013-05-13 00:12:11 +00007814 case TSK_ImplicitInstantiation:
7815 return GVA_TemplateInstantiation;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007816 }
Rafael Espindola27699c82013-05-13 14:05:53 +00007817
7818 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007819}
7820
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007821bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007822 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7823 if (!VD->isFileVarDecl())
7824 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00007825 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7826 // We never need to emit an uninstantiated function template.
7827 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7828 return false;
7829 } else
7830 return false;
7831
7832 // If this is a member of a class template, we do not need to emit it.
7833 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007834 return false;
7835
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007836 // Weak references don't produce any output by themselves.
7837 if (D->hasAttr<WeakRefAttr>())
7838 return false;
7839
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007840 // Aliases and used decls are required.
7841 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7842 return true;
7843
7844 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7845 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007846 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007847 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007848
7849 // Constructors and destructors are required.
7850 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7851 return true;
7852
John McCall6bd2a892013-01-25 22:31:03 +00007853 // The key function for a class is required. This rule only comes
7854 // into play when inline functions can be key functions, though.
7855 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7856 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7857 const CXXRecordDecl *RD = MD->getParent();
7858 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7859 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7860 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7861 return true;
7862 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007863 }
7864 }
7865
7866 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7867
7868 // static, static inline, always_inline, and extern inline functions can
7869 // always be deferred. Normal inline functions can be deferred in C99/C++.
7870 // Implicit template instantiations can also be deferred in C++.
7871 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007872 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007873 return false;
7874 return true;
7875 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007876
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007877 const VarDecl *VD = cast<VarDecl>(D);
7878 assert(VD->isFileVarDecl() && "Expected file scoped var");
7879
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007880 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7881 return false;
7882
Richard Smitha0e5e542012-11-12 21:38:00 +00007883 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007884 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smitha0e5e542012-11-12 21:38:00 +00007885 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7886 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007887
Richard Smitha0e5e542012-11-12 21:38:00 +00007888 // Variables that have destruction with side-effects are required.
7889 if (VD->getType().isDestructedType())
7890 return true;
7891
7892 // Variables that have initialization with side-effects are required.
7893 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7894 return true;
7895
7896 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007897}
Charles Davis53c59df2010-08-16 03:33:14 +00007898
Reid Kleckner78af0702013-08-27 23:08:25 +00007899CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
7900 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00007901 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00007902 if (IsCXXMethod)
7903 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007904
Reid Kleckner78af0702013-08-27 23:08:25 +00007905 return (LangOpts.MRTD && !IsVariadic) ? CC_X86StdCall : CC_C;
Charles Davis99202b32010-11-09 18:04:24 +00007906}
7907
Jay Foad39c79802011-01-12 09:06:06 +00007908bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007909 // Pass through to the C++ ABI object
7910 return ABI->isNearlyEmpty(RD);
7911}
7912
Reid Kleckner96f8f932014-02-05 17:27:08 +00007913VTableContextBase *ASTContext::getVTableContext() {
7914 if (!VTContext.get()) {
7915 if (Target->getCXXABI().isMicrosoft())
7916 VTContext.reset(new MicrosoftVTableContext(*this));
7917 else
7918 VTContext.reset(new ItaniumVTableContext(*this));
7919 }
7920 return VTContext.get();
7921}
7922
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007923MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00007924 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00007925 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00007926 case TargetCXXABI::GenericItanium:
7927 case TargetCXXABI::GenericARM:
7928 case TargetCXXABI::iOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00007929 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00007930 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00007931 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007932 }
David Blaikie83d382b2011-09-23 05:06:16 +00007933 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007934}
7935
Charles Davis53c59df2010-08-16 03:33:14 +00007936CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007937
7938size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00007939 return ASTRecordLayouts.getMemorySize() +
7940 llvm::capacity_in_bytes(ObjCLayouts) +
7941 llvm::capacity_in_bytes(KeyFunctions) +
7942 llvm::capacity_in_bytes(ObjCImpls) +
7943 llvm::capacity_in_bytes(BlockVarCopyInits) +
7944 llvm::capacity_in_bytes(DeclAttrs) +
7945 llvm::capacity_in_bytes(TemplateOrInstantiation) +
7946 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
7947 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
7948 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
7949 llvm::capacity_in_bytes(OverriddenMethods) +
7950 llvm::capacity_in_bytes(Types) +
7951 llvm::capacity_in_bytes(VariableArrayTypes) +
7952 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007953}
Ted Kremenek540017e2011-10-06 05:00:56 +00007954
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007955/// getIntTypeForBitwidth -
7956/// sets integer QualTy according to specified details:
7957/// bitwidth, signed/unsigned.
7958/// Returns empty type if there is no appropriate target types.
7959QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
7960 unsigned Signed) const {
7961 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
7962 CanQualType QualTy = getFromTargetType(Ty);
7963 if (!QualTy && DestWidth == 128)
7964 return Signed ? Int128Ty : UnsignedInt128Ty;
7965 return QualTy;
7966}
7967
7968/// getRealTypeForBitwidth -
7969/// sets floating point QualTy according to specified bitwidth.
7970/// Returns empty type if there is no appropriate target types.
7971QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
7972 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
7973 switch (Ty) {
7974 case TargetInfo::Float:
7975 return FloatTy;
7976 case TargetInfo::Double:
7977 return DoubleTy;
7978 case TargetInfo::LongDouble:
7979 return LongDoubleTy;
7980 case TargetInfo::NoFloat:
7981 return QualType();
7982 }
7983
7984 llvm_unreachable("Unhandled TargetInfo::RealType value");
7985}
7986
Eli Friedman3b7d46c2013-07-10 00:30:46 +00007987void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
7988 if (Number > 1)
7989 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00007990}
7991
Eli Friedman3b7d46c2013-07-10 00:30:46 +00007992unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
7993 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
7994 MangleNumbers.find(ND);
7995 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00007996}
7997
David Majnemer2206bf52014-03-05 08:57:59 +00007998void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
7999 if (Number > 1)
8000 StaticLocalNumbers[VD] = Number;
8001}
8002
8003unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8004 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8005 StaticLocalNumbers.find(VD);
8006 return I != StaticLocalNumbers.end() ? I->second : 1;
8007}
8008
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008009MangleNumberingContext &
8010ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008011 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8012 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8013 if (!MCtx)
8014 MCtx = createMangleNumberingContext();
8015 return *MCtx;
8016}
8017
8018MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8019 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008020}
8021
Ted Kremenek540017e2011-10-06 05:00:56 +00008022void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8023 ParamIndices[D] = index;
8024}
8025
8026unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8027 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8028 assert(I != ParamIndices.end() &&
8029 "ParmIndices lacks entry set by ParmVarDecl");
8030 return I->second;
8031}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008032
Richard Smithe6c01442013-06-05 00:46:14 +00008033APValue *
8034ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8035 bool MayCreate) {
8036 assert(E && E->getStorageDuration() == SD_Static &&
8037 "don't need to cache the computed value for this temporary");
8038 if (MayCreate)
8039 return &MaterializedTemporaryValues[E];
8040
8041 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8042 MaterializedTemporaryValues.find(E);
8043 return I == MaterializedTemporaryValues.end() ? 0 : &I->second;
8044}
8045
Fariborz Jahanian615de762013-05-28 17:37:39 +00008046bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8047 const llvm::Triple &T = getTargetInfo().getTriple();
8048 if (!T.isOSDarwin())
8049 return false;
8050
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008051 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8052 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8053 return false;
8054
Fariborz Jahanian615de762013-05-28 17:37:39 +00008055 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8056 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8057 uint64_t Size = sizeChars.getQuantity();
8058 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8059 unsigned Align = alignChars.getQuantity();
8060 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8061 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8062}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008063
8064namespace {
8065
8066 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8067 /// parents as defined by the \c RecursiveASTVisitor.
8068 ///
8069 /// Note that the relationship described here is purely in terms of AST
8070 /// traversal - there are other relationships (for example declaration context)
8071 /// in the AST that are better modeled by special matchers.
8072 ///
8073 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8074 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8075
8076 public:
8077 /// \brief Builds and returns the translation unit's parent map.
8078 ///
8079 /// The caller takes ownership of the returned \c ParentMap.
8080 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8081 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8082 Visitor.TraverseDecl(&TU);
8083 return Visitor.Parents;
8084 }
8085
8086 private:
8087 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8088
8089 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8090 }
8091
8092 bool shouldVisitTemplateInstantiations() const {
8093 return true;
8094 }
8095 bool shouldVisitImplicitCode() const {
8096 return true;
8097 }
8098 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8099 // are not triggered during data recursion.
8100 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8101 return false;
8102 }
8103
8104 template <typename T>
8105 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
8106 if (Node == NULL)
8107 return true;
8108 if (ParentStack.size() > 0)
8109 // FIXME: Currently we add the same parent multiple times, for example
8110 // when we visit all subexpressions of template instantiations; this is
8111 // suboptimal, bug benign: the only way to visit those is with
8112 // hasAncestor / hasParent, and those do not create new matches.
8113 // The plan is to enable DynTypedNode to be storable in a map or hash
8114 // map. The main problem there is to implement hash functions /
8115 // comparison operators for all types that DynTypedNode supports that
8116 // do not have pointer identity.
8117 (*Parents)[Node].push_back(ParentStack.back());
8118 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8119 bool Result = (this ->* traverse) (Node);
8120 ParentStack.pop_back();
8121 return Result;
8122 }
8123
8124 bool TraverseDecl(Decl *DeclNode) {
8125 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8126 }
8127
8128 bool TraverseStmt(Stmt *StmtNode) {
8129 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8130 }
8131
8132 ASTContext::ParentMap *Parents;
8133 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8134
8135 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8136 };
8137
8138} // end namespace
8139
8140ASTContext::ParentVector
8141ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8142 assert(Node.getMemoizationData() &&
8143 "Invariant broken: only nodes that support memoization may be "
8144 "used in the parent map.");
8145 if (!AllParents) {
8146 // We always need to run over the whole translation unit, as
8147 // hasAncestor can escape any subtree.
8148 AllParents.reset(
8149 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8150 }
8151 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8152 if (I == AllParents->end()) {
8153 return ParentVector();
8154 }
8155 return I->second;
8156}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008157
8158bool
8159ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8160 const ObjCMethodDecl *MethodImpl) {
8161 // No point trying to match an unavailable/deprecated mothod.
8162 if (MethodDecl->hasAttr<UnavailableAttr>()
8163 || MethodDecl->hasAttr<DeprecatedAttr>())
8164 return false;
8165 if (MethodDecl->getObjCDeclQualifier() !=
8166 MethodImpl->getObjCDeclQualifier())
8167 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008168 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008169 return false;
8170
8171 if (MethodDecl->param_size() != MethodImpl->param_size())
8172 return false;
8173
8174 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8175 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8176 EF = MethodDecl->param_end();
8177 IM != EM && IF != EF; ++IM, ++IF) {
8178 const ParmVarDecl *DeclVar = (*IF);
8179 const ParmVarDecl *ImplVar = (*IM);
8180 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8181 return false;
8182 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8183 return false;
8184 }
8185 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8186
8187}