blob: 514a4e15b15e854b21411133216bcd9a0a728b2b [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)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001830 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001831 PE = OC->protocol_end(); P != PE; ++P) {
1832 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001833 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001834 for (const auto *P : Proto->protocols())
1835 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001836 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001837 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001838 for (auto *Proto : OP->protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001839 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001840 for (const auto *P : Proto->protocols())
1841 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001842 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001843 }
1844}
1845
Jay Foad39c79802011-01-12 09:06:06 +00001846unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001847 unsigned count = 0;
1848 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00001849 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001850 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001851
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001852 // Count ivar defined in this class's implementation. This
1853 // includes synthesized ivars.
1854 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001855 count += ImplDecl->ivar_size();
1856
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001857 return count;
1858}
1859
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001860bool ASTContext::isSentinelNullExpr(const Expr *E) {
1861 if (!E)
1862 return false;
1863
1864 // nullptr_t is always treated as null.
1865 if (E->getType()->isNullPtrType()) return true;
1866
1867 if (E->getType()->isAnyPointerType() &&
1868 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1869 Expr::NPC_ValueDependentIsNull))
1870 return true;
1871
1872 // Unfortunately, __null has type 'int'.
1873 if (isa<GNUNullExpr>(E)) return true;
1874
1875 return false;
1876}
1877
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001878/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1879ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1880 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1881 I = ObjCImpls.find(D);
1882 if (I != ObjCImpls.end())
1883 return cast<ObjCImplementationDecl>(I->second);
1884 return 0;
1885}
1886/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1887ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1888 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1889 I = ObjCImpls.find(D);
1890 if (I != ObjCImpls.end())
1891 return cast<ObjCCategoryImplDecl>(I->second);
1892 return 0;
1893}
1894
1895/// \brief Set the implementation of ObjCInterfaceDecl.
1896void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1897 ObjCImplementationDecl *ImplD) {
1898 assert(IFaceD && ImplD && "Passed null params");
1899 ObjCImpls[IFaceD] = ImplD;
1900}
1901/// \brief Set the implementation of ObjCCategoryDecl.
1902void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1903 ObjCCategoryImplDecl *ImplD) {
1904 assert(CatD && ImplD && "Passed null params");
1905 ObjCImpls[CatD] = ImplD;
1906}
1907
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001908const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1909 const NamedDecl *ND) const {
1910 if (const ObjCInterfaceDecl *ID =
1911 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001912 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001913 if (const ObjCCategoryDecl *CD =
1914 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001915 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001916 if (const ObjCImplDecl *IMD =
1917 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001918 return IMD->getClassInterface();
1919
1920 return 0;
1921}
1922
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001923/// \brief Get the copy initialization expression of VarDecl,or NULL if
1924/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001925Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001926 assert(VD && "Passed null params");
1927 assert(VD->hasAttr<BlocksAttr>() &&
1928 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001929 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001930 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001931 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1932}
1933
1934/// \brief Set the copy inialization expression of a block var decl.
1935void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1936 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001937 assert(VD->hasAttr<BlocksAttr>() &&
1938 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001939 BlockVarCopyInits[VD] = Init;
1940}
1941
John McCallbcd03502009-12-07 02:54:59 +00001942TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001943 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001944 if (!DataSize)
1945 DataSize = TypeLoc::getFullDataSizeForType(T);
1946 else
1947 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001948 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001949
John McCallbcd03502009-12-07 02:54:59 +00001950 TypeSourceInfo *TInfo =
1951 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1952 new (TInfo) TypeSourceInfo(T);
1953 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001954}
1955
John McCallbcd03502009-12-07 02:54:59 +00001956TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001957 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001958 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001959 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001960 return DI;
1961}
1962
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001963const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001964ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001965 return getObjCLayout(D, 0);
1966}
1967
1968const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001969ASTContext::getASTObjCImplementationLayout(
1970 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001971 return getObjCLayout(D->getClassInterface(), D);
1972}
1973
Chris Lattner983a8bb2007-07-13 22:13:22 +00001974//===----------------------------------------------------------------------===//
1975// Type creation/memoization methods
1976//===----------------------------------------------------------------------===//
1977
Jay Foad39c79802011-01-12 09:06:06 +00001978QualType
John McCall33ddac02011-01-19 10:06:00 +00001979ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1980 unsigned fastQuals = quals.getFastQualifiers();
1981 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001982
1983 // Check if we've already instantiated this type.
1984 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001985 ExtQuals::Profile(ID, baseType, quals);
1986 void *insertPos = 0;
1987 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1988 assert(eq->getQualifiers() == quals);
1989 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001990 }
1991
John McCall33ddac02011-01-19 10:06:00 +00001992 // If the base type is not canonical, make the appropriate canonical type.
1993 QualType canon;
1994 if (!baseType->isCanonicalUnqualified()) {
1995 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001996 canonSplit.Quals.addConsistentQualifiers(quals);
1997 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001998
1999 // Re-find the insert position.
2000 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2001 }
2002
2003 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2004 ExtQualNodes.InsertNode(eq, insertPos);
2005 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002006}
2007
Jay Foad39c79802011-01-12 09:06:06 +00002008QualType
2009ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002010 QualType CanT = getCanonicalType(T);
2011 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002012 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002013
John McCall8ccfcb52009-09-24 19:53:00 +00002014 // If we are composing extended qualifiers together, merge together
2015 // into one ExtQuals node.
2016 QualifierCollector Quals;
2017 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002018
John McCall8ccfcb52009-09-24 19:53:00 +00002019 // If this type already has an address space specified, it cannot get
2020 // another one.
2021 assert(!Quals.hasAddressSpace() &&
2022 "Type cannot be in multiple addr spaces!");
2023 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002024
John McCall8ccfcb52009-09-24 19:53:00 +00002025 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002026}
2027
Chris Lattnerd60183d2009-02-18 22:53:11 +00002028QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002029 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002030 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002031 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002032 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002033
John McCall53fa7142010-12-24 02:08:15 +00002034 if (const PointerType *ptr = T->getAs<PointerType>()) {
2035 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002036 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002037 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2038 return getPointerType(ResultType);
2039 }
2040 }
Mike Stump11289f42009-09-09 15:08:12 +00002041
John McCall8ccfcb52009-09-24 19:53:00 +00002042 // If we are composing extended qualifiers together, merge together
2043 // into one ExtQuals node.
2044 QualifierCollector Quals;
2045 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002046
John McCall8ccfcb52009-09-24 19:53:00 +00002047 // If this type already has an ObjCGC specified, it cannot get
2048 // another one.
2049 assert(!Quals.hasObjCGCAttr() &&
2050 "Type cannot have multiple ObjCGCs!");
2051 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002052
John McCall8ccfcb52009-09-24 19:53:00 +00002053 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002054}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002055
John McCall4f5019e2010-12-19 02:44:49 +00002056const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2057 FunctionType::ExtInfo Info) {
2058 if (T->getExtInfo() == Info)
2059 return T;
2060
2061 QualType Result;
2062 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002063 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002064 } else {
2065 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2066 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2067 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002068 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002069 }
2070
2071 return cast<FunctionType>(Result.getTypePtr());
2072}
2073
Richard Smith2a7d4812013-05-04 07:00:32 +00002074void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2075 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002076 FD = FD->getMostRecentDecl();
2077 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002078 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2079 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002080 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002081 if (FunctionDecl *Next = FD->getPreviousDecl())
2082 FD = Next;
2083 else
2084 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002085 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002086 if (ASTMutationListener *L = getASTMutationListener())
2087 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002088}
2089
Chris Lattnerc6395932007-06-22 20:56:16 +00002090/// getComplexType - Return the uniqued reference to the type for a complex
2091/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002092QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002093 // Unique pointers, to guarantee there is only one pointer of a particular
2094 // structure.
2095 llvm::FoldingSetNodeID ID;
2096 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002097
Chris Lattnerc6395932007-06-22 20:56:16 +00002098 void *InsertPos = 0;
2099 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2100 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002101
Chris Lattnerc6395932007-06-22 20:56:16 +00002102 // If the pointee type isn't canonical, this won't be a canonical type either,
2103 // so fill in the canonical type field.
2104 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002105 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002106 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002107
Chris Lattnerc6395932007-06-22 20:56:16 +00002108 // Get the new insert position for the node we care about.
2109 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002110 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002111 }
John McCall90d1c2d2009-09-24 23:30:46 +00002112 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002113 Types.push_back(New);
2114 ComplexTypes.InsertNode(New, InsertPos);
2115 return QualType(New, 0);
2116}
2117
Chris Lattner970e54e2006-11-12 00:37:36 +00002118/// getPointerType - Return the uniqued reference to the type for a pointer to
2119/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002120QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002121 // Unique pointers, to guarantee there is only one pointer of a particular
2122 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002123 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002124 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002125
Chris Lattner67521df2007-01-27 01:29:36 +00002126 void *InsertPos = 0;
2127 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002128 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002129
Chris Lattner7ccecb92006-11-12 08:50:50 +00002130 // If the pointee type isn't canonical, this won't be a canonical type either,
2131 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002132 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002133 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002134 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002135
Bob Wilsonc8541f22013-03-15 17:12:43 +00002136 // Get the new insert position for the node we care about.
2137 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2138 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2139 }
John McCall90d1c2d2009-09-24 23:30:46 +00002140 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002141 Types.push_back(New);
2142 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002143 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002144}
2145
Reid Kleckner0503a872013-12-05 01:23:43 +00002146QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2147 llvm::FoldingSetNodeID ID;
2148 AdjustedType::Profile(ID, Orig, New);
2149 void *InsertPos = 0;
2150 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2151 if (AT)
2152 return QualType(AT, 0);
2153
2154 QualType Canonical = getCanonicalType(New);
2155
2156 // Get the new insert position for the node we care about.
2157 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2158 assert(AT == 0 && "Shouldn't be in the map!");
2159
2160 AT = new (*this, TypeAlignment)
2161 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2162 Types.push_back(AT);
2163 AdjustedTypes.InsertNode(AT, InsertPos);
2164 return QualType(AT, 0);
2165}
2166
Reid Kleckner8a365022013-06-24 17:51:48 +00002167QualType ASTContext::getDecayedType(QualType T) const {
2168 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2169
Reid Kleckner8a365022013-06-24 17:51:48 +00002170 QualType Decayed;
2171
2172 // C99 6.7.5.3p7:
2173 // A declaration of a parameter as "array of type" shall be
2174 // adjusted to "qualified pointer to type", where the type
2175 // qualifiers (if any) are those specified within the [ and ] of
2176 // the array type derivation.
2177 if (T->isArrayType())
2178 Decayed = getArrayDecayedType(T);
2179
2180 // C99 6.7.5.3p8:
2181 // A declaration of a parameter as "function returning type"
2182 // shall be adjusted to "pointer to function returning type", as
2183 // in 6.3.2.1.
2184 if (T->isFunctionType())
2185 Decayed = getPointerType(T);
2186
Reid Kleckner0503a872013-12-05 01:23:43 +00002187 llvm::FoldingSetNodeID ID;
2188 AdjustedType::Profile(ID, T, Decayed);
2189 void *InsertPos = 0;
2190 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2191 if (AT)
2192 return QualType(AT, 0);
2193
Reid Kleckner8a365022013-06-24 17:51:48 +00002194 QualType Canonical = getCanonicalType(Decayed);
2195
2196 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002197 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2198 assert(AT == 0 && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002199
Reid Kleckner0503a872013-12-05 01:23:43 +00002200 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2201 Types.push_back(AT);
2202 AdjustedTypes.InsertNode(AT, InsertPos);
2203 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002204}
2205
Mike Stump11289f42009-09-09 15:08:12 +00002206/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002207/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002208QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002209 assert(T->isFunctionType() && "block of function types only");
2210 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002211 // structure.
2212 llvm::FoldingSetNodeID ID;
2213 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002214
Steve Naroffec33ed92008-08-27 16:04:49 +00002215 void *InsertPos = 0;
2216 if (BlockPointerType *PT =
2217 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2218 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002219
2220 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002221 // type either so fill in the canonical type field.
2222 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002223 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002224 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002225
Steve Naroffec33ed92008-08-27 16:04:49 +00002226 // Get the new insert position for the node we care about.
2227 BlockPointerType *NewIP =
2228 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002229 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002230 }
John McCall90d1c2d2009-09-24 23:30:46 +00002231 BlockPointerType *New
2232 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002233 Types.push_back(New);
2234 BlockPointerTypes.InsertNode(New, InsertPos);
2235 return QualType(New, 0);
2236}
2237
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002238/// getLValueReferenceType - Return the uniqued reference to the type for an
2239/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002240QualType
2241ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002242 assert(getCanonicalType(T) != OverloadTy &&
2243 "Unresolved overloaded function type");
2244
Bill Wendling3708c182007-05-27 10:15:43 +00002245 // Unique pointers, to guarantee there is only one pointer of a particular
2246 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002247 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002248 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002249
2250 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002251 if (LValueReferenceType *RT =
2252 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002253 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002254
John McCallfc93cf92009-10-22 22:37:11 +00002255 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2256
Bill Wendling3708c182007-05-27 10:15:43 +00002257 // If the referencee type isn't canonical, this won't be a canonical type
2258 // either, so fill in the canonical type field.
2259 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002260 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2261 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2262 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002263
Bill Wendling3708c182007-05-27 10:15:43 +00002264 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002265 LValueReferenceType *NewIP =
2266 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002267 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002268 }
2269
John McCall90d1c2d2009-09-24 23:30:46 +00002270 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002271 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2272 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002273 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002274 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002275
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002276 return QualType(New, 0);
2277}
2278
2279/// getRValueReferenceType - Return the uniqued reference to the type for an
2280/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002281QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002282 // Unique pointers, to guarantee there is only one pointer of a particular
2283 // structure.
2284 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002285 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002286
2287 void *InsertPos = 0;
2288 if (RValueReferenceType *RT =
2289 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2290 return QualType(RT, 0);
2291
John McCallfc93cf92009-10-22 22:37:11 +00002292 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2293
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002294 // If the referencee type isn't canonical, this won't be a canonical type
2295 // either, so fill in the canonical type field.
2296 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002297 if (InnerRef || !T.isCanonical()) {
2298 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2299 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002300
2301 // Get the new insert position for the node we care about.
2302 RValueReferenceType *NewIP =
2303 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002304 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002305 }
2306
John McCall90d1c2d2009-09-24 23:30:46 +00002307 RValueReferenceType *New
2308 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002309 Types.push_back(New);
2310 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002311 return QualType(New, 0);
2312}
2313
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002314/// getMemberPointerType - Return the uniqued reference to the type for a
2315/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002316QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002317 // Unique pointers, to guarantee there is only one pointer of a particular
2318 // structure.
2319 llvm::FoldingSetNodeID ID;
2320 MemberPointerType::Profile(ID, T, Cls);
2321
2322 void *InsertPos = 0;
2323 if (MemberPointerType *PT =
2324 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2325 return QualType(PT, 0);
2326
2327 // If the pointee or class type isn't canonical, this won't be a canonical
2328 // type either, so fill in the canonical type field.
2329 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002330 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002331 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2332
2333 // Get the new insert position for the node we care about.
2334 MemberPointerType *NewIP =
2335 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002336 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002337 }
John McCall90d1c2d2009-09-24 23:30:46 +00002338 MemberPointerType *New
2339 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002340 Types.push_back(New);
2341 MemberPointerTypes.InsertNode(New, InsertPos);
2342 return QualType(New, 0);
2343}
2344
Mike Stump11289f42009-09-09 15:08:12 +00002345/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002346/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002347QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002348 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002349 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002350 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002351 assert((EltTy->isDependentType() ||
2352 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002353 "Constant array of VLAs is illegal!");
2354
Chris Lattnere2df3f92009-05-13 04:12:56 +00002355 // Convert the array size into a canonical width matching the pointer size for
2356 // the target.
2357 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002358 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002359 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002360
Chris Lattner23b7eb62007-06-15 23:05:46 +00002361 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002362 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002363
Chris Lattner36f8e652007-01-27 08:31:04 +00002364 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002365 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002366 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002367 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002368
John McCall33ddac02011-01-19 10:06:00 +00002369 // If the element type isn't canonical or has qualifiers, this won't
2370 // be a canonical type either, so fill in the canonical type field.
2371 QualType Canon;
2372 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2373 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002374 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002375 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002376 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002377
Chris Lattner36f8e652007-01-27 08:31:04 +00002378 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002379 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002380 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002381 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002382 }
Mike Stump11289f42009-09-09 15:08:12 +00002383
John McCall90d1c2d2009-09-24 23:30:46 +00002384 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002385 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002386 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002387 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002388 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002389}
2390
John McCall06549462011-01-18 08:40:38 +00002391/// getVariableArrayDecayedType - Turns the given type, which may be
2392/// variably-modified, into the corresponding type with all the known
2393/// sizes replaced with [*].
2394QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2395 // Vastly most common case.
2396 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002397
John McCall06549462011-01-18 08:40:38 +00002398 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002399
John McCall06549462011-01-18 08:40:38 +00002400 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002401 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002402 switch (ty->getTypeClass()) {
2403#define TYPE(Class, Base)
2404#define ABSTRACT_TYPE(Class, Base)
2405#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2406#include "clang/AST/TypeNodes.def"
2407 llvm_unreachable("didn't desugar past all non-canonical types?");
2408
2409 // These types should never be variably-modified.
2410 case Type::Builtin:
2411 case Type::Complex:
2412 case Type::Vector:
2413 case Type::ExtVector:
2414 case Type::DependentSizedExtVector:
2415 case Type::ObjCObject:
2416 case Type::ObjCInterface:
2417 case Type::ObjCObjectPointer:
2418 case Type::Record:
2419 case Type::Enum:
2420 case Type::UnresolvedUsing:
2421 case Type::TypeOfExpr:
2422 case Type::TypeOf:
2423 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002424 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002425 case Type::DependentName:
2426 case Type::InjectedClassName:
2427 case Type::TemplateSpecialization:
2428 case Type::DependentTemplateSpecialization:
2429 case Type::TemplateTypeParm:
2430 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002431 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002432 case Type::PackExpansion:
2433 llvm_unreachable("type should never be variably-modified");
2434
2435 // These types can be variably-modified but should never need to
2436 // further decay.
2437 case Type::FunctionNoProto:
2438 case Type::FunctionProto:
2439 case Type::BlockPointer:
2440 case Type::MemberPointer:
2441 return type;
2442
2443 // These types can be variably-modified. All these modifications
2444 // preserve structure except as noted by comments.
2445 // TODO: if we ever care about optimizing VLAs, there are no-op
2446 // optimizations available here.
2447 case Type::Pointer:
2448 result = getPointerType(getVariableArrayDecayedType(
2449 cast<PointerType>(ty)->getPointeeType()));
2450 break;
2451
2452 case Type::LValueReference: {
2453 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2454 result = getLValueReferenceType(
2455 getVariableArrayDecayedType(lv->getPointeeType()),
2456 lv->isSpelledAsLValue());
2457 break;
2458 }
2459
2460 case Type::RValueReference: {
2461 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2462 result = getRValueReferenceType(
2463 getVariableArrayDecayedType(lv->getPointeeType()));
2464 break;
2465 }
2466
Eli Friedman0dfb8892011-10-06 23:00:33 +00002467 case Type::Atomic: {
2468 const AtomicType *at = cast<AtomicType>(ty);
2469 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2470 break;
2471 }
2472
John McCall06549462011-01-18 08:40:38 +00002473 case Type::ConstantArray: {
2474 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2475 result = getConstantArrayType(
2476 getVariableArrayDecayedType(cat->getElementType()),
2477 cat->getSize(),
2478 cat->getSizeModifier(),
2479 cat->getIndexTypeCVRQualifiers());
2480 break;
2481 }
2482
2483 case Type::DependentSizedArray: {
2484 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2485 result = getDependentSizedArrayType(
2486 getVariableArrayDecayedType(dat->getElementType()),
2487 dat->getSizeExpr(),
2488 dat->getSizeModifier(),
2489 dat->getIndexTypeCVRQualifiers(),
2490 dat->getBracketsRange());
2491 break;
2492 }
2493
2494 // Turn incomplete types into [*] types.
2495 case Type::IncompleteArray: {
2496 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2497 result = getVariableArrayType(
2498 getVariableArrayDecayedType(iat->getElementType()),
2499 /*size*/ 0,
2500 ArrayType::Normal,
2501 iat->getIndexTypeCVRQualifiers(),
2502 SourceRange());
2503 break;
2504 }
2505
2506 // Turn VLA types into [*] types.
2507 case Type::VariableArray: {
2508 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2509 result = getVariableArrayType(
2510 getVariableArrayDecayedType(vat->getElementType()),
2511 /*size*/ 0,
2512 ArrayType::Star,
2513 vat->getIndexTypeCVRQualifiers(),
2514 vat->getBracketsRange());
2515 break;
2516 }
2517 }
2518
2519 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002520 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002521}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002522
Steve Naroffcadebd02007-08-30 18:14:25 +00002523/// getVariableArrayType - Returns a non-unique reference to the type for a
2524/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002525QualType ASTContext::getVariableArrayType(QualType EltTy,
2526 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002527 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002528 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002529 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002530 // Since we don't unique expressions, it isn't possible to unique VLA's
2531 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002532 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002533
John McCall33ddac02011-01-19 10:06:00 +00002534 // Be sure to pull qualifiers off the element type.
2535 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2536 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002537 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002538 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002539 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002540 }
2541
John McCall90d1c2d2009-09-24 23:30:46 +00002542 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002543 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002544
2545 VariableArrayTypes.push_back(New);
2546 Types.push_back(New);
2547 return QualType(New, 0);
2548}
2549
Douglas Gregor4619e432008-12-05 23:32:09 +00002550/// getDependentSizedArrayType - Returns a non-unique reference to
2551/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002552/// type.
John McCall33ddac02011-01-19 10:06:00 +00002553QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2554 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002555 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002556 unsigned elementTypeQuals,
2557 SourceRange brackets) const {
2558 assert((!numElements || numElements->isTypeDependent() ||
2559 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002560 "Size must be type- or value-dependent!");
2561
John McCall33ddac02011-01-19 10:06:00 +00002562 // Dependently-sized array types that do not have a specified number
2563 // of elements will have their sizes deduced from a dependent
2564 // initializer. We do no canonicalization here at all, which is okay
2565 // because they can't be used in most locations.
2566 if (!numElements) {
2567 DependentSizedArrayType *newType
2568 = new (*this, TypeAlignment)
2569 DependentSizedArrayType(*this, elementType, QualType(),
2570 numElements, ASM, elementTypeQuals,
2571 brackets);
2572 Types.push_back(newType);
2573 return QualType(newType, 0);
2574 }
2575
2576 // Otherwise, we actually build a new type every time, but we
2577 // also build a canonical type.
2578
2579 SplitQualType canonElementType = getCanonicalType(elementType).split();
2580
2581 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002582 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002583 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002584 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002585 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002586
John McCall33ddac02011-01-19 10:06:00 +00002587 // Look for an existing type with these properties.
2588 DependentSizedArrayType *canonTy =
2589 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002590
John McCall33ddac02011-01-19 10:06:00 +00002591 // If we don't have one, build one.
2592 if (!canonTy) {
2593 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002594 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002595 QualType(), numElements, ASM, elementTypeQuals,
2596 brackets);
2597 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2598 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002599 }
2600
John McCall33ddac02011-01-19 10:06:00 +00002601 // Apply qualifiers from the element type to the array.
2602 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002603 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002604
John McCall33ddac02011-01-19 10:06:00 +00002605 // If we didn't need extra canonicalization for the element type,
2606 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002607 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002608 return canon;
2609
2610 // Otherwise, we need to build a type which follows the spelling
2611 // of the element type.
2612 DependentSizedArrayType *sugaredType
2613 = new (*this, TypeAlignment)
2614 DependentSizedArrayType(*this, elementType, canon, numElements,
2615 ASM, elementTypeQuals, brackets);
2616 Types.push_back(sugaredType);
2617 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002618}
2619
John McCall33ddac02011-01-19 10:06:00 +00002620QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002621 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002622 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002623 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002624 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002625
John McCall33ddac02011-01-19 10:06:00 +00002626 void *insertPos = 0;
2627 if (IncompleteArrayType *iat =
2628 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2629 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002630
2631 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002632 // either, so fill in the canonical type field. We also have to pull
2633 // qualifiers off the element type.
2634 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002635
John McCall33ddac02011-01-19 10:06:00 +00002636 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2637 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002638 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002639 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002640 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002641
2642 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002643 IncompleteArrayType *existing =
2644 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2645 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002646 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002647
John McCall33ddac02011-01-19 10:06:00 +00002648 IncompleteArrayType *newType = new (*this, TypeAlignment)
2649 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002650
John McCall33ddac02011-01-19 10:06:00 +00002651 IncompleteArrayTypes.InsertNode(newType, insertPos);
2652 Types.push_back(newType);
2653 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002654}
2655
Steve Naroff91fcddb2007-07-18 18:00:27 +00002656/// getVectorType - Return the unique reference to a vector type of
2657/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002658QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002659 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002660 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002661
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002662 // Check if we've already instantiated a vector of this type.
2663 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002664 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002665
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002666 void *InsertPos = 0;
2667 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2668 return QualType(VTP, 0);
2669
2670 // If the element type isn't canonical, this won't be a canonical type either,
2671 // so fill in the canonical type field.
2672 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002673 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002674 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002675
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002676 // Get the new insert position for the node we care about.
2677 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002678 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002679 }
John McCall90d1c2d2009-09-24 23:30:46 +00002680 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002681 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002682 VectorTypes.InsertNode(New, InsertPos);
2683 Types.push_back(New);
2684 return QualType(New, 0);
2685}
2686
Nate Begemance4d7fc2008-04-18 23:10:10 +00002687/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002688/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002689QualType
2690ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002691 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002692
Steve Naroff91fcddb2007-07-18 18:00:27 +00002693 // Check if we've already instantiated a vector of this type.
2694 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002695 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002696 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002697 void *InsertPos = 0;
2698 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2699 return QualType(VTP, 0);
2700
2701 // If the element type isn't canonical, this won't be a canonical type either,
2702 // so fill in the canonical type field.
2703 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002704 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002705 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002706
Steve Naroff91fcddb2007-07-18 18:00:27 +00002707 // Get the new insert position for the node we care about.
2708 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002709 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002710 }
John McCall90d1c2d2009-09-24 23:30:46 +00002711 ExtVectorType *New = new (*this, TypeAlignment)
2712 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002713 VectorTypes.InsertNode(New, InsertPos);
2714 Types.push_back(New);
2715 return QualType(New, 0);
2716}
2717
Jay Foad39c79802011-01-12 09:06:06 +00002718QualType
2719ASTContext::getDependentSizedExtVectorType(QualType vecType,
2720 Expr *SizeExpr,
2721 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002722 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002723 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002724 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002725
Douglas Gregor352169a2009-07-31 03:54:25 +00002726 void *InsertPos = 0;
2727 DependentSizedExtVectorType *Canon
2728 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2729 DependentSizedExtVectorType *New;
2730 if (Canon) {
2731 // We already have a canonical version of this array type; use it as
2732 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002733 New = new (*this, TypeAlignment)
2734 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2735 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002736 } else {
2737 QualType CanonVecTy = getCanonicalType(vecType);
2738 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002739 New = new (*this, TypeAlignment)
2740 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2741 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002742
2743 DependentSizedExtVectorType *CanonCheck
2744 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2745 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2746 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002747 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2748 } else {
2749 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2750 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002751 New = new (*this, TypeAlignment)
2752 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002753 }
2754 }
Mike Stump11289f42009-09-09 15:08:12 +00002755
Douglas Gregor758a8692009-06-17 21:51:59 +00002756 Types.push_back(New);
2757 return QualType(New, 0);
2758}
2759
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002760/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002761///
Jay Foad39c79802011-01-12 09:06:06 +00002762QualType
2763ASTContext::getFunctionNoProtoType(QualType ResultTy,
2764 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002765 const CallingConv CallConv = Info.getCC();
2766
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002767 // Unique functions, to guarantee there is only one function of a particular
2768 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002769 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002770 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002771
Chris Lattner47955de2007-01-27 08:37:20 +00002772 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002773 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002774 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002775 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002776
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002777 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002778 if (!ResultTy.isCanonical()) {
2779 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002780
Chris Lattner47955de2007-01-27 08:37:20 +00002781 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002782 FunctionNoProtoType *NewIP =
2783 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002784 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002785 }
Mike Stump11289f42009-09-09 15:08:12 +00002786
Roman Divacky65b88cd2011-03-01 17:40:53 +00002787 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002788 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002789 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002790 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002791 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002792 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002793}
2794
Douglas Gregorcd780372013-01-17 23:36:45 +00002795/// \brief Determine whether \p T is canonical as the result type of a function.
2796static bool isCanonicalResultType(QualType T) {
2797 return T.isCanonical() &&
2798 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2799 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2800}
2801
Jay Foad39c79802011-01-12 09:06:06 +00002802QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002803ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002804 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002805 size_t NumArgs = ArgArray.size();
2806
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002807 // Unique functions, to guarantee there is only one function of a particular
2808 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002809 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002810 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2811 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002812
2813 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002814 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002815 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002816 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002817
2818 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002819 bool isCanonical =
Douglas Gregorcd780372013-01-17 23:36:45 +00002820 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002821 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002822 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002823 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002824 isCanonical = false;
2825
2826 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002827 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002828 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002829 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002830 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002831 CanonicalArgs.reserve(NumArgs);
2832 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002833 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002834
John McCalldb40c7f2010-12-14 08:05:40 +00002835 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002836 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002837 CanonicalEPI.ExceptionSpecType = EST_None;
2838 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002839
Douglas Gregorcd780372013-01-17 23:36:45 +00002840 // Result types do not have ARC lifetime qualifiers.
2841 QualType CanResultTy = getCanonicalType(ResultTy);
2842 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2843 Qualifiers Qs = CanResultTy.getQualifiers();
2844 Qs.removeObjCLifetime();
2845 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2846 }
2847
Jordan Rose5c382722013-03-08 21:51:21 +00002848 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002849
Chris Lattnerfd4de792007-01-27 01:15:32 +00002850 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002851 FunctionProtoType *NewIP =
2852 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002853 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002854 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002855
John McCall31168b02011-06-15 23:02:42 +00002856 // FunctionProtoType objects are allocated with extra bytes after
2857 // them for three variable size arrays at the end:
2858 // - parameter types
2859 // - exception types
2860 // - consumed-arguments flags
2861 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002862 // expression, or information used to resolve the exception
2863 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002864 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002865 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002866 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002867 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002868 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002869 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002870 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002871 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002872 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2873 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002874 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002875 if (EPI.ConsumedParameters)
John McCall31168b02011-06-15 23:02:42 +00002876 Size += NumArgs * sizeof(bool);
2877
John McCalldb40c7f2010-12-14 08:05:40 +00002878 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002879 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00002880 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002881 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002882 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002883 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002884}
Chris Lattneref51c202006-11-10 07:17:23 +00002885
John McCalle78aac42010-03-10 03:28:59 +00002886#ifndef NDEBUG
2887static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2888 if (!isa<CXXRecordDecl>(D)) return false;
2889 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2890 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2891 return true;
2892 if (RD->getDescribedClassTemplate() &&
2893 !isa<ClassTemplateSpecializationDecl>(RD))
2894 return true;
2895 return false;
2896}
2897#endif
2898
2899/// getInjectedClassNameType - Return the unique reference to the
2900/// injected class name type for the specified templated declaration.
2901QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002902 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002903 assert(NeedsInjectedClassNameType(Decl));
2904 if (Decl->TypeForDecl) {
2905 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002906 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002907 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2908 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2909 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2910 } else {
John McCall424cec92011-01-19 06:33:43 +00002911 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002912 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002913 Decl->TypeForDecl = newType;
2914 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002915 }
2916 return QualType(Decl->TypeForDecl, 0);
2917}
2918
Douglas Gregor83a586e2008-04-13 21:07:44 +00002919/// getTypeDeclType - Return the unique reference to the type for the
2920/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002921QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002922 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002923 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002924
Richard Smithdda56e42011-04-15 14:24:37 +00002925 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002926 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002927
John McCall96f0b5f2010-03-10 06:48:02 +00002928 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2929 "Template type parameter types are always available.");
2930
John McCall81e38502010-02-16 03:57:14 +00002931 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00002932 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00002933 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002934 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002935 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00002936 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002937 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002938 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002939 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002940 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2941 Decl->TypeForDecl = newType;
2942 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002943 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002944 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002945
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002946 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002947}
2948
Chris Lattner32d920b2007-01-26 02:01:53 +00002949/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002950/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002951QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002952ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2953 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002954 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002955
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002956 if (Canonical.isNull())
2957 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002958 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002959 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002960 Decl->TypeForDecl = newType;
2961 Types.push_back(newType);
2962 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002963}
2964
Jay Foad39c79802011-01-12 09:06:06 +00002965QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002966 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2967
Douglas Gregorec9fd132012-01-14 16:38:05 +00002968 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002969 if (PrevDecl->TypeForDecl)
2970 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2971
John McCall424cec92011-01-19 06:33:43 +00002972 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2973 Decl->TypeForDecl = newType;
2974 Types.push_back(newType);
2975 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002976}
2977
Jay Foad39c79802011-01-12 09:06:06 +00002978QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002979 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2980
Douglas Gregorec9fd132012-01-14 16:38:05 +00002981 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002982 if (PrevDecl->TypeForDecl)
2983 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2984
John McCall424cec92011-01-19 06:33:43 +00002985 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2986 Decl->TypeForDecl = newType;
2987 Types.push_back(newType);
2988 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002989}
2990
John McCall81904512011-01-06 01:58:22 +00002991QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2992 QualType modifiedType,
2993 QualType equivalentType) {
2994 llvm::FoldingSetNodeID id;
2995 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2996
2997 void *insertPos = 0;
2998 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2999 if (type) return QualType(type, 0);
3000
3001 QualType canon = getCanonicalType(equivalentType);
3002 type = new (*this, TypeAlignment)
3003 AttributedType(canon, attrKind, modifiedType, equivalentType);
3004
3005 Types.push_back(type);
3006 AttributedTypes.InsertNode(type, insertPos);
3007
3008 return QualType(type, 0);
3009}
3010
3011
John McCallcebee162009-10-18 09:09:24 +00003012/// \brief Retrieve a substitution-result type.
3013QualType
3014ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003015 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003016 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003017 && "replacement types must always be canonical");
3018
3019 llvm::FoldingSetNodeID ID;
3020 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3021 void *InsertPos = 0;
3022 SubstTemplateTypeParmType *SubstParm
3023 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3024
3025 if (!SubstParm) {
3026 SubstParm = new (*this, TypeAlignment)
3027 SubstTemplateTypeParmType(Parm, Replacement);
3028 Types.push_back(SubstParm);
3029 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3030 }
3031
3032 return QualType(SubstParm, 0);
3033}
3034
Douglas Gregorada4b792011-01-14 02:55:32 +00003035/// \brief Retrieve a
3036QualType ASTContext::getSubstTemplateTypeParmPackType(
3037 const TemplateTypeParmType *Parm,
3038 const TemplateArgument &ArgPack) {
3039#ifndef NDEBUG
3040 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
3041 PEnd = ArgPack.pack_end();
3042 P != PEnd; ++P) {
3043 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3044 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
3045 }
3046#endif
3047
3048 llvm::FoldingSetNodeID ID;
3049 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3050 void *InsertPos = 0;
3051 if (SubstTemplateTypeParmPackType *SubstParm
3052 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3053 return QualType(SubstParm, 0);
3054
3055 QualType Canon;
3056 if (!Parm->isCanonicalUnqualified()) {
3057 Canon = getCanonicalType(QualType(Parm, 0));
3058 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3059 ArgPack);
3060 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3061 }
3062
3063 SubstTemplateTypeParmPackType *SubstParm
3064 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3065 ArgPack);
3066 Types.push_back(SubstParm);
3067 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3068 return QualType(SubstParm, 0);
3069}
3070
Douglas Gregoreff93e02009-02-05 23:33:38 +00003071/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003072/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003073/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003074QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003075 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003076 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003077 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003078 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003079 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003080 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003081 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3082
3083 if (TypeParm)
3084 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003085
Chandler Carruth08836322011-05-01 00:51:33 +00003086 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003087 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003088 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003089
3090 TemplateTypeParmType *TypeCheck
3091 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3092 assert(!TypeCheck && "Template type parameter canonical type broken");
3093 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003094 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003095 TypeParm = new (*this, TypeAlignment)
3096 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003097
3098 Types.push_back(TypeParm);
3099 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3100
3101 return QualType(TypeParm, 0);
3102}
3103
John McCalle78aac42010-03-10 03:28:59 +00003104TypeSourceInfo *
3105ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3106 SourceLocation NameLoc,
3107 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003108 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003109 assert(!Name.getAsDependentTemplateName() &&
3110 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003111 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003112
3113 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003114 TemplateSpecializationTypeLoc TL =
3115 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003116 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003117 TL.setTemplateNameLoc(NameLoc);
3118 TL.setLAngleLoc(Args.getLAngleLoc());
3119 TL.setRAngleLoc(Args.getRAngleLoc());
3120 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3121 TL.setArgLocInfo(i, Args[i].getLocInfo());
3122 return DI;
3123}
3124
Mike Stump11289f42009-09-09 15:08:12 +00003125QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003126ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003127 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003128 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003129 assert(!Template.getAsDependentTemplateName() &&
3130 "No dependent template names here!");
3131
John McCall6b51f282009-11-23 01:53:49 +00003132 unsigned NumArgs = Args.size();
3133
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003134 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003135 ArgVec.reserve(NumArgs);
3136 for (unsigned i = 0; i != NumArgs; ++i)
3137 ArgVec.push_back(Args[i].getArgument());
3138
John McCall2408e322010-04-27 00:57:59 +00003139 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003140 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003141}
3142
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003143#ifndef NDEBUG
3144static bool hasAnyPackExpansions(const TemplateArgument *Args,
3145 unsigned NumArgs) {
3146 for (unsigned I = 0; I != NumArgs; ++I)
3147 if (Args[I].isPackExpansion())
3148 return true;
3149
3150 return true;
3151}
3152#endif
3153
John McCall0ad16662009-10-29 08:12:44 +00003154QualType
3155ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003156 const TemplateArgument *Args,
3157 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003158 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003159 assert(!Template.getAsDependentTemplateName() &&
3160 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003161 // Look through qualified template names.
3162 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3163 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003164
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003165 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003166 Template.getAsTemplateDecl() &&
3167 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003168 QualType CanonType;
3169 if (!Underlying.isNull())
3170 CanonType = getCanonicalType(Underlying);
3171 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003172 // We can get here with an alias template when the specialization contains
3173 // a pack expansion that does not match up with a parameter pack.
3174 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3175 "Caller must compute aliased type");
3176 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003177 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3178 NumArgs);
3179 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003180
Douglas Gregora8e02e72009-07-28 23:00:59 +00003181 // Allocate the (non-canonical) template specialization type, but don't
3182 // try to unique it: these types typically have location information that
3183 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003184 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3185 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003186 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003187 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003188 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003189 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3190 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003191
Douglas Gregor8bf42052009-02-09 18:46:07 +00003192 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003193 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003194}
3195
Mike Stump11289f42009-09-09 15:08:12 +00003196QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003197ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3198 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003199 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003200 assert(!Template.getAsDependentTemplateName() &&
3201 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003202
Douglas Gregore29139c2011-03-03 17:04:51 +00003203 // Look through qualified template names.
3204 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3205 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003206
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003207 // Build the canonical template specialization type.
3208 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003209 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003210 CanonArgs.reserve(NumArgs);
3211 for (unsigned I = 0; I != NumArgs; ++I)
3212 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3213
3214 // Determine whether this canonical template specialization type already
3215 // exists.
3216 llvm::FoldingSetNodeID ID;
3217 TemplateSpecializationType::Profile(ID, CanonTemplate,
3218 CanonArgs.data(), NumArgs, *this);
3219
3220 void *InsertPos = 0;
3221 TemplateSpecializationType *Spec
3222 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3223
3224 if (!Spec) {
3225 // Allocate a new canonical template specialization type.
3226 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3227 sizeof(TemplateArgument) * NumArgs),
3228 TypeAlignment);
3229 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3230 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003231 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003232 Types.push_back(Spec);
3233 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3234 }
3235
3236 assert(Spec->isDependentType() &&
3237 "Non-dependent template-id type must have a canonical type");
3238 return QualType(Spec, 0);
3239}
3240
3241QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003242ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3243 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003244 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003245 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003246 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003247
3248 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003249 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003250 if (T)
3251 return QualType(T, 0);
3252
Douglas Gregorc42075a2010-02-04 18:10:26 +00003253 QualType Canon = NamedType;
3254 if (!Canon.isCanonical()) {
3255 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003256 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3257 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003258 (void)CheckT;
3259 }
3260
Abramo Bagnara6150c882010-05-11 21:36:43 +00003261 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003262 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003263 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003264 return QualType(T, 0);
3265}
3266
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003267QualType
Jay Foad39c79802011-01-12 09:06:06 +00003268ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003269 llvm::FoldingSetNodeID ID;
3270 ParenType::Profile(ID, InnerType);
3271
3272 void *InsertPos = 0;
3273 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3274 if (T)
3275 return QualType(T, 0);
3276
3277 QualType Canon = InnerType;
3278 if (!Canon.isCanonical()) {
3279 Canon = getCanonicalType(InnerType);
3280 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3281 assert(!CheckT && "Paren canonical type broken");
3282 (void)CheckT;
3283 }
3284
3285 T = new (*this) ParenType(InnerType, Canon);
3286 Types.push_back(T);
3287 ParenTypes.InsertNode(T, InsertPos);
3288 return QualType(T, 0);
3289}
3290
Douglas Gregor02085352010-03-31 20:19:30 +00003291QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3292 NestedNameSpecifier *NNS,
3293 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003294 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003295 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3296
3297 if (Canon.isNull()) {
3298 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003299 ElaboratedTypeKeyword CanonKeyword = Keyword;
3300 if (Keyword == ETK_None)
3301 CanonKeyword = ETK_Typename;
3302
3303 if (CanonNNS != NNS || CanonKeyword != Keyword)
3304 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003305 }
3306
3307 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003308 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003309
3310 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003311 DependentNameType *T
3312 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003313 if (T)
3314 return QualType(T, 0);
3315
Douglas Gregor02085352010-03-31 20:19:30 +00003316 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003317 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003318 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003319 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003320}
3321
Mike Stump11289f42009-09-09 15:08:12 +00003322QualType
John McCallc392f372010-06-11 00:33:02 +00003323ASTContext::getDependentTemplateSpecializationType(
3324 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003325 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003326 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003327 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003328 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003329 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003330 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3331 ArgCopy.push_back(Args[I].getArgument());
3332 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3333 ArgCopy.size(),
3334 ArgCopy.data());
3335}
3336
3337QualType
3338ASTContext::getDependentTemplateSpecializationType(
3339 ElaboratedTypeKeyword Keyword,
3340 NestedNameSpecifier *NNS,
3341 const IdentifierInfo *Name,
3342 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003343 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003344 assert((!NNS || NNS->isDependent()) &&
3345 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003346
Douglas Gregorc42075a2010-02-04 18:10:26 +00003347 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003348 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3349 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003350
3351 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00003352 DependentTemplateSpecializationType *T
3353 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003354 if (T)
3355 return QualType(T, 0);
3356
John McCallc392f372010-06-11 00:33:02 +00003357 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003358
John McCallc392f372010-06-11 00:33:02 +00003359 ElaboratedTypeKeyword CanonKeyword = Keyword;
3360 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3361
3362 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003363 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003364 for (unsigned I = 0; I != NumArgs; ++I) {
3365 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3366 if (!CanonArgs[I].structurallyEquals(Args[I]))
3367 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003368 }
3369
John McCallc392f372010-06-11 00:33:02 +00003370 QualType Canon;
3371 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3372 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3373 Name, NumArgs,
3374 CanonArgs.data());
3375
3376 // Find the insert position again.
3377 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3378 }
3379
3380 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3381 sizeof(TemplateArgument) * NumArgs),
3382 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003383 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003384 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003385 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003386 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003387 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003388}
3389
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003390QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003391 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003392 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003393 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003394
3395 assert(Pattern->containsUnexpandedParameterPack() &&
3396 "Pack expansions must expand one or more parameter packs");
3397 void *InsertPos = 0;
3398 PackExpansionType *T
3399 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3400 if (T)
3401 return QualType(T, 0);
3402
3403 QualType Canon;
3404 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003405 Canon = getCanonicalType(Pattern);
3406 // The canonical type might not contain an unexpanded parameter pack, if it
3407 // contains an alias template specialization which ignores one of its
3408 // parameters.
3409 if (Canon->containsUnexpandedParameterPack()) {
3410 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003411
Richard Smith68eea502012-07-16 00:20:35 +00003412 // Find the insert position again, in case we inserted an element into
3413 // PackExpansionTypes and invalidated our insert position.
3414 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3415 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003416 }
3417
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003418 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003419 Types.push_back(T);
3420 PackExpansionTypes.InsertNode(T, InsertPos);
3421 return QualType(T, 0);
3422}
3423
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003424/// CmpProtocolNames - Comparison predicate for sorting protocols
3425/// alphabetically.
3426static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3427 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003428 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003429}
3430
John McCall8b07ec22010-05-15 11:32:37 +00003431static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003432 unsigned NumProtocols) {
3433 if (NumProtocols == 0) return true;
3434
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003435 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3436 return false;
3437
John McCallfc93cf92009-10-22 22:37:11 +00003438 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003439 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3440 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003441 return false;
3442 return true;
3443}
3444
3445static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003446 unsigned &NumProtocols) {
3447 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003448
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003449 // Sort protocols, keyed by name.
3450 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3451
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003452 // Canonicalize.
3453 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3454 Protocols[I] = Protocols[I]->getCanonicalDecl();
3455
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003456 // Remove duplicates.
3457 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3458 NumProtocols = ProtocolsEnd-Protocols;
3459}
3460
John McCall8b07ec22010-05-15 11:32:37 +00003461QualType ASTContext::getObjCObjectType(QualType BaseType,
3462 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003463 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003464 // If the base type is an interface and there aren't any protocols
3465 // to add, then the interface type will do just fine.
3466 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3467 return BaseType;
3468
3469 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003470 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003471 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003472 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003473 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3474 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003475
John McCall8b07ec22010-05-15 11:32:37 +00003476 // Build the canonical type, which has the canonical base type and
3477 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003478 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003479 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3480 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3481 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003482 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003483 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003484 unsigned UniqueCount = NumProtocols;
3485
John McCallfc93cf92009-10-22 22:37:11 +00003486 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003487 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3488 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003489 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003490 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3491 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003492 }
3493
3494 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003495 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3496 }
3497
3498 unsigned Size = sizeof(ObjCObjectTypeImpl);
3499 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3500 void *Mem = Allocate(Size, TypeAlignment);
3501 ObjCObjectTypeImpl *T =
3502 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3503
3504 Types.push_back(T);
3505 ObjCObjectTypes.InsertNode(T, InsertPos);
3506 return QualType(T, 0);
3507}
3508
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003509/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3510/// protocol list adopt all protocols in QT's qualified-id protocol
3511/// list.
3512bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3513 ObjCInterfaceDecl *IC) {
3514 if (!QT->isObjCQualifiedIdType())
3515 return false;
3516
3517 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3518 // If both the right and left sides have qualifiers.
3519 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3520 E = OPT->qual_end(); I != E; ++I) {
3521 ObjCProtocolDecl *Proto = *I;
3522 if (!IC->ClassImplementsProtocol(Proto, false))
3523 return false;
3524 }
3525 return true;
3526 }
3527 return false;
3528}
3529
3530/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3531/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3532/// of protocols.
3533bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3534 ObjCInterfaceDecl *IDecl) {
3535 if (!QT->isObjCQualifiedIdType())
3536 return false;
3537 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3538 if (!OPT)
3539 return false;
3540 if (!IDecl->hasDefinition())
3541 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003542 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3543 CollectInheritedProtocols(IDecl, InheritedProtocols);
3544 if (InheritedProtocols.empty())
3545 return false;
3546
3547 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator PI =
3548 InheritedProtocols.begin(),
3549 E = InheritedProtocols.end(); PI != E; ++PI) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003550 // If both the right and left sides have qualifiers.
3551 bool Adopts = false;
3552 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3553 E = OPT->qual_end(); I != E; ++I) {
3554 ObjCProtocolDecl *Proto = *I;
3555 // return 'true' if '*PI' is in the inheritance hierarchy of Proto
3556 if ((Adopts = ProtocolCompatibleWithProtocol(*PI, Proto)))
3557 break;
3558 }
3559 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003560 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003561 }
3562 return true;
3563}
3564
John McCall8b07ec22010-05-15 11:32:37 +00003565/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3566/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003567QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003568 llvm::FoldingSetNodeID ID;
3569 ObjCObjectPointerType::Profile(ID, ObjectT);
3570
3571 void *InsertPos = 0;
3572 if (ObjCObjectPointerType *QT =
3573 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3574 return QualType(QT, 0);
3575
3576 // Find the canonical object type.
3577 QualType Canonical;
3578 if (!ObjectT.isCanonical()) {
3579 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3580
3581 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003582 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3583 }
3584
Douglas Gregorf85bee62010-02-08 22:59:26 +00003585 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003586 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3587 ObjCObjectPointerType *QType =
3588 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003589
Steve Narofffb4330f2009-06-17 22:40:22 +00003590 Types.push_back(QType);
3591 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003592 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003593}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003594
Douglas Gregor1c283312010-08-11 12:19:30 +00003595/// getObjCInterfaceType - Return the unique reference to the type for the
3596/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003597QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3598 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003599 if (Decl->TypeForDecl)
3600 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003601
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003602 if (PrevDecl) {
3603 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3604 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3605 return QualType(PrevDecl->TypeForDecl, 0);
3606 }
3607
Douglas Gregor7671e532011-12-16 16:34:57 +00003608 // Prefer the definition, if there is one.
3609 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3610 Decl = Def;
3611
Douglas Gregor1c283312010-08-11 12:19:30 +00003612 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3613 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3614 Decl->TypeForDecl = T;
3615 Types.push_back(T);
3616 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003617}
3618
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003619/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3620/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003621/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003622/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003623/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003624QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003625 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003626 if (tofExpr->isTypeDependent()) {
3627 llvm::FoldingSetNodeID ID;
3628 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003629
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003630 void *InsertPos = 0;
3631 DependentTypeOfExprType *Canon
3632 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3633 if (Canon) {
3634 // We already have a "canonical" version of an identical, dependent
3635 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003636 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003637 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003638 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003639 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003640 Canon
3641 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003642 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3643 toe = Canon;
3644 }
3645 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003646 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003647 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003648 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003649 Types.push_back(toe);
3650 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003651}
3652
Steve Naroffa773cd52007-08-01 18:02:17 +00003653/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3654/// TypeOfType AST's. The only motivation to unique these nodes would be
3655/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003656/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003657/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003658QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003659 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003660 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003661 Types.push_back(tot);
3662 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003663}
3664
Anders Carlssonad6bd352009-06-24 21:24:56 +00003665
Anders Carlsson81df7b82009-06-24 19:06:50 +00003666/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3667/// DecltypeType AST's. The only motivation to unique these nodes would be
3668/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003669/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003670/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003671QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003672 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003673
3674 // C++0x [temp.type]p2:
3675 // If an expression e involves a template parameter, decltype(e) denotes a
3676 // unique dependent type. Two such decltype-specifiers refer to the same
3677 // type only if their expressions are equivalent (14.5.6.1).
3678 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003679 llvm::FoldingSetNodeID ID;
3680 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003681
Douglas Gregora21f6c32009-07-30 23:36:40 +00003682 void *InsertPos = 0;
3683 DependentDecltypeType *Canon
3684 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3685 if (Canon) {
3686 // We already have a "canonical" version of an equivalent, dependent
3687 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003688 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003689 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003690 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003691 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003692 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003693 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3694 dt = Canon;
3695 }
3696 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003697 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3698 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003699 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003700 Types.push_back(dt);
3701 return QualType(dt, 0);
3702}
3703
Alexis Hunte852b102011-05-24 22:41:36 +00003704/// getUnaryTransformationType - We don't unique these, since the memory
3705/// savings are minimal and these are rare.
3706QualType ASTContext::getUnaryTransformType(QualType BaseType,
3707 QualType UnderlyingType,
3708 UnaryTransformType::UTTKind Kind)
3709 const {
3710 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003711 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3712 Kind,
3713 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003714 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003715 Types.push_back(Ty);
3716 return QualType(Ty, 0);
3717}
3718
Richard Smith2a7d4812013-05-04 07:00:32 +00003719/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3720/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3721/// canonical deduced-but-dependent 'auto' type.
3722QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003723 bool IsDependent) const {
3724 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003725 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003726
Richard Smith2a7d4812013-05-04 07:00:32 +00003727 // Look in the folding set for an existing type.
Richard Smithb2bc2e62011-02-21 20:05:19 +00003728 void *InsertPos = 0;
Richard Smith2a7d4812013-05-04 07:00:32 +00003729 llvm::FoldingSetNodeID ID;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003730 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003731 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3732 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003733
Richard Smith74aeef52013-04-26 16:15:35 +00003734 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003735 IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003736 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003737 Types.push_back(AT);
3738 if (InsertPos)
3739 AutoTypes.InsertNode(AT, InsertPos);
3740 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003741}
3742
Eli Friedman0dfb8892011-10-06 23:00:33 +00003743/// getAtomicType - Return the uniqued reference to the atomic type for
3744/// the given value type.
3745QualType ASTContext::getAtomicType(QualType T) const {
3746 // Unique pointers, to guarantee there is only one pointer of a particular
3747 // structure.
3748 llvm::FoldingSetNodeID ID;
3749 AtomicType::Profile(ID, T);
3750
3751 void *InsertPos = 0;
3752 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3753 return QualType(AT, 0);
3754
3755 // If the atomic value type isn't canonical, this won't be a canonical type
3756 // either, so fill in the canonical type field.
3757 QualType Canonical;
3758 if (!T.isCanonical()) {
3759 Canonical = getAtomicType(getCanonicalType(T));
3760
3761 // Get the new insert position for the node we care about.
3762 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3763 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3764 }
3765 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3766 Types.push_back(New);
3767 AtomicTypes.InsertNode(New, InsertPos);
3768 return QualType(New, 0);
3769}
3770
Richard Smith02e85f32011-04-14 22:09:26 +00003771/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3772QualType ASTContext::getAutoDeductType() const {
3773 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00003774 AutoDeductTy = QualType(
3775 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003776 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00003777 0);
Richard Smith02e85f32011-04-14 22:09:26 +00003778 return AutoDeductTy;
3779}
3780
3781/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3782QualType ASTContext::getAutoRRefDeductType() const {
3783 if (AutoRRefDeductTy.isNull())
3784 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3785 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3786 return AutoRRefDeductTy;
3787}
3788
Chris Lattnerfb072462007-01-23 05:45:31 +00003789/// getTagDeclType - Return the unique reference to the type for the
3790/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003791QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003792 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003793 // FIXME: What is the design on getTagDeclType when it requires casting
3794 // away const? mutable?
3795 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003796}
3797
Mike Stump11289f42009-09-09 15:08:12 +00003798/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3799/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3800/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003801CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003802 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003803}
Chris Lattnerfb072462007-01-23 05:45:31 +00003804
Hans Wennborg27541db2011-10-27 08:29:09 +00003805/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3806CanQualType ASTContext::getIntMaxType() const {
3807 return getFromTargetType(Target->getIntMaxType());
3808}
3809
3810/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3811CanQualType ASTContext::getUIntMaxType() const {
3812 return getFromTargetType(Target->getUIntMaxType());
3813}
3814
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003815/// getSignedWCharType - Return the type of "signed wchar_t".
3816/// Used when in C++, as a GCC extension.
3817QualType ASTContext::getSignedWCharType() const {
3818 // FIXME: derive from "Target" ?
3819 return WCharTy;
3820}
3821
3822/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3823/// Used when in C++, as a GCC extension.
3824QualType ASTContext::getUnsignedWCharType() const {
3825 // FIXME: derive from "Target" ?
3826 return UnsignedIntTy;
3827}
3828
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00003829QualType ASTContext::getIntPtrType() const {
3830 return getFromTargetType(Target->getIntPtrType());
3831}
3832
3833QualType ASTContext::getUIntPtrType() const {
3834 return getCorrespondingUnsignedType(getIntPtrType());
3835}
3836
Hans Wennborg27541db2011-10-27 08:29:09 +00003837/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003838/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3839QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003840 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003841}
3842
Eli Friedman4e91899e2012-11-27 02:58:24 +00003843/// \brief Return the unique type for "pid_t" defined in
3844/// <sys/types.h>. We need this to compute the correct type for vfork().
3845QualType ASTContext::getProcessIDType() const {
3846 return getFromTargetType(Target->getProcessIDType());
3847}
3848
Chris Lattnera21ad802008-04-02 05:18:44 +00003849//===----------------------------------------------------------------------===//
3850// Type Operators
3851//===----------------------------------------------------------------------===//
3852
Jay Foad39c79802011-01-12 09:06:06 +00003853CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003854 // Push qualifiers into arrays, and then discard any remaining
3855 // qualifiers.
3856 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003857 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003858 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003859 QualType Result;
3860 if (isa<ArrayType>(Ty)) {
3861 Result = getArrayDecayedType(QualType(Ty,0));
3862 } else if (isa<FunctionType>(Ty)) {
3863 Result = getPointerType(QualType(Ty, 0));
3864 } else {
3865 Result = QualType(Ty, 0);
3866 }
3867
3868 return CanQualType::CreateUnsafe(Result);
3869}
3870
John McCall6c9dd522011-01-18 07:41:22 +00003871QualType ASTContext::getUnqualifiedArrayType(QualType type,
3872 Qualifiers &quals) {
3873 SplitQualType splitType = type.getSplitUnqualifiedType();
3874
3875 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3876 // the unqualified desugared type and then drops it on the floor.
3877 // We then have to strip that sugar back off with
3878 // getUnqualifiedDesugaredType(), which is silly.
3879 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003880 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003881
3882 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003883 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003884 quals = splitType.Quals;
3885 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003886 }
3887
John McCall6c9dd522011-01-18 07:41:22 +00003888 // Otherwise, recurse on the array's element type.
3889 QualType elementType = AT->getElementType();
3890 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3891
3892 // If that didn't change the element type, AT has no qualifiers, so we
3893 // can just use the results in splitType.
3894 if (elementType == unqualElementType) {
3895 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003896 quals = splitType.Quals;
3897 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003898 }
3899
3900 // Otherwise, add in the qualifiers from the outermost type, then
3901 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003902 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003903
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003904 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003905 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003906 CAT->getSizeModifier(), 0);
3907 }
3908
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003909 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003910 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003911 }
3912
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003913 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003914 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003915 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003916 VAT->getSizeModifier(),
3917 VAT->getIndexTypeCVRQualifiers(),
3918 VAT->getBracketsRange());
3919 }
3920
3921 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003922 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003923 DSAT->getSizeModifier(), 0,
3924 SourceRange());
3925}
3926
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003927/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3928/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3929/// they point to and return true. If T1 and T2 aren't pointer types
3930/// or pointer-to-member types, or if they are not similar at this
3931/// level, returns false and leaves T1 and T2 unchanged. Top-level
3932/// qualifiers on T1 and T2 are ignored. This function will typically
3933/// be called in a loop that successively "unwraps" pointer and
3934/// pointer-to-member types to compare them at each level.
3935bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3936 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3937 *T2PtrType = T2->getAs<PointerType>();
3938 if (T1PtrType && T2PtrType) {
3939 T1 = T1PtrType->getPointeeType();
3940 T2 = T2PtrType->getPointeeType();
3941 return true;
3942 }
3943
3944 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3945 *T2MPType = T2->getAs<MemberPointerType>();
3946 if (T1MPType && T2MPType &&
3947 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3948 QualType(T2MPType->getClass(), 0))) {
3949 T1 = T1MPType->getPointeeType();
3950 T2 = T2MPType->getPointeeType();
3951 return true;
3952 }
3953
David Blaikiebbafb8a2012-03-11 07:00:24 +00003954 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003955 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3956 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3957 if (T1OPType && T2OPType) {
3958 T1 = T1OPType->getPointeeType();
3959 T2 = T2OPType->getPointeeType();
3960 return true;
3961 }
3962 }
3963
3964 // FIXME: Block pointers, too?
3965
3966 return false;
3967}
3968
Jay Foad39c79802011-01-12 09:06:06 +00003969DeclarationNameInfo
3970ASTContext::getNameForTemplate(TemplateName Name,
3971 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003972 switch (Name.getKind()) {
3973 case TemplateName::QualifiedTemplate:
3974 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003975 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003976 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3977 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003978
John McCalld9dfe3a2011-06-30 08:33:18 +00003979 case TemplateName::OverloadedTemplate: {
3980 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3981 // DNInfo work in progress: CHECKME: what about DNLoc?
3982 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3983 }
3984
3985 case TemplateName::DependentTemplate: {
3986 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003987 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003988 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003989 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3990 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003991 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003992 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3993 // DNInfo work in progress: FIXME: source locations?
3994 DeclarationNameLoc DNLoc;
3995 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3996 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3997 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003998 }
3999 }
4000
John McCalld9dfe3a2011-06-30 08:33:18 +00004001 case TemplateName::SubstTemplateTemplateParm: {
4002 SubstTemplateTemplateParmStorage *subst
4003 = Name.getAsSubstTemplateTemplateParm();
4004 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4005 NameLoc);
4006 }
4007
4008 case TemplateName::SubstTemplateTemplateParmPack: {
4009 SubstTemplateTemplateParmPackStorage *subst
4010 = Name.getAsSubstTemplateTemplateParmPack();
4011 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4012 NameLoc);
4013 }
4014 }
4015
4016 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004017}
4018
Jay Foad39c79802011-01-12 09:06:06 +00004019TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004020 switch (Name.getKind()) {
4021 case TemplateName::QualifiedTemplate:
4022 case TemplateName::Template: {
4023 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004024 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004025 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004026 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4027
4028 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004029 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004030 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004031
John McCalld9dfe3a2011-06-30 08:33:18 +00004032 case TemplateName::OverloadedTemplate:
4033 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004034
John McCalld9dfe3a2011-06-30 08:33:18 +00004035 case TemplateName::DependentTemplate: {
4036 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4037 assert(DTN && "Non-dependent template names must refer to template decls.");
4038 return DTN->CanonicalTemplateName;
4039 }
4040
4041 case TemplateName::SubstTemplateTemplateParm: {
4042 SubstTemplateTemplateParmStorage *subst
4043 = Name.getAsSubstTemplateTemplateParm();
4044 return getCanonicalTemplateName(subst->getReplacement());
4045 }
4046
4047 case TemplateName::SubstTemplateTemplateParmPack: {
4048 SubstTemplateTemplateParmPackStorage *subst
4049 = Name.getAsSubstTemplateTemplateParmPack();
4050 TemplateTemplateParmDecl *canonParameter
4051 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4052 TemplateArgument canonArgPack
4053 = getCanonicalTemplateArgument(subst->getArgumentPack());
4054 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4055 }
4056 }
4057
4058 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004059}
4060
Douglas Gregoradee3e32009-11-11 23:06:43 +00004061bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4062 X = getCanonicalTemplateName(X);
4063 Y = getCanonicalTemplateName(Y);
4064 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4065}
4066
Mike Stump11289f42009-09-09 15:08:12 +00004067TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004068ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004069 switch (Arg.getKind()) {
4070 case TemplateArgument::Null:
4071 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004072
Douglas Gregora8e02e72009-07-28 23:00:59 +00004073 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004074 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004075
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004076 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004077 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4078 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004079 }
Mike Stump11289f42009-09-09 15:08:12 +00004080
Eli Friedmanb826a002012-09-26 02:36:12 +00004081 case TemplateArgument::NullPtr:
4082 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4083 /*isNullPtr*/true);
4084
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004085 case TemplateArgument::Template:
4086 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004087
4088 case TemplateArgument::TemplateExpansion:
4089 return TemplateArgument(getCanonicalTemplateName(
4090 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004091 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004092
Douglas Gregora8e02e72009-07-28 23:00:59 +00004093 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004094 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004095
Douglas Gregora8e02e72009-07-28 23:00:59 +00004096 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004097 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004098
Douglas Gregora8e02e72009-07-28 23:00:59 +00004099 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004100 if (Arg.pack_size() == 0)
4101 return Arg;
4102
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004103 TemplateArgument *CanonArgs
4104 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004105 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004106 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004107 AEnd = Arg.pack_end();
4108 A != AEnd; (void)++A, ++Idx)
4109 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004110
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004111 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00004112 }
4113 }
4114
4115 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004116 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004117}
4118
Douglas Gregor333489b2009-03-27 23:10:48 +00004119NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004120ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004121 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00004122 return 0;
4123
4124 switch (NNS->getKind()) {
4125 case NestedNameSpecifier::Identifier:
4126 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004127 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004128 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4129 NNS->getAsIdentifier());
4130
4131 case NestedNameSpecifier::Namespace:
4132 // A namespace is canonical; build a nested-name-specifier with
4133 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004134 return NestedNameSpecifier::Create(*this, 0,
4135 NNS->getAsNamespace()->getOriginalNamespace());
4136
4137 case NestedNameSpecifier::NamespaceAlias:
4138 // A namespace is canonical; build a nested-name-specifier with
4139 // this namespace and no prefix.
4140 return NestedNameSpecifier::Create(*this, 0,
4141 NNS->getAsNamespaceAlias()->getNamespace()
4142 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004143
4144 case NestedNameSpecifier::TypeSpec:
4145 case NestedNameSpecifier::TypeSpecWithTemplate: {
4146 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004147
4148 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4149 // break it apart into its prefix and identifier, then reconsititute those
4150 // as the canonical nested-name-specifier. This is required to canonicalize
4151 // a dependent nested-name-specifier involving typedefs of dependent-name
4152 // types, e.g.,
4153 // typedef typename T::type T1;
4154 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004155 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4156 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004157 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004158
Eli Friedman5358a0a2012-03-03 04:09:56 +00004159 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4160 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4161 // first place?
John McCall33ddac02011-01-19 10:06:00 +00004162 return NestedNameSpecifier::Create(*this, 0, false,
4163 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004164 }
4165
4166 case NestedNameSpecifier::Global:
4167 // The global specifier is canonical and unique.
4168 return NNS;
4169 }
4170
David Blaikie8a40f702012-01-17 06:56:22 +00004171 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004172}
4173
Chris Lattner7adf0762008-08-04 07:31:14 +00004174
Jay Foad39c79802011-01-12 09:06:06 +00004175const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004176 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004177 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004178 // Handle the common positive case fast.
4179 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4180 return AT;
4181 }
Mike Stump11289f42009-09-09 15:08:12 +00004182
John McCall8ccfcb52009-09-24 19:53:00 +00004183 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004184 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00004185 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004186
John McCall8ccfcb52009-09-24 19:53:00 +00004187 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004188 // implements C99 6.7.3p8: "If the specification of an array type includes
4189 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004190
Chris Lattner7adf0762008-08-04 07:31:14 +00004191 // If we get here, we either have type qualifiers on the type, or we have
4192 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004193 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004194
John McCall33ddac02011-01-19 10:06:00 +00004195 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004196 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004197
Chris Lattner7adf0762008-08-04 07:31:14 +00004198 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004199 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00004200 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004201 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004202
Chris Lattner7adf0762008-08-04 07:31:14 +00004203 // Otherwise, we have an array and we have qualifiers on it. Push the
4204 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004205 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004206
Chris Lattner7adf0762008-08-04 07:31:14 +00004207 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4208 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4209 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004210 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004211 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4212 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4213 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004214 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004215
Mike Stump11289f42009-09-09 15:08:12 +00004216 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004217 = dyn_cast<DependentSizedArrayType>(ATy))
4218 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004219 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004220 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004221 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004222 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004223 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004224
Chris Lattner7adf0762008-08-04 07:31:14 +00004225 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004226 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004227 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004228 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004229 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004230 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004231}
4232
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004233QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004234 if (T->isArrayType() || T->isFunctionType())
4235 return getDecayedType(T);
4236 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004237}
4238
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004239QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004240 T = getVariableArrayDecayedType(T);
4241 T = getAdjustedParameterType(T);
4242 return T.getUnqualifiedType();
4243}
4244
Chris Lattnera21ad802008-04-02 05:18:44 +00004245/// getArrayDecayedType - Return the properly qualified result of decaying the
4246/// specified array type to a pointer. This operation is non-trivial when
4247/// handling typedefs etc. The canonical type of "T" must be an array type,
4248/// this returns a pointer to a properly qualified element of the array.
4249///
4250/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004251QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004252 // Get the element type with 'getAsArrayType' so that we don't lose any
4253 // typedefs in the element type of the array. This also handles propagation
4254 // of type qualifiers from the array type into the element type if present
4255 // (C99 6.7.3p8).
4256 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4257 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004258
Chris Lattner7adf0762008-08-04 07:31:14 +00004259 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004260
4261 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004262 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004263}
4264
John McCall33ddac02011-01-19 10:06:00 +00004265QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4266 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004267}
4268
John McCall33ddac02011-01-19 10:06:00 +00004269QualType ASTContext::getBaseElementType(QualType type) const {
4270 Qualifiers qs;
4271 while (true) {
4272 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004273 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004274 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004275
John McCall33ddac02011-01-19 10:06:00 +00004276 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004277 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004278 }
Mike Stump11289f42009-09-09 15:08:12 +00004279
John McCall33ddac02011-01-19 10:06:00 +00004280 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004281}
4282
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004283/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004284uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004285ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4286 uint64_t ElementCount = 1;
4287 do {
4288 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004289 CA = dyn_cast_or_null<ConstantArrayType>(
4290 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004291 } while (CA);
4292 return ElementCount;
4293}
4294
Steve Naroff0af91202007-04-27 21:51:21 +00004295/// getFloatingRank - Return a relative rank for floating point types.
4296/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004297static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004298 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004299 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004300
John McCall9dd450b2009-09-21 23:43:11 +00004301 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4302 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004303 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004304 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004305 case BuiltinType::Float: return FloatRank;
4306 case BuiltinType::Double: return DoubleRank;
4307 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004308 }
4309}
4310
Mike Stump11289f42009-09-09 15:08:12 +00004311/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4312/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004313/// 'typeDomain' is a real floating point or complex type.
4314/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004315QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4316 QualType Domain) const {
4317 FloatingRank EltRank = getFloatingRank(Size);
4318 if (Domain->isComplexType()) {
4319 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004320 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004321 case FloatRank: return FloatComplexTy;
4322 case DoubleRank: return DoubleComplexTy;
4323 case LongDoubleRank: return LongDoubleComplexTy;
4324 }
Steve Naroff0af91202007-04-27 21:51:21 +00004325 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004326
4327 assert(Domain->isRealFloatingType() && "Unknown domain!");
4328 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004329 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004330 case FloatRank: return FloatTy;
4331 case DoubleRank: return DoubleTy;
4332 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004333 }
David Blaikief47fa302012-01-17 02:30:50 +00004334 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004335}
4336
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004337/// getFloatingTypeOrder - Compare the rank of the two specified floating
4338/// point types, ignoring the domain of the type (i.e. 'double' ==
4339/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004340/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004341int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004342 FloatingRank LHSR = getFloatingRank(LHS);
4343 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004344
Chris Lattnerb90739d2008-04-06 23:38:49 +00004345 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004346 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004347 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004348 return 1;
4349 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004350}
4351
Chris Lattner76a00cf2008-04-06 22:59:24 +00004352/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4353/// routine will assert if passed a built-in type that isn't an integer or enum,
4354/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004355unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004356 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004357
Chris Lattner76a00cf2008-04-06 22:59:24 +00004358 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004359 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004360 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004361 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004362 case BuiltinType::Char_S:
4363 case BuiltinType::Char_U:
4364 case BuiltinType::SChar:
4365 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004366 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004367 case BuiltinType::Short:
4368 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004369 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004370 case BuiltinType::Int:
4371 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004372 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004373 case BuiltinType::Long:
4374 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004375 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004376 case BuiltinType::LongLong:
4377 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004378 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004379 case BuiltinType::Int128:
4380 case BuiltinType::UInt128:
4381 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004382 }
4383}
4384
Eli Friedman629ffb92009-08-20 04:21:42 +00004385/// \brief Whether this is a promotable bitfield reference according
4386/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4387///
4388/// \returns the type this bit-field will promote to, or NULL if no
4389/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004390QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004391 if (E->isTypeDependent() || E->isValueDependent())
4392 return QualType();
4393
John McCalld25db7e2013-05-06 21:39:12 +00004394 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004395 if (!Field)
4396 return QualType();
4397
4398 QualType FT = Field->getType();
4399
Richard Smithcaf33902011-10-10 18:28:20 +00004400 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004401 uint64_t IntSize = getTypeSize(IntTy);
4402 // GCC extension compatibility: if the bit-field size is less than or equal
4403 // to the size of int, it gets promoted no matter what its type is.
4404 // For instance, unsigned long bf : 4 gets promoted to signed int.
4405 if (BitWidth < IntSize)
4406 return IntTy;
4407
4408 if (BitWidth == IntSize)
4409 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4410
4411 // Types bigger than int are not subject to promotions, and therefore act
4412 // like the base type.
4413 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4414 // is ridiculous.
4415 return QualType();
4416}
4417
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004418/// getPromotedIntegerType - Returns the type that Promotable will
4419/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4420/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004421QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004422 assert(!Promotable.isNull());
4423 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004424 if (const EnumType *ET = Promotable->getAs<EnumType>())
4425 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004426
4427 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4428 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4429 // (3.9.1) can be converted to a prvalue of the first of the following
4430 // types that can represent all the values of its underlying type:
4431 // int, unsigned int, long int, unsigned long int, long long int, or
4432 // unsigned long long int [...]
4433 // FIXME: Is there some better way to compute this?
4434 if (BT->getKind() == BuiltinType::WChar_S ||
4435 BT->getKind() == BuiltinType::WChar_U ||
4436 BT->getKind() == BuiltinType::Char16 ||
4437 BT->getKind() == BuiltinType::Char32) {
4438 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4439 uint64_t FromSize = getTypeSize(BT);
4440 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4441 LongLongTy, UnsignedLongLongTy };
4442 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4443 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4444 if (FromSize < ToSize ||
4445 (FromSize == ToSize &&
4446 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4447 return PromoteTypes[Idx];
4448 }
4449 llvm_unreachable("char type should fit into long long");
4450 }
4451 }
4452
4453 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004454 if (Promotable->isSignedIntegerType())
4455 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004456 uint64_t PromotableSize = getIntWidth(Promotable);
4457 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004458 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4459 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4460}
4461
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004462/// \brief Recurses in pointer/array types until it finds an objc retainable
4463/// type and returns its ownership.
4464Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4465 while (!T.isNull()) {
4466 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4467 return T.getObjCLifetime();
4468 if (T->isArrayType())
4469 T = getBaseElementType(T);
4470 else if (const PointerType *PT = T->getAs<PointerType>())
4471 T = PT->getPointeeType();
4472 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004473 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004474 else
4475 break;
4476 }
4477
4478 return Qualifiers::OCL_None;
4479}
4480
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004481static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4482 // Incomplete enum types are not treated as integer types.
4483 // FIXME: In C++, enum types are never integer types.
4484 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4485 return ET->getDecl()->getIntegerType().getTypePtr();
4486 return NULL;
4487}
4488
Mike Stump11289f42009-09-09 15:08:12 +00004489/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004490/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004491/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004492int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004493 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4494 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004495
4496 // Unwrap enums to their underlying type.
4497 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4498 LHSC = getIntegerTypeForEnum(ET);
4499 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4500 RHSC = getIntegerTypeForEnum(ET);
4501
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004502 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004503
Chris Lattner76a00cf2008-04-06 22:59:24 +00004504 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4505 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004506
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004507 unsigned LHSRank = getIntegerRank(LHSC);
4508 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004509
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004510 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4511 if (LHSRank == RHSRank) return 0;
4512 return LHSRank > RHSRank ? 1 : -1;
4513 }
Mike Stump11289f42009-09-09 15:08:12 +00004514
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004515 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4516 if (LHSUnsigned) {
4517 // If the unsigned [LHS] type is larger, return it.
4518 if (LHSRank >= RHSRank)
4519 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004520
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004521 // If the signed type can represent all values of the unsigned type, it
4522 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004523 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004524 return -1;
4525 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004526
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004527 // If the unsigned [RHS] type is larger, return it.
4528 if (RHSRank >= LHSRank)
4529 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004530
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004531 // If the signed type can represent all values of the unsigned type, it
4532 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004533 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004534 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004535}
Anders Carlsson98f07902007-08-17 05:31:46 +00004536
Mike Stump11289f42009-09-09 15:08:12 +00004537// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004538QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004539 if (!CFConstantStringTypeDecl) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004540 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
John McCallae580fe2010-02-05 01:33:36 +00004541 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004542
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004543 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004544
Anders Carlsson98f07902007-08-17 05:31:46 +00004545 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004546 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004547 // int flags;
4548 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004549 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004550 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004551 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004552 FieldTypes[3] = LongTy;
4553
Anders Carlsson98f07902007-08-17 05:31:46 +00004554 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004555 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004556 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004557 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004558 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004559 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004560 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004561 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004562 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004563 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004564 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004565 }
4566
Douglas Gregord5058122010-02-11 01:19:42 +00004567 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004568 }
Mike Stump11289f42009-09-09 15:08:12 +00004569
Anders Carlsson98f07902007-08-17 05:31:46 +00004570 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004571}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004572
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004573QualType ASTContext::getObjCSuperType() const {
4574 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004575 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004576 TUDecl->addDecl(ObjCSuperTypeDecl);
4577 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4578 }
4579 return ObjCSuperType;
4580}
4581
Douglas Gregor512b0772009-04-23 22:29:11 +00004582void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004583 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004584 assert(Rec && "Invalid CFConstantStringType");
4585 CFConstantStringTypeDecl = Rec->getDecl();
4586}
4587
Jay Foad39c79802011-01-12 09:06:06 +00004588QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004589 if (BlockDescriptorType)
4590 return getTagDeclType(BlockDescriptorType);
4591
Alp Toker2dea15b2013-12-17 01:22:38 +00004592 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004593 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004594 RD = buildImplicitRecord("__block_descriptor");
4595 RD->startDefinition();
4596
Mike Stumpd0153282009-10-20 02:12:22 +00004597 QualType FieldTypes[] = {
4598 UnsignedLongTy,
4599 UnsignedLongTy,
4600 };
4601
Craig Topperd6d31ac2013-07-15 08:24:27 +00004602 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004603 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004604 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004605 };
4606
4607 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004608 FieldDecl *Field = FieldDecl::Create(
4609 *this, RD, SourceLocation(), SourceLocation(),
4610 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/0,
4611 /*BitWidth=*/0, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004612 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004613 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004614 }
4615
Alp Toker2dea15b2013-12-17 01:22:38 +00004616 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004617
Alp Toker2dea15b2013-12-17 01:22:38 +00004618 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004619
4620 return getTagDeclType(BlockDescriptorType);
4621}
4622
Jay Foad39c79802011-01-12 09:06:06 +00004623QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004624 if (BlockDescriptorExtendedType)
4625 return getTagDeclType(BlockDescriptorExtendedType);
4626
Alp Toker2dea15b2013-12-17 01:22:38 +00004627 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004628 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004629 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4630 RD->startDefinition();
4631
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004632 QualType FieldTypes[] = {
4633 UnsignedLongTy,
4634 UnsignedLongTy,
4635 getPointerType(VoidPtrTy),
4636 getPointerType(VoidPtrTy)
4637 };
4638
Craig Topperd6d31ac2013-07-15 08:24:27 +00004639 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004640 "reserved",
4641 "Size",
4642 "CopyFuncPtr",
4643 "DestroyFuncPtr"
4644 };
4645
4646 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004647 FieldDecl *Field = FieldDecl::Create(
4648 *this, RD, SourceLocation(), SourceLocation(),
4649 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/0,
4650 /*BitWidth=*/0,
4651 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004652 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004653 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004654 }
4655
Alp Toker2dea15b2013-12-17 01:22:38 +00004656 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004657
Alp Toker2dea15b2013-12-17 01:22:38 +00004658 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004659 return getTagDeclType(BlockDescriptorExtendedType);
4660}
4661
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004662/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4663/// requires copy/dispose. Note that this must match the logic
4664/// in buildByrefHelpers.
4665bool ASTContext::BlockRequiresCopying(QualType Ty,
4666 const VarDecl *D) {
4667 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4668 const Expr *copyExpr = getBlockVarCopyInits(D);
4669 if (!copyExpr && record->hasTrivialDestructor()) return false;
4670
Mike Stump94967902009-10-21 18:16:27 +00004671 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004672 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004673
4674 if (!Ty->isObjCRetainableType()) return false;
4675
4676 Qualifiers qs = Ty.getQualifiers();
4677
4678 // If we have lifetime, that dominates.
4679 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4680 assert(getLangOpts().ObjCAutoRefCount);
4681
4682 switch (lifetime) {
4683 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4684
4685 // These are just bits as far as the runtime is concerned.
4686 case Qualifiers::OCL_ExplicitNone:
4687 case Qualifiers::OCL_Autoreleasing:
4688 return false;
4689
4690 // Tell the runtime that this is ARC __weak, called by the
4691 // byref routines.
4692 case Qualifiers::OCL_Weak:
4693 // ARC __strong __block variables need to be retained.
4694 case Qualifiers::OCL_Strong:
4695 return true;
4696 }
4697 llvm_unreachable("fell out of lifetime switch!");
4698 }
4699 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4700 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004701}
4702
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004703bool ASTContext::getByrefLifetime(QualType Ty,
4704 Qualifiers::ObjCLifetime &LifeTime,
4705 bool &HasByrefExtendedLayout) const {
4706
4707 if (!getLangOpts().ObjC1 ||
4708 getLangOpts().getGC() != LangOptions::NonGC)
4709 return false;
4710
4711 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004712 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004713 HasByrefExtendedLayout = true;
4714 LifeTime = Qualifiers::OCL_None;
4715 }
4716 else if (getLangOpts().ObjCAutoRefCount)
4717 LifeTime = Ty.getObjCLifetime();
4718 // MRR.
4719 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4720 LifeTime = Qualifiers::OCL_ExplicitNone;
4721 else
4722 LifeTime = Qualifiers::OCL_None;
4723 return true;
4724}
4725
Douglas Gregorbab8a962011-09-08 01:46:34 +00004726TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4727 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00004728 ObjCInstanceTypeDecl =
4729 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00004730 return ObjCInstanceTypeDecl;
4731}
4732
Anders Carlsson18acd442007-10-29 06:33:42 +00004733// This returns true if a type has been typedefed to BOOL:
4734// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004735static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004736 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004737 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4738 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004739
Anders Carlssond8499822007-10-29 05:01:08 +00004740 return false;
4741}
4742
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004743/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004744/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004745CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004746 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4747 return CharUnits::Zero();
4748
Ken Dyck40775002010-01-11 17:06:35 +00004749 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004750
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004751 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004752 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004753 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004754 // Treat arrays as pointers, since that's how they're passed in.
4755 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004756 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004757 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004758}
4759
4760static inline
4761std::string charUnitsToString(const CharUnits &CU) {
4762 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004763}
4764
John McCall351762c2011-02-07 10:33:21 +00004765/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004766/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004767std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4768 std::string S;
4769
David Chisnall950a9512009-11-17 19:33:30 +00004770 const BlockDecl *Decl = Expr->getBlockDecl();
4771 QualType BlockTy =
4772 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4773 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004774 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00004775 getObjCEncodingForMethodParameter(
4776 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
4777 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004778 else
Alp Toker314cc812014-01-25 16:55:45 +00004779 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004780 // Compute size of all parameters.
4781 // Start with computing size of a pointer in number of bytes.
4782 // FIXME: There might(should) be a better way of doing this computation!
4783 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004784 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4785 CharUnits ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00004786 for (auto PI : Decl->params()) {
4787 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004788 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004789 if (sz.isZero())
4790 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004791 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004792 ParmOffset += sz;
4793 }
4794 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004795 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004796 // Block pointer and offset.
4797 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004798
4799 // Argument types.
4800 ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00004801 for (auto PVDecl : Decl->params()) {
David Chisnall950a9512009-11-17 19:33:30 +00004802 QualType PType = PVDecl->getOriginalType();
4803 if (const ArrayType *AT =
4804 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4805 // Use array's original type only if it has known number of
4806 // elements.
4807 if (!isa<ConstantArrayType>(AT))
4808 PType = PVDecl->getType();
4809 } else if (PType->isFunctionType())
4810 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004811 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004812 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4813 S, true /*Extended*/);
4814 else
4815 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004816 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004817 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004818 }
John McCall351762c2011-02-07 10:33:21 +00004819
4820 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004821}
4822
Douglas Gregora9d84932011-05-27 01:19:52 +00004823bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004824 std::string& S) {
4825 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00004826 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00004827 CharUnits ParmOffset;
4828 // Compute size of all parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00004829 for (auto PI : Decl->params()) {
4830 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00004831 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004832 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004833 continue;
4834
David Chisnall50e4eba2010-12-30 14:05:53 +00004835 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004836 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004837 ParmOffset += sz;
4838 }
4839 S += charUnitsToString(ParmOffset);
4840 ParmOffset = CharUnits::Zero();
4841
4842 // Argument types.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00004843 for (auto PVDecl : Decl->params()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00004844 QualType PType = PVDecl->getOriginalType();
4845 if (const ArrayType *AT =
4846 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4847 // Use array's original type only if it has known number of
4848 // elements.
4849 if (!isa<ConstantArrayType>(AT))
4850 PType = PVDecl->getType();
4851 } else if (PType->isFunctionType())
4852 PType = PVDecl->getType();
4853 getObjCEncodingForType(PType, S);
4854 S += charUnitsToString(ParmOffset);
4855 ParmOffset += getObjCEncodingTypeSize(PType);
4856 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004857
4858 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004859}
4860
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004861/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4862/// method parameter or return type. If Extended, include class names and
4863/// block object types.
4864void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4865 QualType T, std::string& S,
4866 bool Extended) const {
4867 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4868 getObjCEncodingForTypeQualifier(QT, S);
4869 // Encode parameter type.
4870 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4871 true /*OutermostType*/,
4872 false /*EncodingProperty*/,
4873 false /*StructField*/,
4874 Extended /*EncodeBlockParameters*/,
4875 Extended /*EncodeClassNames*/);
4876}
4877
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004878/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004879/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004880bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004881 std::string& S,
4882 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004883 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004884 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00004885 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4886 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004887 // Compute size of all parameters.
4888 // Start with computing size of a pointer in number of bytes.
4889 // FIXME: There might(should) be a better way of doing this computation!
4890 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004891 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004892 // The first two arguments (self and _cmd) are pointers; account for
4893 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004894 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004895 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004896 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004897 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004898 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004899 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004900 continue;
4901
Ken Dyck40775002010-01-11 17:06:35 +00004902 assert (sz.isPositive() &&
4903 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004904 ParmOffset += sz;
4905 }
Ken Dyck40775002010-01-11 17:06:35 +00004906 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004907 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004908 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004909
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004910 // Argument types.
4911 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004912 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004913 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004914 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004915 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004916 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004917 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4918 // Use array's original type only if it has known number of
4919 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004920 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004921 PType = PVDecl->getType();
4922 } else if (PType->isFunctionType())
4923 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004924 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4925 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004926 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004927 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004928 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004929
4930 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004931}
4932
Fariborz Jahaniandad96302014-01-22 19:02:20 +00004933ObjCPropertyImplDecl *
4934ASTContext::getObjCPropertyImplDeclForPropertyDecl(
4935 const ObjCPropertyDecl *PD,
4936 const Decl *Container) const {
4937 if (!Container)
4938 return 0;
4939 if (const ObjCCategoryImplDecl *CID =
4940 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4941 for (ObjCCategoryImplDecl::propimpl_iterator
4942 i = CID->propimpl_begin(), e = CID->propimpl_end();
4943 i != e; ++i) {
4944 ObjCPropertyImplDecl *PID = *i;
4945 if (PID->getPropertyDecl() == PD)
4946 return PID;
4947 }
4948 } else {
4949 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
4950 for (ObjCCategoryImplDecl::propimpl_iterator
4951 i = OID->propimpl_begin(), e = OID->propimpl_end();
4952 i != e; ++i) {
4953 ObjCPropertyImplDecl *PID = *i;
4954 if (PID->getPropertyDecl() == PD)
4955 return PID;
4956 }
4957 }
4958 return 0;
4959}
4960
Daniel Dunbar4932b362008-08-28 04:38:10 +00004961/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004962/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004963/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4964/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004965/// Property attributes are stored as a comma-delimited C string. The simple
4966/// attributes readonly and bycopy are encoded as single characters. The
4967/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4968/// encoded as single characters, followed by an identifier. Property types
4969/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004970/// these attributes are defined by the following enumeration:
4971/// @code
4972/// enum PropertyAttributes {
4973/// kPropertyReadOnly = 'R', // property is read-only.
4974/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4975/// kPropertyByref = '&', // property is a reference to the value last assigned
4976/// kPropertyDynamic = 'D', // property is dynamic
4977/// kPropertyGetter = 'G', // followed by getter selector name
4978/// kPropertySetter = 'S', // followed by setter selector name
4979/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004980/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004981/// kPropertyWeak = 'W' // 'weak' property
4982/// kPropertyStrong = 'P' // property GC'able
4983/// kPropertyNonAtomic = 'N' // property non-atomic
4984/// };
4985/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004986void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004987 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004988 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004989 // Collect information from the property implementation decl(s).
4990 bool Dynamic = false;
4991 ObjCPropertyImplDecl *SynthesizePID = 0;
4992
Fariborz Jahaniandad96302014-01-22 19:02:20 +00004993 if (ObjCPropertyImplDecl *PropertyImpDecl =
4994 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
4995 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
4996 Dynamic = true;
4997 else
4998 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004999 }
5000
5001 // FIXME: This is not very efficient.
5002 S = "T";
5003
5004 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005005 // GCC has some special rules regarding encoding of properties which
5006 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00005007 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005008 true /* outermost type */,
5009 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005010
5011 if (PD->isReadOnly()) {
5012 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005013 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5014 S += ",C";
5015 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5016 S += ",&";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005017 } else {
5018 switch (PD->getSetterKind()) {
5019 case ObjCPropertyDecl::Assign: break;
5020 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005021 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005022 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005023 }
5024 }
5025
5026 // It really isn't clear at all what this means, since properties
5027 // are "dynamic by default".
5028 if (Dynamic)
5029 S += ",D";
5030
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005031 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5032 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005033
Daniel Dunbar4932b362008-08-28 04:38:10 +00005034 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5035 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005036 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005037 }
5038
5039 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5040 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005041 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005042 }
5043
5044 if (SynthesizePID) {
5045 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5046 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005047 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005048 }
5049
5050 // FIXME: OBJCGC: weak & strong
5051}
5052
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005053/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005054/// Another legacy compatibility encoding: 32-bit longs are encoded as
5055/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005056/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5057///
5058void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005059 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005060 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005061 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005062 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005063 else
Jay Foad39c79802011-01-12 09:06:06 +00005064 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005065 PointeeTy = IntTy;
5066 }
5067 }
5068}
5069
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005070void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00005071 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005072 // We follow the behavior of gcc, expanding structures which are
5073 // directly pointed to, and expanding embedded structures. Note that
5074 // these rules are sufficient to prevent recursive encoding of the
5075 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005076 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00005077 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005078}
5079
John McCall393a78d2012-12-20 02:45:14 +00005080static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5081 BuiltinType::Kind kind) {
5082 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005083 case BuiltinType::Void: return 'v';
5084 case BuiltinType::Bool: return 'B';
5085 case BuiltinType::Char_U:
5086 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005087 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005088 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005089 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005090 case BuiltinType::UInt: return 'I';
5091 case BuiltinType::ULong:
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::UInt128: return 'T';
5094 case BuiltinType::ULongLong: return 'Q';
5095 case BuiltinType::Char_S:
5096 case BuiltinType::SChar: return 'c';
5097 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005098 case BuiltinType::WChar_S:
5099 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005100 case BuiltinType::Int: return 'i';
5101 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005102 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005103 case BuiltinType::LongLong: return 'q';
5104 case BuiltinType::Int128: return 't';
5105 case BuiltinType::Float: return 'f';
5106 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005107 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005108 case BuiltinType::NullPtr: return '*'; // like char*
5109
5110 case BuiltinType::Half:
5111 // FIXME: potentially need @encodes for these!
5112 return ' ';
5113
5114 case BuiltinType::ObjCId:
5115 case BuiltinType::ObjCClass:
5116 case BuiltinType::ObjCSel:
5117 llvm_unreachable("@encoding ObjC primitive type");
5118
5119 // OpenCL and placeholder types don't need @encodings.
5120 case BuiltinType::OCLImage1d:
5121 case BuiltinType::OCLImage1dArray:
5122 case BuiltinType::OCLImage1dBuffer:
5123 case BuiltinType::OCLImage2d:
5124 case BuiltinType::OCLImage2dArray:
5125 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005126 case BuiltinType::OCLEvent:
Guy Benyei61054192013-02-07 10:55:47 +00005127 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005128 case BuiltinType::Dependent:
5129#define BUILTIN_TYPE(KIND, ID)
5130#define PLACEHOLDER_TYPE(KIND, ID) \
5131 case BuiltinType::KIND:
5132#include "clang/AST/BuiltinTypes.def"
5133 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005134 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005135 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005136}
5137
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005138static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5139 EnumDecl *Enum = ET->getDecl();
5140
5141 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5142 if (!Enum->isFixed())
5143 return 'i';
5144
5145 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005146 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5147 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005148}
5149
Jay Foad39c79802011-01-12 09:06:06 +00005150static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005151 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005152 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005153 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005154 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5155 // The GNU runtime requires more information; bitfields are encoded as b,
5156 // then the offset (in bits) of the first element, then the type of the
5157 // bitfield, then the size in bits. For example, in this structure:
5158 //
5159 // struct
5160 // {
5161 // int integer;
5162 // int flags:2;
5163 // };
5164 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5165 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5166 // information is not especially sensible, but we're stuck with it for
5167 // compatibility with GCC, although providing it breaks anything that
5168 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005169 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005170 const RecordDecl *RD = FD->getParent();
5171 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005172 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005173 if (const EnumType *ET = T->getAs<EnumType>())
5174 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005175 else {
5176 const BuiltinType *BT = T->castAs<BuiltinType>();
5177 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5178 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005179 }
Richard Smithcaf33902011-10-10 18:28:20 +00005180 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005181}
5182
Daniel Dunbar07d07852009-10-18 21:17:35 +00005183// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005184void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5185 bool ExpandPointedToStructures,
5186 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005187 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005188 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005189 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005190 bool StructField,
5191 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005192 bool EncodeClassNames,
5193 bool EncodePointerToObjCTypedef) const {
John McCall393a78d2012-12-20 02:45:14 +00005194 CanQualType CT = getCanonicalType(T);
5195 switch (CT->getTypeClass()) {
5196 case Type::Builtin:
5197 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005198 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005199 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005200 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5201 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5202 else
5203 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005204 return;
Mike Stump11289f42009-09-09 15:08:12 +00005205
John McCall393a78d2012-12-20 02:45:14 +00005206 case Type::Complex: {
5207 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005208 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00005209 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00005210 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005211 return;
5212 }
John McCall393a78d2012-12-20 02:45:14 +00005213
5214 case Type::Atomic: {
5215 const AtomicType *AT = T->castAs<AtomicType>();
5216 S += 'A';
5217 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5218 false, false);
5219 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005220 }
John McCall393a78d2012-12-20 02:45:14 +00005221
5222 // encoding for pointer or reference types.
5223 case Type::Pointer:
5224 case Type::LValueReference:
5225 case Type::RValueReference: {
5226 QualType PointeeTy;
5227 if (isa<PointerType>(CT)) {
5228 const PointerType *PT = T->castAs<PointerType>();
5229 if (PT->isObjCSelType()) {
5230 S += ':';
5231 return;
5232 }
5233 PointeeTy = PT->getPointeeType();
5234 } else {
5235 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5236 }
5237
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005238 bool isReadOnly = false;
5239 // For historical/compatibility reasons, the read-only qualifier of the
5240 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5241 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005242 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005243 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005244 if (OutermostType && T.isConstQualified()) {
5245 isReadOnly = true;
5246 S += 'r';
5247 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005248 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005249 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005250 while (P->getAs<PointerType>())
5251 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005252 if (P.isConstQualified()) {
5253 isReadOnly = true;
5254 S += 'r';
5255 }
5256 }
5257 if (isReadOnly) {
5258 // Another legacy compatibility encoding. Some ObjC qualifier and type
5259 // combinations need to be rearranged.
5260 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005261 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005262 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005263 }
Mike Stump11289f42009-09-09 15:08:12 +00005264
Anders Carlssond8499822007-10-29 05:01:08 +00005265 if (PointeeTy->isCharType()) {
5266 // char pointer types should be encoded as '*' unless it is a
5267 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005268 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005269 S += '*';
5270 return;
5271 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005272 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005273 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5274 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5275 S += '#';
5276 return;
5277 }
5278 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5279 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5280 S += '@';
5281 return;
5282 }
5283 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005284 }
Anders Carlssond8499822007-10-29 05:01:08 +00005285 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005286 getLegacyIntegralTypeEncoding(PointeeTy);
5287
Mike Stump11289f42009-09-09 15:08:12 +00005288 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005289 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005290 return;
5291 }
John McCall393a78d2012-12-20 02:45:14 +00005292
5293 case Type::ConstantArray:
5294 case Type::IncompleteArray:
5295 case Type::VariableArray: {
5296 const ArrayType *AT = cast<ArrayType>(CT);
5297
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005298 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005299 // Incomplete arrays are encoded as a pointer to the array element.
5300 S += '^';
5301
Mike Stump11289f42009-09-09 15:08:12 +00005302 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005303 false, ExpandStructures, FD);
5304 } else {
5305 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005306
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005307 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5308 S += llvm::utostr(CAT->getSize().getZExtValue());
5309 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005310 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005311 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5312 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005313 S += '0';
5314 }
Mike Stump11289f42009-09-09 15:08:12 +00005315
5316 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005317 false, ExpandStructures, FD);
5318 S += ']';
5319 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005320 return;
5321 }
Mike Stump11289f42009-09-09 15:08:12 +00005322
John McCall393a78d2012-12-20 02:45:14 +00005323 case Type::FunctionNoProto:
5324 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005325 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005326 return;
Mike Stump11289f42009-09-09 15:08:12 +00005327
John McCall393a78d2012-12-20 02:45:14 +00005328 case Type::Record: {
5329 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005330 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005331 // Anonymous structures print as '?'
5332 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5333 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005334 if (ClassTemplateSpecializationDecl *Spec
5335 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5336 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005337 llvm::raw_string_ostream OS(S);
5338 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005339 TemplateArgs.data(),
5340 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005341 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005342 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005343 } else {
5344 S += '?';
5345 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005346 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005347 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005348 if (!RDecl->isUnion()) {
5349 getObjCEncodingForStructureImpl(RDecl, S, FD);
5350 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005351 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005352 if (FD) {
5353 S += '"';
5354 S += Field->getNameAsString();
5355 S += '"';
5356 }
Mike Stump11289f42009-09-09 15:08:12 +00005357
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005358 // Special case bit-fields.
5359 if (Field->isBitField()) {
5360 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005361 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005362 } else {
5363 QualType qt = Field->getType();
5364 getLegacyIntegralTypeEncoding(qt);
5365 getObjCEncodingForTypeImpl(qt, S, false, true,
5366 FD, /*OutermostType*/false,
5367 /*EncodingProperty*/false,
5368 /*StructField*/true);
5369 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005370 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005371 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005372 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005373 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005374 return;
5375 }
Mike Stump11289f42009-09-09 15:08:12 +00005376
John McCall393a78d2012-12-20 02:45:14 +00005377 case Type::BlockPointer: {
5378 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005379 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005380 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005381 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005382
5383 S += '<';
5384 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005385 getObjCEncodingForTypeImpl(
5386 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5387 FD, false /* OutermostType */, EncodingProperty,
5388 false /* StructField */, EncodeBlockParameters, EncodeClassNames);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005389 // Block self
5390 S += "@?";
5391 // Block parameters
5392 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Alp Toker9cacbab2014-01-20 20:26:09 +00005393 for (FunctionProtoType::param_type_iterator I = FPT->param_type_begin(),
5394 E = FPT->param_type_end();
5395 I && (I != E); ++I) {
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005396 getObjCEncodingForTypeImpl(*I, S,
5397 ExpandPointedToStructures,
5398 ExpandStructures,
5399 FD,
5400 false /* OutermostType */,
5401 EncodingProperty,
5402 false /* StructField */,
5403 EncodeBlockParameters,
5404 EncodeClassNames);
5405 }
5406 }
5407 S += '>';
5408 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005409 return;
5410 }
Mike Stump11289f42009-09-09 15:08:12 +00005411
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005412 case Type::ObjCObject: {
5413 // hack to match legacy encoding of *id and *Class
5414 QualType Ty = getObjCObjectPointerType(CT);
5415 if (Ty->isObjCIdType()) {
5416 S += "{objc_object=}";
5417 return;
5418 }
5419 else if (Ty->isObjCClassType()) {
5420 S += "{objc_class=}";
5421 return;
5422 }
5423 }
5424
John McCall393a78d2012-12-20 02:45:14 +00005425 case Type::ObjCInterface: {
5426 // Ignore protocol qualifiers when mangling at this level.
5427 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005428
John McCall393a78d2012-12-20 02:45:14 +00005429 // The assumption seems to be that this assert will succeed
5430 // because nested levels will have filtered out 'id' and 'Class'.
5431 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005432 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005433 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005434 S += '{';
5435 const IdentifierInfo *II = OI->getIdentifier();
5436 S += II->getName();
5437 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005438 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005439 DeepCollectObjCIvars(OI, true, Ivars);
5440 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005441 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005442 if (Field->isBitField())
5443 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005444 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005445 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5446 false, false, false, false, false,
5447 EncodePointerToObjCTypedef);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005448 }
5449 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005450 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005451 }
Mike Stump11289f42009-09-09 15:08:12 +00005452
John McCall393a78d2012-12-20 02:45:14 +00005453 case Type::ObjCObjectPointer: {
5454 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005455 if (OPT->isObjCIdType()) {
5456 S += '@';
5457 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005458 }
Mike Stump11289f42009-09-09 15:08:12 +00005459
Steve Narofff0c86112009-10-28 22:03:49 +00005460 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5461 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5462 // Since this is a binary compatibility issue, need to consult with runtime
5463 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005464 S += '#';
5465 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005466 }
Mike Stump11289f42009-09-09 15:08:12 +00005467
Chris Lattnere7cabb92009-07-13 00:10:46 +00005468 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005469 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005470 ExpandPointedToStructures,
5471 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005472 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005473 // Note that we do extended encoding of protocol qualifer list
5474 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005475 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00005476 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5477 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005478 S += '<';
5479 S += (*I)->getNameAsString();
5480 S += '>';
5481 }
5482 S += '"';
5483 }
5484 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005485 }
Mike Stump11289f42009-09-09 15:08:12 +00005486
Chris Lattnere7cabb92009-07-13 00:10:46 +00005487 QualType PointeeTy = OPT->getPointeeType();
5488 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005489 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5490 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005491 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005492 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005493 // {...};
5494 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005495 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005496 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005497 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5498 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5499 DeepCollectObjCIvars(OI, true, Ivars);
5500 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5501 if (cast<FieldDecl>(Ivars[i]) == FD) {
5502 S += '{';
5503 S += OI->getIdentifier()->getName();
5504 S += '}';
5505 return;
5506 }
5507 }
5508 }
Mike Stump11289f42009-09-09 15:08:12 +00005509 getObjCEncodingForTypeImpl(PointeeTy, S,
5510 false, ExpandPointedToStructures,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005511 NULL,
5512 false, false, false, false, false,
5513 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005514 return;
5515 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005516
5517 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005518 if (OPT->getInterfaceDecl() &&
5519 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005520 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005521 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00005522 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5523 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005524 S += '<';
5525 S += (*I)->getNameAsString();
5526 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005527 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005528 S += '"';
5529 }
5530 return;
5531 }
Mike Stump11289f42009-09-09 15:08:12 +00005532
John McCalla9e6e8d2010-05-17 23:56:34 +00005533 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005534 // FIXME: we shoul do better than that. 'M' is available.
5535 case Type::MemberPointer:
John McCalla9e6e8d2010-05-17 23:56:34 +00005536 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005537
John McCall393a78d2012-12-20 02:45:14 +00005538 case Type::Vector:
5539 case Type::ExtVector:
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005540 // This matches gcc's encoding, even though technically it is
5541 // insufficient.
5542 // FIXME. We should do a better job than gcc.
5543 return;
John McCall393a78d2012-12-20 02:45:14 +00005544
Richard Smith27d807c2013-04-30 13:56:41 +00005545 case Type::Auto:
5546 // We could see an undeduced auto type here during error recovery.
5547 // Just ignore it.
5548 return;
5549
John McCall393a78d2012-12-20 02:45:14 +00005550#define ABSTRACT_TYPE(KIND, BASE)
5551#define TYPE(KIND, BASE)
5552#define DEPENDENT_TYPE(KIND, BASE) \
5553 case Type::KIND:
5554#define NON_CANONICAL_TYPE(KIND, BASE) \
5555 case Type::KIND:
5556#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5557 case Type::KIND:
5558#include "clang/AST/TypeNodes.def"
5559 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005560 }
John McCall393a78d2012-12-20 02:45:14 +00005561 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005562}
5563
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005564void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5565 std::string &S,
5566 const FieldDecl *FD,
5567 bool includeVBases) const {
5568 assert(RDecl && "Expected non-null RecordDecl");
5569 assert(!RDecl->isUnion() && "Should not be called for unions");
5570 if (!RDecl->getDefinition())
5571 return;
5572
5573 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5574 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5575 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5576
5577 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00005578 for (const auto &BI : CXXRec->bases()) {
5579 if (!BI.isVirtual()) {
5580 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005581 if (base->isEmpty())
5582 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005583 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005584 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5585 std::make_pair(offs, base));
5586 }
5587 }
5588 }
5589
5590 unsigned i = 0;
5591 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5592 FieldEnd = RDecl->field_end();
5593 Field != FieldEnd; ++Field, ++i) {
5594 uint64_t offs = layout.getFieldOffset(i);
5595 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005596 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005597 }
5598
5599 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005600 for (const auto &BI : CXXRec->vbases()) {
5601 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005602 if (base->isEmpty())
5603 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005604 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005605 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5606 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005607 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5608 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005609 }
5610 }
5611
5612 CharUnits size;
5613 if (CXXRec) {
5614 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5615 } else {
5616 size = layout.getSize();
5617 }
5618
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005619#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005620 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005621#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005622 std::multimap<uint64_t, NamedDecl *>::iterator
5623 CurLayObj = FieldOrBaseOffsets.begin();
5624
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005625 if (CXXRec && CXXRec->isDynamicClass() &&
5626 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005627 if (FD) {
5628 S += "\"_vptr$";
5629 std::string recname = CXXRec->getNameAsString();
5630 if (recname.empty()) recname = "?";
5631 S += recname;
5632 S += '"';
5633 }
5634 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005635#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005636 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005637#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005638 }
5639
5640 if (!RDecl->hasFlexibleArrayMember()) {
5641 // Mark the end of the structure.
5642 uint64_t offs = toBits(size);
5643 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5644 std::make_pair(offs, (NamedDecl*)0));
5645 }
5646
5647 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005648#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005649 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005650 if (CurOffs < CurLayObj->first) {
5651 uint64_t padding = CurLayObj->first - CurOffs;
5652 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5653 // packing/alignment of members is different that normal, in which case
5654 // the encoding will be out-of-sync with the real layout.
5655 // If the runtime switches to just consider the size of types without
5656 // taking into account alignment, we could make padding explicit in the
5657 // encoding (e.g. using arrays of chars). The encoding strings would be
5658 // longer then though.
5659 CurOffs += padding;
5660 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005661#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005662
5663 NamedDecl *dcl = CurLayObj->second;
5664 if (dcl == 0)
5665 break; // reached end of structure.
5666
5667 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5668 // We expand the bases without their virtual bases since those are going
5669 // in the initial structure. Note that this differs from gcc which
5670 // expands virtual bases each time one is encountered in the hierarchy,
5671 // making the encoding type bigger than it really is.
5672 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005673 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005674#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005675 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005676#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005677 } else {
5678 FieldDecl *field = cast<FieldDecl>(dcl);
5679 if (FD) {
5680 S += '"';
5681 S += field->getNameAsString();
5682 S += '"';
5683 }
5684
5685 if (field->isBitField()) {
5686 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005687#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00005688 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005689#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005690 } else {
5691 QualType qt = field->getType();
5692 getLegacyIntegralTypeEncoding(qt);
5693 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5694 /*OutermostType*/false,
5695 /*EncodingProperty*/false,
5696 /*StructField*/true);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005697#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005698 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005699#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005700 }
5701 }
5702 }
5703}
5704
Mike Stump11289f42009-09-09 15:08:12 +00005705void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005706 std::string& S) const {
5707 if (QT & Decl::OBJC_TQ_In)
5708 S += 'n';
5709 if (QT & Decl::OBJC_TQ_Inout)
5710 S += 'N';
5711 if (QT & Decl::OBJC_TQ_Out)
5712 S += 'o';
5713 if (QT & Decl::OBJC_TQ_Bycopy)
5714 S += 'O';
5715 if (QT & Decl::OBJC_TQ_Byref)
5716 S += 'R';
5717 if (QT & Decl::OBJC_TQ_Oneway)
5718 S += 'V';
5719}
5720
Douglas Gregor3ea72692011-08-12 05:46:01 +00005721TypedefDecl *ASTContext::getObjCIdDecl() const {
5722 if (!ObjCIdDecl) {
5723 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5724 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005725 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00005726 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00005727 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005728}
5729
Douglas Gregor52e02802011-08-12 06:17:30 +00005730TypedefDecl *ASTContext::getObjCSelDecl() const {
5731 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005732 QualType T = getPointerType(ObjCBuiltinSelTy);
5733 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00005734 }
5735 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005736}
5737
Douglas Gregor0a586182011-08-12 05:59:41 +00005738TypedefDecl *ASTContext::getObjCClassDecl() const {
5739 if (!ObjCClassDecl) {
5740 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5741 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005742 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00005743 }
Douglas Gregor0a586182011-08-12 05:59:41 +00005744 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005745}
5746
Douglas Gregord53ae832012-01-17 18:09:05 +00005747ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5748 if (!ObjCProtocolClassDecl) {
5749 ObjCProtocolClassDecl
5750 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5751 SourceLocation(),
5752 &Idents.get("Protocol"),
5753 /*PrevDecl=*/0,
5754 SourceLocation(), true);
5755 }
5756
5757 return ObjCProtocolClassDecl;
5758}
5759
Meador Inge5d3fb222012-06-16 03:34:49 +00005760//===----------------------------------------------------------------------===//
5761// __builtin_va_list Construction Functions
5762//===----------------------------------------------------------------------===//
5763
5764static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5765 // typedef char* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005766 QualType T = Context->getPointerType(Context->CharTy);
5767 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005768}
5769
5770static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5771 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005772 QualType T = Context->getPointerType(Context->VoidTy);
5773 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005774}
5775
Tim Northover9bb857a2013-01-31 12:13:10 +00005776static TypedefDecl *
5777CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005778 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00005779 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005780 if (Context->getLangOpts().CPlusPlus) {
5781 // namespace std { struct __va_list {
5782 NamespaceDecl *NS;
5783 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5784 Context->getTranslationUnitDecl(),
5785 /*Inline*/false, SourceLocation(),
5786 SourceLocation(), &Context->Idents.get("std"),
5787 /*PrevDecl*/0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005788 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00005789 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00005790 }
5791
5792 VaListTagDecl->startDefinition();
5793
5794 const size_t NumFields = 5;
5795 QualType FieldTypes[NumFields];
5796 const char *FieldNames[NumFields];
5797
5798 // void *__stack;
5799 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5800 FieldNames[0] = "__stack";
5801
5802 // void *__gr_top;
5803 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5804 FieldNames[1] = "__gr_top";
5805
5806 // void *__vr_top;
5807 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5808 FieldNames[2] = "__vr_top";
5809
5810 // int __gr_offs;
5811 FieldTypes[3] = Context->IntTy;
5812 FieldNames[3] = "__gr_offs";
5813
5814 // int __vr_offs;
5815 FieldTypes[4] = Context->IntTy;
5816 FieldNames[4] = "__vr_offs";
5817
5818 // Create fields
5819 for (unsigned i = 0; i < NumFields; ++i) {
5820 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5821 VaListTagDecl,
5822 SourceLocation(),
5823 SourceLocation(),
5824 &Context->Idents.get(FieldNames[i]),
5825 FieldTypes[i], /*TInfo=*/0,
5826 /*BitWidth=*/0,
5827 /*Mutable=*/false,
5828 ICIS_NoInit);
5829 Field->setAccess(AS_public);
5830 VaListTagDecl->addDecl(Field);
5831 }
5832 VaListTagDecl->completeDefinition();
5833 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5834 Context->VaListTagTy = VaListTagType;
5835
5836 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005837 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005838}
5839
Meador Inge5d3fb222012-06-16 03:34:49 +00005840static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5841 // typedef struct __va_list_tag {
5842 RecordDecl *VaListTagDecl;
5843
Alp Toker2dea15b2013-12-17 01:22:38 +00005844 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005845 VaListTagDecl->startDefinition();
5846
5847 const size_t NumFields = 5;
5848 QualType FieldTypes[NumFields];
5849 const char *FieldNames[NumFields];
5850
5851 // unsigned char gpr;
5852 FieldTypes[0] = Context->UnsignedCharTy;
5853 FieldNames[0] = "gpr";
5854
5855 // unsigned char fpr;
5856 FieldTypes[1] = Context->UnsignedCharTy;
5857 FieldNames[1] = "fpr";
5858
5859 // unsigned short reserved;
5860 FieldTypes[2] = Context->UnsignedShortTy;
5861 FieldNames[2] = "reserved";
5862
5863 // void* overflow_arg_area;
5864 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5865 FieldNames[3] = "overflow_arg_area";
5866
5867 // void* reg_save_area;
5868 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5869 FieldNames[4] = "reg_save_area";
5870
5871 // Create fields
5872 for (unsigned i = 0; i < NumFields; ++i) {
5873 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5874 SourceLocation(),
5875 SourceLocation(),
5876 &Context->Idents.get(FieldNames[i]),
5877 FieldTypes[i], /*TInfo=*/0,
5878 /*BitWidth=*/0,
5879 /*Mutable=*/false,
5880 ICIS_NoInit);
5881 Field->setAccess(AS_public);
5882 VaListTagDecl->addDecl(Field);
5883 }
5884 VaListTagDecl->completeDefinition();
5885 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005886 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005887
5888 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00005889 TypedefDecl *VaListTagTypedefDecl =
5890 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
5891
Meador Inge5d3fb222012-06-16 03:34:49 +00005892 QualType VaListTagTypedefType =
5893 Context->getTypedefType(VaListTagTypedefDecl);
5894
5895 // typedef __va_list_tag __builtin_va_list[1];
5896 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5897 QualType VaListTagArrayType
5898 = Context->getConstantArrayType(VaListTagTypedefType,
5899 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005900 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005901}
5902
5903static TypedefDecl *
5904CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5905 // typedef struct __va_list_tag {
5906 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00005907 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005908 VaListTagDecl->startDefinition();
5909
5910 const size_t NumFields = 4;
5911 QualType FieldTypes[NumFields];
5912 const char *FieldNames[NumFields];
5913
5914 // unsigned gp_offset;
5915 FieldTypes[0] = Context->UnsignedIntTy;
5916 FieldNames[0] = "gp_offset";
5917
5918 // unsigned fp_offset;
5919 FieldTypes[1] = Context->UnsignedIntTy;
5920 FieldNames[1] = "fp_offset";
5921
5922 // void* overflow_arg_area;
5923 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5924 FieldNames[2] = "overflow_arg_area";
5925
5926 // void* reg_save_area;
5927 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5928 FieldNames[3] = "reg_save_area";
5929
5930 // Create fields
5931 for (unsigned i = 0; i < NumFields; ++i) {
5932 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5933 VaListTagDecl,
5934 SourceLocation(),
5935 SourceLocation(),
5936 &Context->Idents.get(FieldNames[i]),
5937 FieldTypes[i], /*TInfo=*/0,
5938 /*BitWidth=*/0,
5939 /*Mutable=*/false,
5940 ICIS_NoInit);
5941 Field->setAccess(AS_public);
5942 VaListTagDecl->addDecl(Field);
5943 }
5944 VaListTagDecl->completeDefinition();
5945 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005946 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005947
5948 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00005949 TypedefDecl *VaListTagTypedefDecl =
5950 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
5951
Meador Inge5d3fb222012-06-16 03:34:49 +00005952 QualType VaListTagTypedefType =
5953 Context->getTypedefType(VaListTagTypedefDecl);
5954
5955 // typedef __va_list_tag __builtin_va_list[1];
5956 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5957 QualType VaListTagArrayType
5958 = Context->getConstantArrayType(VaListTagTypedefType,
5959 Size, ArrayType::Normal,0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005960 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005961}
5962
5963static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5964 // typedef int __builtin_va_list[4];
5965 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5966 QualType IntArrayType
5967 = Context->getConstantArrayType(Context->IntTy,
5968 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005969 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005970}
5971
Logan Chien57086ce2012-10-10 06:56:20 +00005972static TypedefDecl *
5973CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005974 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00005975 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00005976 if (Context->getLangOpts().CPlusPlus) {
5977 // namespace std { struct __va_list {
5978 NamespaceDecl *NS;
5979 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5980 Context->getTranslationUnitDecl(),
5981 /*Inline*/false, SourceLocation(),
5982 SourceLocation(), &Context->Idents.get("std"),
5983 /*PrevDecl*/0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005984 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00005985 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00005986 }
5987
5988 VaListDecl->startDefinition();
5989
5990 // void * __ap;
5991 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5992 VaListDecl,
5993 SourceLocation(),
5994 SourceLocation(),
5995 &Context->Idents.get("__ap"),
5996 Context->getPointerType(Context->VoidTy),
5997 /*TInfo=*/0,
5998 /*BitWidth=*/0,
5999 /*Mutable=*/false,
6000 ICIS_NoInit);
6001 Field->setAccess(AS_public);
6002 VaListDecl->addDecl(Field);
6003
6004 // };
6005 VaListDecl->completeDefinition();
6006
6007 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006008 QualType T = Context->getRecordType(VaListDecl);
6009 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006010}
6011
Ulrich Weigand47445072013-05-06 16:26:41 +00006012static TypedefDecl *
6013CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6014 // typedef struct __va_list_tag {
6015 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006016 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006017 VaListTagDecl->startDefinition();
6018
6019 const size_t NumFields = 4;
6020 QualType FieldTypes[NumFields];
6021 const char *FieldNames[NumFields];
6022
6023 // long __gpr;
6024 FieldTypes[0] = Context->LongTy;
6025 FieldNames[0] = "__gpr";
6026
6027 // long __fpr;
6028 FieldTypes[1] = Context->LongTy;
6029 FieldNames[1] = "__fpr";
6030
6031 // void *__overflow_arg_area;
6032 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6033 FieldNames[2] = "__overflow_arg_area";
6034
6035 // void *__reg_save_area;
6036 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6037 FieldNames[3] = "__reg_save_area";
6038
6039 // Create fields
6040 for (unsigned i = 0; i < NumFields; ++i) {
6041 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6042 VaListTagDecl,
6043 SourceLocation(),
6044 SourceLocation(),
6045 &Context->Idents.get(FieldNames[i]),
6046 FieldTypes[i], /*TInfo=*/0,
6047 /*BitWidth=*/0,
6048 /*Mutable=*/false,
6049 ICIS_NoInit);
6050 Field->setAccess(AS_public);
6051 VaListTagDecl->addDecl(Field);
6052 }
6053 VaListTagDecl->completeDefinition();
6054 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6055 Context->VaListTagTy = VaListTagType;
6056
6057 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006058 TypedefDecl *VaListTagTypedefDecl =
6059 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006060 QualType VaListTagTypedefType =
6061 Context->getTypedefType(VaListTagTypedefDecl);
6062
6063 // typedef __va_list_tag __builtin_va_list[1];
6064 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6065 QualType VaListTagArrayType
6066 = Context->getConstantArrayType(VaListTagTypedefType,
6067 Size, ArrayType::Normal,0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006068
Alp Toker56b5cc92013-12-15 10:36:26 +00006069 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006070}
6071
Meador Inge5d3fb222012-06-16 03:34:49 +00006072static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6073 TargetInfo::BuiltinVaListKind Kind) {
6074 switch (Kind) {
6075 case TargetInfo::CharPtrBuiltinVaList:
6076 return CreateCharPtrBuiltinVaListDecl(Context);
6077 case TargetInfo::VoidPtrBuiltinVaList:
6078 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006079 case TargetInfo::AArch64ABIBuiltinVaList:
6080 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006081 case TargetInfo::PowerABIBuiltinVaList:
6082 return CreatePowerABIBuiltinVaListDecl(Context);
6083 case TargetInfo::X86_64ABIBuiltinVaList:
6084 return CreateX86_64ABIBuiltinVaListDecl(Context);
6085 case TargetInfo::PNaClABIBuiltinVaList:
6086 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006087 case TargetInfo::AAPCSABIBuiltinVaList:
6088 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006089 case TargetInfo::SystemZBuiltinVaList:
6090 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006091 }
6092
6093 llvm_unreachable("Unhandled __builtin_va_list type kind");
6094}
6095
6096TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006097 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006098 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006099 assert(BuiltinVaListDecl->isImplicit());
6100 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006101
6102 return BuiltinVaListDecl;
6103}
6104
Meador Ingecfb60902012-07-01 15:57:25 +00006105QualType ASTContext::getVaListTagType() const {
6106 // Force the creation of VaListTagTy by building the __builtin_va_list
6107 // declaration.
6108 if (VaListTagTy.isNull())
6109 (void) getBuiltinVaListDecl();
6110
6111 return VaListTagTy;
6112}
6113
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006114void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006115 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006116 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006117
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006118 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006119}
6120
John McCalld28ae272009-12-02 08:04:21 +00006121/// \brief Retrieve the template name that corresponds to a non-empty
6122/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006123TemplateName
6124ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6125 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006126 unsigned size = End - Begin;
6127 assert(size > 1 && "set is not overloaded!");
6128
6129 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6130 size * sizeof(FunctionTemplateDecl*));
6131 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6132
6133 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006134 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006135 NamedDecl *D = *I;
6136 assert(isa<FunctionTemplateDecl>(D) ||
6137 (isa<UsingShadowDecl>(D) &&
6138 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6139 *Storage++ = D;
6140 }
6141
6142 return TemplateName(OT);
6143}
6144
Douglas Gregordc572a32009-03-30 22:58:21 +00006145/// \brief Retrieve the template name that represents a qualified
6146/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006147TemplateName
6148ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6149 bool TemplateKeyword,
6150 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006151 assert(NNS && "Missing nested-name-specifier in qualified template name");
6152
Douglas Gregorc42075a2010-02-04 18:10:26 +00006153 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006154 llvm::FoldingSetNodeID ID;
6155 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6156
6157 void *InsertPos = 0;
6158 QualifiedTemplateName *QTN =
6159 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6160 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006161 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6162 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006163 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6164 }
6165
6166 return TemplateName(QTN);
6167}
6168
6169/// \brief Retrieve the template name that represents a dependent
6170/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006171TemplateName
6172ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6173 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006174 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006175 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006176
6177 llvm::FoldingSetNodeID ID;
6178 DependentTemplateName::Profile(ID, NNS, Name);
6179
6180 void *InsertPos = 0;
6181 DependentTemplateName *QTN =
6182 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6183
6184 if (QTN)
6185 return TemplateName(QTN);
6186
6187 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6188 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006189 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6190 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006191 } else {
6192 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006193 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6194 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006195 DependentTemplateName *CheckQTN =
6196 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6197 assert(!CheckQTN && "Dependent type name canonicalization broken");
6198 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006199 }
6200
6201 DependentTemplateNames.InsertNode(QTN, InsertPos);
6202 return TemplateName(QTN);
6203}
6204
Douglas Gregor71395fa2009-11-04 00:56:37 +00006205/// \brief Retrieve the template name that represents a dependent
6206/// template name such as \c MetaFun::template operator+.
6207TemplateName
6208ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006209 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006210 assert((!NNS || NNS->isDependent()) &&
6211 "Nested name specifier must be dependent");
6212
6213 llvm::FoldingSetNodeID ID;
6214 DependentTemplateName::Profile(ID, NNS, Operator);
6215
6216 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006217 DependentTemplateName *QTN
6218 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006219
6220 if (QTN)
6221 return TemplateName(QTN);
6222
6223 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6224 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006225 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6226 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006227 } else {
6228 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006229 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6230 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006231
6232 DependentTemplateName *CheckQTN
6233 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6234 assert(!CheckQTN && "Dependent template name canonicalization broken");
6235 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006236 }
6237
6238 DependentTemplateNames.InsertNode(QTN, InsertPos);
6239 return TemplateName(QTN);
6240}
6241
Douglas Gregor5590be02011-01-15 06:45:20 +00006242TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006243ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6244 TemplateName replacement) const {
6245 llvm::FoldingSetNodeID ID;
6246 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6247
6248 void *insertPos = 0;
6249 SubstTemplateTemplateParmStorage *subst
6250 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6251
6252 if (!subst) {
6253 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6254 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6255 }
6256
6257 return TemplateName(subst);
6258}
6259
6260TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006261ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6262 const TemplateArgument &ArgPack) const {
6263 ASTContext &Self = const_cast<ASTContext &>(*this);
6264 llvm::FoldingSetNodeID ID;
6265 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6266
6267 void *InsertPos = 0;
6268 SubstTemplateTemplateParmPackStorage *Subst
6269 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6270
6271 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006272 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006273 ArgPack.pack_size(),
6274 ArgPack.pack_begin());
6275 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6276 }
6277
6278 return TemplateName(Subst);
6279}
6280
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006281/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006282/// TargetInfo, produce the corresponding type. The unsigned @p Type
6283/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006284CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006285 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006286 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006287 case TargetInfo::SignedChar: return SignedCharTy;
6288 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006289 case TargetInfo::SignedShort: return ShortTy;
6290 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6291 case TargetInfo::SignedInt: return IntTy;
6292 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6293 case TargetInfo::SignedLong: return LongTy;
6294 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6295 case TargetInfo::SignedLongLong: return LongLongTy;
6296 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6297 }
6298
David Blaikie83d382b2011-09-23 05:06:16 +00006299 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006300}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006301
6302//===----------------------------------------------------------------------===//
6303// Type Predicates.
6304//===----------------------------------------------------------------------===//
6305
Fariborz Jahanian96207692009-02-18 21:49:28 +00006306/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6307/// garbage collection attribute.
6308///
John McCall553d45a2011-01-12 00:34:59 +00006309Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006310 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006311 return Qualifiers::GCNone;
6312
David Blaikiebbafb8a2012-03-11 07:00:24 +00006313 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006314 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6315
6316 // Default behaviour under objective-C's gc is for ObjC pointers
6317 // (or pointers to them) be treated as though they were declared
6318 // as __strong.
6319 if (GCAttrs == Qualifiers::GCNone) {
6320 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6321 return Qualifiers::Strong;
6322 else if (Ty->isPointerType())
6323 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6324 } else {
6325 // It's not valid to set GC attributes on anything that isn't a
6326 // pointer.
6327#ifndef NDEBUG
6328 QualType CT = Ty->getCanonicalTypeInternal();
6329 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6330 CT = AT->getElementType();
6331 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6332#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006333 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006334 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006335}
6336
Chris Lattner49af6a42008-04-07 06:51:04 +00006337//===----------------------------------------------------------------------===//
6338// Type Compatibility Testing
6339//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006340
Mike Stump11289f42009-09-09 15:08:12 +00006341/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006342/// compatible.
6343static bool areCompatVectorTypes(const VectorType *LHS,
6344 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006345 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006346 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006347 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006348}
6349
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006350bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6351 QualType SecondVec) {
6352 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6353 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6354
6355 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6356 return true;
6357
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006358 // Treat Neon vector types and most AltiVec vector types as if they are the
6359 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006360 const VectorType *First = FirstVec->getAs<VectorType>();
6361 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006362 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006363 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006364 First->getVectorKind() != VectorType::AltiVecPixel &&
6365 First->getVectorKind() != VectorType::AltiVecBool &&
6366 Second->getVectorKind() != VectorType::AltiVecPixel &&
6367 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006368 return true;
6369
6370 return false;
6371}
6372
Steve Naroff8e6aee52009-07-23 01:01:38 +00006373//===----------------------------------------------------------------------===//
6374// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6375//===----------------------------------------------------------------------===//
6376
6377/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6378/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006379bool
6380ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6381 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006382 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006383 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006384 for (auto *PI : rProto->protocols())
6385 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006386 return true;
6387 return false;
6388}
6389
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006390/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6391/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006392bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6393 QualType rhs) {
6394 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6395 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6396 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6397
6398 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6399 E = lhsQID->qual_end(); I != E; ++I) {
6400 bool match = false;
6401 ObjCProtocolDecl *lhsProto = *I;
6402 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6403 E = rhsOPT->qual_end(); J != E; ++J) {
6404 ObjCProtocolDecl *rhsProto = *J;
6405 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6406 match = true;
6407 break;
6408 }
6409 }
6410 if (!match)
6411 return false;
6412 }
6413 return true;
6414}
6415
Steve Naroff8e6aee52009-07-23 01:01:38 +00006416/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6417/// ObjCQualifiedIDType.
6418bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6419 bool compare) {
6420 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006421 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006422 lhs->isObjCIdType() || lhs->isObjCClassType())
6423 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006424 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006425 rhs->isObjCIdType() || rhs->isObjCClassType())
6426 return true;
6427
6428 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006429 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006430
Steve Naroff8e6aee52009-07-23 01:01:38 +00006431 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006432
Steve Naroff8e6aee52009-07-23 01:01:38 +00006433 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006434 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006435 // make sure we check the class hierarchy.
6436 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6437 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6438 E = lhsQID->qual_end(); I != E; ++I) {
6439 // when comparing an id<P> on lhs with a static type on rhs,
6440 // see if static class implements all of id's protocols, directly or
6441 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006442 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006443 return false;
6444 }
6445 }
6446 // If there are no qualifiers and no interface, we have an 'id'.
6447 return true;
6448 }
Mike Stump11289f42009-09-09 15:08:12 +00006449 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006450 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6451 E = lhsQID->qual_end(); I != E; ++I) {
6452 ObjCProtocolDecl *lhsProto = *I;
6453 bool match = false;
6454
6455 // when comparing an id<P> on lhs with a static type on rhs,
6456 // see if static class implements all of id's protocols, directly or
6457 // through its super class and categories.
6458 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6459 E = rhsOPT->qual_end(); J != E; ++J) {
6460 ObjCProtocolDecl *rhsProto = *J;
6461 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6462 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6463 match = true;
6464 break;
6465 }
6466 }
Mike Stump11289f42009-09-09 15:08:12 +00006467 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006468 // make sure we check the class hierarchy.
6469 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6470 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6471 E = lhsQID->qual_end(); I != E; ++I) {
6472 // when comparing an id<P> on lhs with a static type on rhs,
6473 // see if static class implements all of id's protocols, directly or
6474 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006475 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006476 match = true;
6477 break;
6478 }
6479 }
6480 }
6481 if (!match)
6482 return false;
6483 }
Mike Stump11289f42009-09-09 15:08:12 +00006484
Steve Naroff8e6aee52009-07-23 01:01:38 +00006485 return true;
6486 }
Mike Stump11289f42009-09-09 15:08:12 +00006487
Steve Naroff8e6aee52009-07-23 01:01:38 +00006488 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6489 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6490
Mike Stump11289f42009-09-09 15:08:12 +00006491 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006492 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006493 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006494 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6495 E = lhsOPT->qual_end(); I != E; ++I) {
6496 ObjCProtocolDecl *lhsProto = *I;
6497 bool match = false;
6498
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006499 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006500 // see if static class implements all of id's protocols, directly or
6501 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006502 // First, lhs protocols in the qualifier list must be found, direct
6503 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006504 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6505 E = rhsQID->qual_end(); J != E; ++J) {
6506 ObjCProtocolDecl *rhsProto = *J;
6507 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6508 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6509 match = true;
6510 break;
6511 }
6512 }
6513 if (!match)
6514 return false;
6515 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006516
6517 // Static class's protocols, or its super class or category protocols
6518 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6519 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6520 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6521 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6522 // This is rather dubious but matches gcc's behavior. If lhs has
6523 // no type qualifier and its class has no static protocol(s)
6524 // assume that it is mismatch.
6525 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6526 return false;
6527 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6528 LHSInheritedProtocols.begin(),
6529 E = LHSInheritedProtocols.end(); I != E; ++I) {
6530 bool match = false;
6531 ObjCProtocolDecl *lhsProto = (*I);
6532 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6533 E = rhsQID->qual_end(); J != E; ++J) {
6534 ObjCProtocolDecl *rhsProto = *J;
6535 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6536 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6537 match = true;
6538 break;
6539 }
6540 }
6541 if (!match)
6542 return false;
6543 }
6544 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006545 return true;
6546 }
6547 return false;
6548}
6549
Eli Friedman47f77112008-08-22 00:56:42 +00006550/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006551/// compatible for assignment from RHS to LHS. This handles validation of any
6552/// protocol qualifiers on the LHS or RHS.
6553///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006554bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6555 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006556 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6557 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6558
Steve Naroff1329fa02009-07-15 18:40:39 +00006559 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006560 if (LHS->isObjCUnqualifiedIdOrClass() ||
6561 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006562 return true;
6563
John McCall8b07ec22010-05-15 11:32:37 +00006564 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006565 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6566 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006567 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006568
6569 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6570 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6571 QualType(RHSOPT,0));
6572
John McCall8b07ec22010-05-15 11:32:37 +00006573 // If we have 2 user-defined types, fall into that path.
6574 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006575 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006576
Steve Naroff8e6aee52009-07-23 01:01:38 +00006577 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006578}
6579
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006580/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006581/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006582/// arguments in block literals. When passed as arguments, passing 'A*' where
6583/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6584/// not OK. For the return type, the opposite is not OK.
6585bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6586 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006587 const ObjCObjectPointerType *RHSOPT,
6588 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006589 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006590 return true;
6591
6592 if (LHSOPT->isObjCBuiltinType()) {
6593 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6594 }
6595
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006596 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006597 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6598 QualType(RHSOPT,0),
6599 false);
6600
6601 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6602 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6603 if (LHS && RHS) { // We have 2 user-defined types.
6604 if (LHS != RHS) {
6605 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006606 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006607 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006608 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006609 }
6610 else
6611 return true;
6612 }
6613 return false;
6614}
6615
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006616/// getIntersectionOfProtocols - This routine finds the intersection of set
6617/// of protocols inherited from two distinct objective-c pointer objects.
6618/// It is used to build composite qualifier list of the composite type of
6619/// the conditional expression involving two objective-c pointer objects.
6620static
6621void getIntersectionOfProtocols(ASTContext &Context,
6622 const ObjCObjectPointerType *LHSOPT,
6623 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006624 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006625
John McCall8b07ec22010-05-15 11:32:37 +00006626 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6627 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6628 assert(LHS->getInterface() && "LHS must have an interface base");
6629 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006630
6631 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6632 unsigned LHSNumProtocols = LHS->getNumProtocols();
6633 if (LHSNumProtocols > 0)
6634 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6635 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006636 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006637 Context.CollectInheritedProtocols(LHS->getInterface(),
6638 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006639 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6640 LHSInheritedProtocols.end());
6641 }
6642
6643 unsigned RHSNumProtocols = RHS->getNumProtocols();
6644 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006645 ObjCProtocolDecl **RHSProtocols =
6646 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006647 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6648 if (InheritedProtocolSet.count(RHSProtocols[i]))
6649 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006650 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006651 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006652 Context.CollectInheritedProtocols(RHS->getInterface(),
6653 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006654 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6655 RHSInheritedProtocols.begin(),
6656 E = RHSInheritedProtocols.end(); I != E; ++I)
6657 if (InheritedProtocolSet.count((*I)))
6658 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006659 }
6660}
6661
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006662/// areCommonBaseCompatible - Returns common base class of the two classes if
6663/// one found. Note that this is O'2 algorithm. But it will be called as the
6664/// last type comparison in a ?-exp of ObjC pointer types before a
6665/// warning is issued. So, its invokation is extremely rare.
6666QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006667 const ObjCObjectPointerType *Lptr,
6668 const ObjCObjectPointerType *Rptr) {
6669 const ObjCObjectType *LHS = Lptr->getObjectType();
6670 const ObjCObjectType *RHS = Rptr->getObjectType();
6671 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6672 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006673 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006674 return QualType();
6675
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006676 do {
John McCall8b07ec22010-05-15 11:32:37 +00006677 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006678 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006679 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006680 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6681
6682 QualType Result = QualType(LHS, 0);
6683 if (!Protocols.empty())
6684 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6685 Result = getObjCObjectPointerType(Result);
6686 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006687 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006688 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006689
6690 return QualType();
6691}
6692
John McCall8b07ec22010-05-15 11:32:37 +00006693bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6694 const ObjCObjectType *RHS) {
6695 assert(LHS->getInterface() && "LHS is not an interface type");
6696 assert(RHS->getInterface() && "RHS is not an interface type");
6697
Chris Lattner49af6a42008-04-07 06:51:04 +00006698 // Verify that the base decls are compatible: the RHS must be a subclass of
6699 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006700 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006701 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006702
Chris Lattner49af6a42008-04-07 06:51:04 +00006703 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6704 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006705 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006706 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006707
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006708 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6709 // more detailed analysis is required.
6710 if (RHS->getNumProtocols() == 0) {
6711 // OK, if LHS is a superclass of RHS *and*
6712 // this superclass is assignment compatible with LHS.
6713 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006714 bool IsSuperClass =
6715 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6716 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006717 // OK if conversion of LHS to SuperClass results in narrowing of types
6718 // ; i.e., SuperClass may implement at least one of the protocols
6719 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6720 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6721 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006722 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006723 // If super class has no protocols, it is not a match.
6724 if (SuperClassInheritedProtocols.empty())
6725 return false;
6726
6727 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6728 LHSPE = LHS->qual_end();
6729 LHSPI != LHSPE; LHSPI++) {
6730 bool SuperImplementsProtocol = false;
6731 ObjCProtocolDecl *LHSProto = (*LHSPI);
6732
6733 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6734 SuperClassInheritedProtocols.begin(),
6735 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6736 ObjCProtocolDecl *SuperClassProto = (*I);
6737 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6738 SuperImplementsProtocol = true;
6739 break;
6740 }
6741 }
6742 if (!SuperImplementsProtocol)
6743 return false;
6744 }
6745 return true;
6746 }
6747 return false;
6748 }
Mike Stump11289f42009-09-09 15:08:12 +00006749
John McCall8b07ec22010-05-15 11:32:37 +00006750 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6751 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006752 LHSPI != LHSPE; LHSPI++) {
6753 bool RHSImplementsProtocol = false;
6754
6755 // If the RHS doesn't implement the protocol on the left, the types
6756 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006757 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6758 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006759 RHSPI != RHSPE; RHSPI++) {
6760 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006761 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006762 break;
6763 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006764 }
6765 // FIXME: For better diagnostics, consider passing back the protocol name.
6766 if (!RHSImplementsProtocol)
6767 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006768 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006769 // The RHS implements all protocols listed on the LHS.
6770 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006771}
6772
Steve Naroffb7605152009-02-12 17:52:19 +00006773bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6774 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006775 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6776 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006777
Steve Naroff7cae42b2009-07-10 23:34:53 +00006778 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006779 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006780
6781 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6782 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006783}
6784
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006785bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6786 return canAssignObjCInterfaces(
6787 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6788 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6789}
6790
Mike Stump11289f42009-09-09 15:08:12 +00006791/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006792/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006793/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006794/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006795bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6796 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006797 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006798 return hasSameType(LHS, RHS);
6799
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006800 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006801}
6802
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006803bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006804 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006805}
6806
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006807bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6808 return !mergeTypes(LHS, RHS, true).isNull();
6809}
6810
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006811/// mergeTransparentUnionType - if T is a transparent union type and a member
6812/// of T is compatible with SubType, return the merged type, else return
6813/// QualType()
6814QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6815 bool OfBlockPointer,
6816 bool Unqualified) {
6817 if (const RecordType *UT = T->getAsUnionType()) {
6818 RecordDecl *UD = UT->getDecl();
6819 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006820 for (const auto *I : UD->fields()) {
6821 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006822 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6823 if (!MT.isNull())
6824 return MT;
6825 }
6826 }
6827 }
6828
6829 return QualType();
6830}
6831
Alp Toker9cacbab2014-01-20 20:26:09 +00006832/// mergeFunctionParameterTypes - merge two types which appear as function
6833/// parameter types
6834QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
6835 bool OfBlockPointer,
6836 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006837 // GNU extension: two types are compatible if they appear as a function
6838 // argument, one of the types is a transparent union type and the other
6839 // type is compatible with a union member
6840 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6841 Unqualified);
6842 if (!lmerge.isNull())
6843 return lmerge;
6844
6845 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6846 Unqualified);
6847 if (!rmerge.isNull())
6848 return rmerge;
6849
6850 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6851}
6852
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006853QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006854 bool OfBlockPointer,
6855 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006856 const FunctionType *lbase = lhs->getAs<FunctionType>();
6857 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006858 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6859 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006860 bool allLTypes = true;
6861 bool allRTypes = true;
6862
6863 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006864 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006865 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00006866 QualType RHS = rbase->getReturnType();
6867 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00006868 bool UnqualifiedResult = Unqualified;
6869 if (!UnqualifiedResult)
6870 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006871 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006872 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006873 else
Alp Toker314cc812014-01-25 16:55:45 +00006874 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00006875 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006876 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006877
6878 if (Unqualified)
6879 retType = retType.getUnqualifiedType();
6880
Alp Toker314cc812014-01-25 16:55:45 +00006881 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
6882 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006883 if (Unqualified) {
6884 LRetType = LRetType.getUnqualifiedType();
6885 RRetType = RRetType.getUnqualifiedType();
6886 }
6887
6888 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006889 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006890 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006891 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006892
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006893 // FIXME: double check this
6894 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6895 // rbase->getRegParmAttr() != 0 &&
6896 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006897 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6898 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006899
Douglas Gregor8c940862010-01-18 17:14:39 +00006900 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00006901 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00006902 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006903
John McCall8c6b56f2010-12-15 01:06:38 +00006904 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006905 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6906 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006907 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6908 return QualType();
6909
John McCall31168b02011-06-15 23:02:42 +00006910 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6911 return QualType();
6912
John McCall8c6b56f2010-12-15 01:06:38 +00006913 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6914 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006915
Rafael Espindola8778c282012-11-29 16:09:03 +00006916 if (lbaseInfo.getNoReturn() != NoReturn)
6917 allLTypes = false;
6918 if (rbaseInfo.getNoReturn() != NoReturn)
6919 allRTypes = false;
6920
John McCall31168b02011-06-15 23:02:42 +00006921 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006922
Eli Friedman47f77112008-08-22 00:56:42 +00006923 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006924 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6925 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00006926 // Compatible functions must have the same number of parameters
6927 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00006928 return QualType();
6929
6930 // Variadic and non-variadic functions aren't compatible
6931 if (lproto->isVariadic() != rproto->isVariadic())
6932 return QualType();
6933
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006934 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6935 return QualType();
6936
Fariborz Jahanian97676972011-09-28 21:52:05 +00006937 if (LangOpts.ObjCAutoRefCount &&
6938 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6939 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00006940
6941 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006942 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00006943 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
6944 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
6945 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
6946 QualType paramType = mergeFunctionParameterTypes(
6947 lParamType, rParamType, OfBlockPointer, Unqualified);
6948 if (paramType.isNull())
6949 return QualType();
6950
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006951 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00006952 paramType = paramType.getUnqualifiedType();
6953
6954 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006955 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00006956 lParamType = lParamType.getUnqualifiedType();
6957 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006958 }
Alp Toker601b22c2014-01-21 23:35:24 +00006959
6960 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00006961 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00006962 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00006963 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006964 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006965
Eli Friedman47f77112008-08-22 00:56:42 +00006966 if (allLTypes) return lhs;
6967 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006968
6969 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6970 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00006971 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006972 }
6973
6974 if (lproto) allRTypes = false;
6975 if (rproto) allLTypes = false;
6976
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006977 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006978 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006979 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006980 if (proto->isVariadic()) return QualType();
6981 // Check that the types are compatible with the types that
6982 // would result from default argument promotions (C99 6.7.5.3p15).
6983 // The only types actually affected are promotable integer
6984 // types and floats, which would be passed as a different
6985 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00006986 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
6987 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00006988
Eli Friedman448ce402012-08-30 00:44:15 +00006989 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00006990 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00006991 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
6992 paramTy = Enum->getDecl()->getIntegerType();
6993 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00006994 return QualType();
6995 }
Alp Toker601b22c2014-01-21 23:35:24 +00006996
6997 if (paramTy->isPromotableIntegerType() ||
6998 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00006999 return QualType();
7000 }
7001
7002 if (allLTypes) return lhs;
7003 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007004
7005 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7006 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007007 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007008 }
7009
7010 if (allLTypes) return lhs;
7011 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007012 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007013}
7014
John McCall433c2e62013-03-21 00:10:07 +00007015/// Given that we have an enum type and a non-enum type, try to merge them.
7016static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7017 QualType other, bool isBlockReturnType) {
7018 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7019 // a signed integer type, or an unsigned integer type.
7020 // Compatibility is based on the underlying type, not the promotion
7021 // type.
7022 QualType underlyingType = ET->getDecl()->getIntegerType();
7023 if (underlyingType.isNull()) return QualType();
7024 if (Context.hasSameType(underlyingType, other))
7025 return other;
7026
7027 // In block return types, we're more permissive and accept any
7028 // integral type of the same size.
7029 if (isBlockReturnType && other->isIntegerType() &&
7030 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7031 return other;
7032
7033 return QualType();
7034}
7035
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007036QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007037 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007038 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007039 // C++ [expr]: If an expression initially has the type "reference to T", the
7040 // type is adjusted to "T" prior to any further analysis, the expression
7041 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007042 // expression is an lvalue unless the reference is an rvalue reference and
7043 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007044 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7045 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007046
7047 if (Unqualified) {
7048 LHS = LHS.getUnqualifiedType();
7049 RHS = RHS.getUnqualifiedType();
7050 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007051
Eli Friedman47f77112008-08-22 00:56:42 +00007052 QualType LHSCan = getCanonicalType(LHS),
7053 RHSCan = getCanonicalType(RHS);
7054
7055 // If two types are identical, they are compatible.
7056 if (LHSCan == RHSCan)
7057 return LHS;
7058
John McCall8ccfcb52009-09-24 19:53:00 +00007059 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007060 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7061 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007062 if (LQuals != RQuals) {
7063 // If any of these qualifiers are different, we have a type
7064 // mismatch.
7065 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007066 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7067 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007068 return QualType();
7069
7070 // Exactly one GC qualifier difference is allowed: __strong is
7071 // okay if the other type has no GC qualifier but is an Objective
7072 // C object pointer (i.e. implicitly strong by default). We fix
7073 // this by pretending that the unqualified type was actually
7074 // qualified __strong.
7075 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7076 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7077 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7078
7079 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7080 return QualType();
7081
7082 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7083 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7084 }
7085 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7086 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7087 }
Eli Friedman47f77112008-08-22 00:56:42 +00007088 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007089 }
7090
7091 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007092
Eli Friedmandcca6332009-06-01 01:22:52 +00007093 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7094 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007095
Chris Lattnerfd652912008-01-14 05:45:46 +00007096 // We want to consider the two function types to be the same for these
7097 // comparisons, just force one to the other.
7098 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7099 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007100
7101 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007102 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7103 LHSClass = Type::ConstantArray;
7104 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7105 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007106
John McCall8b07ec22010-05-15 11:32:37 +00007107 // ObjCInterfaces are just specialized ObjCObjects.
7108 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7109 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7110
Nate Begemance4d7fc2008-04-18 23:10:10 +00007111 // Canonicalize ExtVector -> Vector.
7112 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7113 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007114
Chris Lattner95554662008-04-07 05:43:21 +00007115 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007116 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007117 // Note that we only have special rules for turning block enum
7118 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007119 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007120 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007121 }
John McCall9dd450b2009-09-21 23:43:11 +00007122 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007123 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007124 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007125 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007126 if (OfBlockPointer && !BlockReturnType) {
7127 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7128 return LHS;
7129 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7130 return RHS;
7131 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007132
Eli Friedman47f77112008-08-22 00:56:42 +00007133 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007134 }
Eli Friedman47f77112008-08-22 00:56:42 +00007135
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007136 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007137 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007138#define TYPE(Class, Base)
7139#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007140#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007141#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7142#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7143#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007144 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007145
Richard Smith27d807c2013-04-30 13:56:41 +00007146 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007147 case Type::LValueReference:
7148 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007149 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007150 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007151
John McCall8b07ec22010-05-15 11:32:37 +00007152 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007153 case Type::IncompleteArray:
7154 case Type::VariableArray:
7155 case Type::FunctionProto:
7156 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007157 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007158
Chris Lattnerfd652912008-01-14 05:45:46 +00007159 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007160 {
7161 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007162 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7163 QualType RHSPointee = RHS->getAs<PointerType>()->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, false,
7169 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007170 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007171 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007172 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007173 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007174 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007175 return getPointerType(ResultType);
7176 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007177 case Type::BlockPointer:
7178 {
7179 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007180 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7181 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007182 if (Unqualified) {
7183 LHSPointee = LHSPointee.getUnqualifiedType();
7184 RHSPointee = RHSPointee.getUnqualifiedType();
7185 }
7186 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7187 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007188 if (ResultType.isNull()) return QualType();
7189 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7190 return LHS;
7191 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7192 return RHS;
7193 return getBlockPointerType(ResultType);
7194 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007195 case Type::Atomic:
7196 {
7197 // Merge two pointer types, while trying to preserve typedef info
7198 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7199 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7200 if (Unqualified) {
7201 LHSValue = LHSValue.getUnqualifiedType();
7202 RHSValue = RHSValue.getUnqualifiedType();
7203 }
7204 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7205 Unqualified);
7206 if (ResultType.isNull()) return QualType();
7207 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7208 return LHS;
7209 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7210 return RHS;
7211 return getAtomicType(ResultType);
7212 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007213 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007214 {
7215 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7216 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7217 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7218 return QualType();
7219
7220 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7221 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007222 if (Unqualified) {
7223 LHSElem = LHSElem.getUnqualifiedType();
7224 RHSElem = RHSElem.getUnqualifiedType();
7225 }
7226
7227 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007228 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007229 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7230 return LHS;
7231 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7232 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007233 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7234 ArrayType::ArraySizeModifier(), 0);
7235 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7236 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007237 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7238 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007239 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7240 return LHS;
7241 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7242 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007243 if (LVAT) {
7244 // FIXME: This isn't correct! But tricky to implement because
7245 // the array's size has to be the size of LHS, but the type
7246 // has to be different.
7247 return LHS;
7248 }
7249 if (RVAT) {
7250 // FIXME: This isn't correct! But tricky to implement because
7251 // the array's size has to be the size of RHS, but the type
7252 // has to be different.
7253 return RHS;
7254 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007255 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7256 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007257 return getIncompleteArrayType(ResultType,
7258 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007259 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007260 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007261 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007262 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007263 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007264 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007265 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007266 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007267 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007268 case Type::Complex:
7269 // Distinct complex types are incompatible.
7270 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007271 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007272 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007273 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7274 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007275 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007276 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007277 case Type::ObjCObject: {
7278 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007279 // FIXME: This should be type compatibility, e.g. whether
7280 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007281 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7282 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7283 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007284 return LHS;
7285
Eli Friedman47f77112008-08-22 00:56:42 +00007286 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007287 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007288 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007289 if (OfBlockPointer) {
7290 if (canAssignObjCInterfacesInBlockPointer(
7291 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007292 RHS->getAs<ObjCObjectPointerType>(),
7293 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007294 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007295 return QualType();
7296 }
John McCall9dd450b2009-09-21 23:43:11 +00007297 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7298 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007299 return LHS;
7300
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007301 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007302 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007303 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007304
David Blaikie8a40f702012-01-17 06:56:22 +00007305 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007306}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007307
Fariborz Jahanian97676972011-09-28 21:52:05 +00007308bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7309 const FunctionProtoType *FromFunctionType,
7310 const FunctionProtoType *ToFunctionType) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007311 if (FromFunctionType->hasAnyConsumedParams() !=
7312 ToFunctionType->hasAnyConsumedParams())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007313 return false;
7314 FunctionProtoType::ExtProtoInfo FromEPI =
7315 FromFunctionType->getExtProtoInfo();
7316 FunctionProtoType::ExtProtoInfo ToEPI =
7317 ToFunctionType->getExtProtoInfo();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007318 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
Alp Toker601b22c2014-01-21 23:35:24 +00007319 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7320 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
Fariborz Jahanian97676972011-09-28 21:52:05 +00007321 return false;
7322 }
7323 return true;
7324}
7325
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007326/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7327/// 'RHS' attributes and returns the merged version; including for function
7328/// return types.
7329QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7330 QualType LHSCan = getCanonicalType(LHS),
7331 RHSCan = getCanonicalType(RHS);
7332 // If two types are identical, they are compatible.
7333 if (LHSCan == RHSCan)
7334 return LHS;
7335 if (RHSCan->isFunctionType()) {
7336 if (!LHSCan->isFunctionType())
7337 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007338 QualType OldReturnType =
7339 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007340 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007341 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007342 QualType ResReturnType =
7343 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7344 if (ResReturnType.isNull())
7345 return QualType();
7346 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7347 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7348 // In either case, use OldReturnType to build the new function type.
7349 const FunctionType *F = LHS->getAs<FunctionType>();
7350 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007351 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7352 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007353 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007354 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007355 return ResultType;
7356 }
7357 }
7358 return QualType();
7359 }
7360
7361 // If the qualifiers are different, the types can still be merged.
7362 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7363 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7364 if (LQuals != RQuals) {
7365 // If any of these qualifiers are different, we have a type mismatch.
7366 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7367 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7368 return QualType();
7369
7370 // Exactly one GC qualifier difference is allowed: __strong is
7371 // okay if the other type has no GC qualifier but is an Objective
7372 // C object pointer (i.e. implicitly strong by default). We fix
7373 // this by pretending that the unqualified type was actually
7374 // qualified __strong.
7375 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7376 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7377 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7378
7379 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7380 return QualType();
7381
7382 if (GC_L == Qualifiers::Strong)
7383 return LHS;
7384 if (GC_R == Qualifiers::Strong)
7385 return RHS;
7386 return QualType();
7387 }
7388
7389 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7390 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7391 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7392 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7393 if (ResQT == LHSBaseQT)
7394 return LHS;
7395 if (ResQT == RHSBaseQT)
7396 return RHS;
7397 }
7398 return QualType();
7399}
7400
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007401//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007402// Integer Predicates
7403//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007404
Jay Foad39c79802011-01-12 09:06:06 +00007405unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007406 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007407 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007408 if (T->isBooleanType())
7409 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007410 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007411 return (unsigned)getTypeSize(T);
7412}
7413
Abramo Bagnara13640492012-09-09 10:21:24 +00007414QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007415 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007416
7417 // Turn <4 x signed int> -> <4 x unsigned int>
7418 if (const VectorType *VTy = T->getAs<VectorType>())
7419 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007420 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007421
7422 // For enums, we return the unsigned version of the base type.
7423 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007424 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007425
7426 const BuiltinType *BTy = T->getAs<BuiltinType>();
7427 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007428 switch (BTy->getKind()) {
7429 case BuiltinType::Char_S:
7430 case BuiltinType::SChar:
7431 return UnsignedCharTy;
7432 case BuiltinType::Short:
7433 return UnsignedShortTy;
7434 case BuiltinType::Int:
7435 return UnsignedIntTy;
7436 case BuiltinType::Long:
7437 return UnsignedLongTy;
7438 case BuiltinType::LongLong:
7439 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007440 case BuiltinType::Int128:
7441 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007442 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007443 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007444 }
7445}
7446
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007447ASTMutationListener::~ASTMutationListener() { }
7448
Richard Smith1fa5d642013-05-11 05:45:24 +00007449void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7450 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007451
7452//===----------------------------------------------------------------------===//
7453// Builtin Type Computation
7454//===----------------------------------------------------------------------===//
7455
7456/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007457/// pointer over the consumed characters. This returns the resultant type. If
7458/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7459/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7460/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007461///
7462/// RequiresICE is filled in on return to indicate whether the value is required
7463/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007464static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007465 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007466 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007467 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007468 // Modifiers.
7469 int HowLong = 0;
7470 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007471 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007472
Chris Lattnerdc226c22010-10-01 22:42:38 +00007473 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007474 bool Done = false;
7475 while (!Done) {
7476 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007477 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007478 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007479 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007480 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007481 case 'S':
7482 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7483 assert(!Signed && "Can't use 'S' modifier multiple times!");
7484 Signed = true;
7485 break;
7486 case 'U':
7487 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7488 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7489 Unsigned = true;
7490 break;
7491 case 'L':
7492 assert(HowLong <= 2 && "Can't have LLLL modifier");
7493 ++HowLong;
7494 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00007495 case 'W':
7496 // This modifier represents int64 type.
7497 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7498 switch (Context.getTargetInfo().getInt64Type()) {
7499 default:
7500 llvm_unreachable("Unexpected integer type");
7501 case TargetInfo::SignedLong:
7502 HowLong = 1;
7503 break;
7504 case TargetInfo::SignedLongLong:
7505 HowLong = 2;
7506 break;
7507 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00007508 }
7509 }
7510
7511 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007512
Chris Lattnerecd79c62009-06-14 00:45:47 +00007513 // Read the base type.
7514 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007515 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007516 case 'v':
7517 assert(HowLong == 0 && !Signed && !Unsigned &&
7518 "Bad modifiers used with 'v'!");
7519 Type = Context.VoidTy;
7520 break;
Jack Carter24bef982013-08-15 15:16:57 +00007521 case 'h':
7522 assert(HowLong == 0 && !Signed && !Unsigned &&
7523 "Bad modifiers used with 'f'!");
7524 Type = Context.HalfTy;
7525 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007526 case 'f':
7527 assert(HowLong == 0 && !Signed && !Unsigned &&
7528 "Bad modifiers used with 'f'!");
7529 Type = Context.FloatTy;
7530 break;
7531 case 'd':
7532 assert(HowLong < 2 && !Signed && !Unsigned &&
7533 "Bad modifiers used with 'd'!");
7534 if (HowLong)
7535 Type = Context.LongDoubleTy;
7536 else
7537 Type = Context.DoubleTy;
7538 break;
7539 case 's':
7540 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7541 if (Unsigned)
7542 Type = Context.UnsignedShortTy;
7543 else
7544 Type = Context.ShortTy;
7545 break;
7546 case 'i':
7547 if (HowLong == 3)
7548 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7549 else if (HowLong == 2)
7550 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7551 else if (HowLong == 1)
7552 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7553 else
7554 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7555 break;
7556 case 'c':
7557 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7558 if (Signed)
7559 Type = Context.SignedCharTy;
7560 else if (Unsigned)
7561 Type = Context.UnsignedCharTy;
7562 else
7563 Type = Context.CharTy;
7564 break;
7565 case 'b': // boolean
7566 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7567 Type = Context.BoolTy;
7568 break;
7569 case 'z': // size_t.
7570 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7571 Type = Context.getSizeType();
7572 break;
7573 case 'F':
7574 Type = Context.getCFConstantStringType();
7575 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007576 case 'G':
7577 Type = Context.getObjCIdType();
7578 break;
7579 case 'H':
7580 Type = Context.getObjCSelType();
7581 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007582 case 'M':
7583 Type = Context.getObjCSuperType();
7584 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007585 case 'a':
7586 Type = Context.getBuiltinVaListType();
7587 assert(!Type.isNull() && "builtin va list type not initialized!");
7588 break;
7589 case 'A':
7590 // This is a "reference" to a va_list; however, what exactly
7591 // this means depends on how va_list is defined. There are two
7592 // different kinds of va_list: ones passed by value, and ones
7593 // passed by reference. An example of a by-value va_list is
7594 // x86, where va_list is a char*. An example of by-ref va_list
7595 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7596 // we want this argument to be a char*&; for x86-64, we want
7597 // it to be a __va_list_tag*.
7598 Type = Context.getBuiltinVaListType();
7599 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007600 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007601 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007602 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007603 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007604 break;
7605 case 'V': {
7606 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007607 unsigned NumElements = strtoul(Str, &End, 10);
7608 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007609 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007610
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007611 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7612 RequiresICE, false);
7613 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007614
7615 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007616 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007617 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007618 break;
7619 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007620 case 'E': {
7621 char *End;
7622
7623 unsigned NumElements = strtoul(Str, &End, 10);
7624 assert(End != Str && "Missing vector size");
7625
7626 Str = End;
7627
7628 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7629 false);
7630 Type = Context.getExtVectorType(ElementType, NumElements);
7631 break;
7632 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007633 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007634 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7635 false);
7636 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007637 Type = Context.getComplexType(ElementType);
7638 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007639 }
7640 case 'Y' : {
7641 Type = Context.getPointerDiffType();
7642 break;
7643 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007644 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007645 Type = Context.getFILEType();
7646 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007647 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007648 return QualType();
7649 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007650 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007651 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007652 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007653 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007654 else
7655 Type = Context.getjmp_bufType();
7656
Mike Stump2adb4da2009-07-28 23:47:15 +00007657 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007658 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007659 return QualType();
7660 }
7661 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007662 case 'K':
7663 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7664 Type = Context.getucontext_tType();
7665
7666 if (Type.isNull()) {
7667 Error = ASTContext::GE_Missing_ucontext;
7668 return QualType();
7669 }
7670 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007671 case 'p':
7672 Type = Context.getProcessIDType();
7673 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007674 }
Mike Stump11289f42009-09-09 15:08:12 +00007675
Chris Lattnerdc226c22010-10-01 22:42:38 +00007676 // If there are modifiers and if we're allowed to parse them, go for it.
7677 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007678 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007679 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007680 default: Done = true; --Str; break;
7681 case '*':
7682 case '&': {
7683 // Both pointers and references can have their pointee types
7684 // qualified with an address space.
7685 char *End;
7686 unsigned AddrSpace = strtoul(Str, &End, 10);
7687 if (End != Str && AddrSpace != 0) {
7688 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7689 Str = End;
7690 }
7691 if (c == '*')
7692 Type = Context.getPointerType(Type);
7693 else
7694 Type = Context.getLValueReferenceType(Type);
7695 break;
7696 }
7697 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7698 case 'C':
7699 Type = Type.withConst();
7700 break;
7701 case 'D':
7702 Type = Context.getVolatileType(Type);
7703 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007704 case 'R':
7705 Type = Type.withRestrict();
7706 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007707 }
7708 }
Chris Lattner84733392010-10-01 07:13:18 +00007709
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007710 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007711 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007712
Chris Lattnerecd79c62009-06-14 00:45:47 +00007713 return Type;
7714}
7715
7716/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007717QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007718 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007719 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007720 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007721
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007722 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007723
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007724 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007725 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007726 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7727 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007728 if (Error != GE_None)
7729 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007730
7731 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7732
Chris Lattnerecd79c62009-06-14 00:45:47 +00007733 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007734 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007735 if (Error != GE_None)
7736 return QualType();
7737
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007738 // If this argument is required to be an IntegerConstantExpression and the
7739 // caller cares, fill in the bitmask we return.
7740 if (RequiresICE && IntegerConstantArgs)
7741 *IntegerConstantArgs |= 1 << ArgTypes.size();
7742
Chris Lattnerecd79c62009-06-14 00:45:47 +00007743 // Do array -> pointer decay. The builtin should use the decayed type.
7744 if (Ty->isArrayType())
7745 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007746
Chris Lattnerecd79c62009-06-14 00:45:47 +00007747 ArgTypes.push_back(Ty);
7748 }
7749
7750 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7751 "'.' should only occur at end of builtin type list!");
7752
Reid Kleckner78af0702013-08-27 23:08:25 +00007753 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00007754 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7755
7756 bool Variadic = (TypeStr[0] == '.');
7757
7758 // We really shouldn't be making a no-proto type here, especially in C++.
7759 if (ArgTypes.empty() && Variadic)
7760 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007761
John McCalldb40c7f2010-12-14 08:05:40 +00007762 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007763 EPI.ExtInfo = EI;
7764 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007765
Jordan Rose5c382722013-03-08 21:51:21 +00007766 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007767}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007768
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007769GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007770 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007771 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007772
Rafael Espindola3ae00052013-05-13 00:12:11 +00007773 GVALinkage External = GVA_StrongExternal;
7774 switch (FD->getTemplateSpecializationKind()) {
7775 case TSK_Undeclared:
7776 case TSK_ExplicitSpecialization:
7777 External = GVA_StrongExternal;
7778 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007779
Rafael Espindola3ae00052013-05-13 00:12:11 +00007780 case TSK_ExplicitInstantiationDefinition:
7781 return GVA_ExplicitTemplateInstantiation;
7782
7783 case TSK_ExplicitInstantiationDeclaration:
7784 case TSK_ImplicitInstantiation:
7785 External = GVA_TemplateInstantiation;
7786 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007787 }
7788
7789 if (!FD->isInlined())
7790 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00007791
Alp Tokerbfa39342014-01-14 12:51:41 +00007792 if ((!getLangOpts().CPlusPlus && !getLangOpts().MSVCCompat) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00007793 FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007794 // GNU or C99 inline semantics. Determine whether this symbol should be
7795 // externally visible.
7796 if (FD->isInlineDefinitionExternallyVisible())
7797 return External;
7798
7799 // C99 inline semantics, where the symbol is not externally visible.
7800 return GVA_C99Inline;
7801 }
7802
7803 // C++0x [temp.explicit]p9:
7804 // [ Note: The intent is that an inline function that is the subject of
7805 // an explicit instantiation declaration will still be implicitly
7806 // instantiated when used so that the body can be considered for
7807 // inlining, but that no out-of-line copy of the inline function would be
7808 // generated in the translation unit. -- end note ]
7809 if (FD->getTemplateSpecializationKind()
7810 == TSK_ExplicitInstantiationDeclaration)
7811 return GVA_C99Inline;
7812
7813 return GVA_CXXInline;
7814}
7815
7816GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007817 if (!VD->isExternallyVisible())
7818 return GVA_Internal;
7819
Richard Smith8809a0c2013-09-27 20:14:12 +00007820 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007821 case TSK_Undeclared:
7822 case TSK_ExplicitSpecialization:
7823 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007824
Rafael Espindola3ae00052013-05-13 00:12:11 +00007825 case TSK_ExplicitInstantiationDeclaration:
7826 llvm_unreachable("Variable should not be instantiated");
7827 // Fall through to treat this like any other instantiation.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007828
Rafael Espindola3ae00052013-05-13 00:12:11 +00007829 case TSK_ExplicitInstantiationDefinition:
7830 return GVA_ExplicitTemplateInstantiation;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007831
Rafael Espindola3ae00052013-05-13 00:12:11 +00007832 case TSK_ImplicitInstantiation:
7833 return GVA_TemplateInstantiation;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007834 }
Rafael Espindola27699c82013-05-13 14:05:53 +00007835
7836 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007837}
7838
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007839bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007840 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7841 if (!VD->isFileVarDecl())
7842 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00007843 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7844 // We never need to emit an uninstantiated function template.
7845 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7846 return false;
7847 } else
7848 return false;
7849
7850 // If this is a member of a class template, we do not need to emit it.
7851 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007852 return false;
7853
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007854 // Weak references don't produce any output by themselves.
7855 if (D->hasAttr<WeakRefAttr>())
7856 return false;
7857
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007858 // Aliases and used decls are required.
7859 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7860 return true;
7861
7862 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7863 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007864 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007865 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007866
7867 // Constructors and destructors are required.
7868 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7869 return true;
7870
John McCall6bd2a892013-01-25 22:31:03 +00007871 // The key function for a class is required. This rule only comes
7872 // into play when inline functions can be key functions, though.
7873 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7874 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7875 const CXXRecordDecl *RD = MD->getParent();
7876 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7877 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7878 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7879 return true;
7880 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007881 }
7882 }
7883
7884 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7885
7886 // static, static inline, always_inline, and extern inline functions can
7887 // always be deferred. Normal inline functions can be deferred in C99/C++.
7888 // Implicit template instantiations can also be deferred in C++.
7889 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007890 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007891 return false;
7892 return true;
7893 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007894
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007895 const VarDecl *VD = cast<VarDecl>(D);
7896 assert(VD->isFileVarDecl() && "Expected file scoped var");
7897
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007898 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7899 return false;
7900
Richard Smitha0e5e542012-11-12 21:38:00 +00007901 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007902 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smitha0e5e542012-11-12 21:38:00 +00007903 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7904 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007905
Richard Smitha0e5e542012-11-12 21:38:00 +00007906 // Variables that have destruction with side-effects are required.
7907 if (VD->getType().isDestructedType())
7908 return true;
7909
7910 // Variables that have initialization with side-effects are required.
7911 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7912 return true;
7913
7914 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007915}
Charles Davis53c59df2010-08-16 03:33:14 +00007916
Reid Kleckner78af0702013-08-27 23:08:25 +00007917CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
7918 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00007919 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00007920 if (IsCXXMethod)
7921 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007922
Reid Kleckner78af0702013-08-27 23:08:25 +00007923 return (LangOpts.MRTD && !IsVariadic) ? CC_X86StdCall : CC_C;
Charles Davis99202b32010-11-09 18:04:24 +00007924}
7925
Jay Foad39c79802011-01-12 09:06:06 +00007926bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007927 // Pass through to the C++ ABI object
7928 return ABI->isNearlyEmpty(RD);
7929}
7930
Reid Kleckner96f8f932014-02-05 17:27:08 +00007931VTableContextBase *ASTContext::getVTableContext() {
7932 if (!VTContext.get()) {
7933 if (Target->getCXXABI().isMicrosoft())
7934 VTContext.reset(new MicrosoftVTableContext(*this));
7935 else
7936 VTContext.reset(new ItaniumVTableContext(*this));
7937 }
7938 return VTContext.get();
7939}
7940
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007941MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00007942 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00007943 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00007944 case TargetCXXABI::GenericItanium:
7945 case TargetCXXABI::GenericARM:
7946 case TargetCXXABI::iOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00007947 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00007948 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00007949 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007950 }
David Blaikie83d382b2011-09-23 05:06:16 +00007951 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007952}
7953
Charles Davis53c59df2010-08-16 03:33:14 +00007954CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007955
7956size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00007957 return ASTRecordLayouts.getMemorySize() +
7958 llvm::capacity_in_bytes(ObjCLayouts) +
7959 llvm::capacity_in_bytes(KeyFunctions) +
7960 llvm::capacity_in_bytes(ObjCImpls) +
7961 llvm::capacity_in_bytes(BlockVarCopyInits) +
7962 llvm::capacity_in_bytes(DeclAttrs) +
7963 llvm::capacity_in_bytes(TemplateOrInstantiation) +
7964 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
7965 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
7966 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
7967 llvm::capacity_in_bytes(OverriddenMethods) +
7968 llvm::capacity_in_bytes(Types) +
7969 llvm::capacity_in_bytes(VariableArrayTypes) +
7970 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007971}
Ted Kremenek540017e2011-10-06 05:00:56 +00007972
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007973/// getIntTypeForBitwidth -
7974/// sets integer QualTy according to specified details:
7975/// bitwidth, signed/unsigned.
7976/// Returns empty type if there is no appropriate target types.
7977QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
7978 unsigned Signed) const {
7979 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
7980 CanQualType QualTy = getFromTargetType(Ty);
7981 if (!QualTy && DestWidth == 128)
7982 return Signed ? Int128Ty : UnsignedInt128Ty;
7983 return QualTy;
7984}
7985
7986/// getRealTypeForBitwidth -
7987/// sets floating point QualTy according to specified bitwidth.
7988/// Returns empty type if there is no appropriate target types.
7989QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
7990 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
7991 switch (Ty) {
7992 case TargetInfo::Float:
7993 return FloatTy;
7994 case TargetInfo::Double:
7995 return DoubleTy;
7996 case TargetInfo::LongDouble:
7997 return LongDoubleTy;
7998 case TargetInfo::NoFloat:
7999 return QualType();
8000 }
8001
8002 llvm_unreachable("Unhandled TargetInfo::RealType value");
8003}
8004
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008005void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8006 if (Number > 1)
8007 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008008}
8009
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008010unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8011 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8012 MangleNumbers.find(ND);
8013 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008014}
8015
David Majnemer2206bf52014-03-05 08:57:59 +00008016void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8017 if (Number > 1)
8018 StaticLocalNumbers[VD] = Number;
8019}
8020
8021unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8022 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8023 StaticLocalNumbers.find(VD);
8024 return I != StaticLocalNumbers.end() ? I->second : 1;
8025}
8026
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008027MangleNumberingContext &
8028ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008029 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8030 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8031 if (!MCtx)
8032 MCtx = createMangleNumberingContext();
8033 return *MCtx;
8034}
8035
8036MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8037 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008038}
8039
Ted Kremenek540017e2011-10-06 05:00:56 +00008040void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8041 ParamIndices[D] = index;
8042}
8043
8044unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8045 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8046 assert(I != ParamIndices.end() &&
8047 "ParmIndices lacks entry set by ParmVarDecl");
8048 return I->second;
8049}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008050
Richard Smithe6c01442013-06-05 00:46:14 +00008051APValue *
8052ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8053 bool MayCreate) {
8054 assert(E && E->getStorageDuration() == SD_Static &&
8055 "don't need to cache the computed value for this temporary");
8056 if (MayCreate)
8057 return &MaterializedTemporaryValues[E];
8058
8059 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8060 MaterializedTemporaryValues.find(E);
8061 return I == MaterializedTemporaryValues.end() ? 0 : &I->second;
8062}
8063
Fariborz Jahanian615de762013-05-28 17:37:39 +00008064bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8065 const llvm::Triple &T = getTargetInfo().getTriple();
8066 if (!T.isOSDarwin())
8067 return false;
8068
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008069 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8070 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8071 return false;
8072
Fariborz Jahanian615de762013-05-28 17:37:39 +00008073 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8074 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8075 uint64_t Size = sizeChars.getQuantity();
8076 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8077 unsigned Align = alignChars.getQuantity();
8078 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8079 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8080}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008081
8082namespace {
8083
8084 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8085 /// parents as defined by the \c RecursiveASTVisitor.
8086 ///
8087 /// Note that the relationship described here is purely in terms of AST
8088 /// traversal - there are other relationships (for example declaration context)
8089 /// in the AST that are better modeled by special matchers.
8090 ///
8091 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8092 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8093
8094 public:
8095 /// \brief Builds and returns the translation unit's parent map.
8096 ///
8097 /// The caller takes ownership of the returned \c ParentMap.
8098 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8099 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8100 Visitor.TraverseDecl(&TU);
8101 return Visitor.Parents;
8102 }
8103
8104 private:
8105 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8106
8107 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8108 }
8109
8110 bool shouldVisitTemplateInstantiations() const {
8111 return true;
8112 }
8113 bool shouldVisitImplicitCode() const {
8114 return true;
8115 }
8116 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8117 // are not triggered during data recursion.
8118 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8119 return false;
8120 }
8121
8122 template <typename T>
8123 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
8124 if (Node == NULL)
8125 return true;
8126 if (ParentStack.size() > 0)
8127 // FIXME: Currently we add the same parent multiple times, for example
8128 // when we visit all subexpressions of template instantiations; this is
8129 // suboptimal, bug benign: the only way to visit those is with
8130 // hasAncestor / hasParent, and those do not create new matches.
8131 // The plan is to enable DynTypedNode to be storable in a map or hash
8132 // map. The main problem there is to implement hash functions /
8133 // comparison operators for all types that DynTypedNode supports that
8134 // do not have pointer identity.
8135 (*Parents)[Node].push_back(ParentStack.back());
8136 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8137 bool Result = (this ->* traverse) (Node);
8138 ParentStack.pop_back();
8139 return Result;
8140 }
8141
8142 bool TraverseDecl(Decl *DeclNode) {
8143 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8144 }
8145
8146 bool TraverseStmt(Stmt *StmtNode) {
8147 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8148 }
8149
8150 ASTContext::ParentMap *Parents;
8151 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8152
8153 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8154 };
8155
8156} // end namespace
8157
8158ASTContext::ParentVector
8159ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8160 assert(Node.getMemoizationData() &&
8161 "Invariant broken: only nodes that support memoization may be "
8162 "used in the parent map.");
8163 if (!AllParents) {
8164 // We always need to run over the whole translation unit, as
8165 // hasAncestor can escape any subtree.
8166 AllParents.reset(
8167 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8168 }
8169 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8170 if (I == AllParents->end()) {
8171 return ParentVector();
8172 }
8173 return I->second;
8174}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008175
8176bool
8177ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8178 const ObjCMethodDecl *MethodImpl) {
8179 // No point trying to match an unavailable/deprecated mothod.
8180 if (MethodDecl->hasAttr<UnavailableAttr>()
8181 || MethodDecl->hasAttr<DeprecatedAttr>())
8182 return false;
8183 if (MethodDecl->getObjCDeclQualifier() !=
8184 MethodImpl->getObjCDeclQualifier())
8185 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008186 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008187 return false;
8188
8189 if (MethodDecl->param_size() != MethodImpl->param_size())
8190 return false;
8191
8192 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8193 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8194 EF = MethodDecl->param_end();
8195 IM != EM && IF != EF; ++IM, ++IF) {
8196 const ParmVarDecl *DeclVar = (*IF);
8197 const ParmVarDecl *ImplVar = (*IM);
8198 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8199 return false;
8200 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8201 return false;
8202 }
8203 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8204
8205}