blob: cded2e106d5d1f04c8282b2ecab42f957cbcfd69 [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.
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000390 for (ObjCInterfaceDecl::known_extensions_iterator
391 Ext = ID->known_extensions_begin(),
392 ExtEnd = ID->known_extensions_end();
393 Ext != ExtEnd; ++Ext) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000394 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000395 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000396 ObjCMethod->isInstanceMethod()))
397 Redeclared.push_back(RedeclaredMethod);
398 }
399 }
400}
401
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000402comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
403 const Decl *D) const {
404 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
405 ThisDeclInfo->CommentDecl = D;
406 ThisDeclInfo->IsFilled = false;
407 ThisDeclInfo->fill();
408 ThisDeclInfo->CommentDecl = FC->getDecl();
409 comments::FullComment *CFC =
410 new (*this) comments::FullComment(FC->getBlocks(),
411 ThisDeclInfo);
412 return CFC;
413
414}
415
Richard Smithb39b9d52013-05-21 05:24:00 +0000416comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
417 const RawComment *RC = getRawCommentForDeclNoCache(D);
418 return RC ? RC->parse(*this, 0, D) : 0;
419}
420
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000421comments::FullComment *ASTContext::getCommentForDecl(
422 const Decl *D,
423 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000424 if (D->isInvalidDecl())
425 return NULL;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000426 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000427
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000428 const Decl *Canonical = D->getCanonicalDecl();
429 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
430 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000431
432 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000433 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000434 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000435 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000436 return CFC;
437 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000438 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000439 }
440
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000441 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000442
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000443 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000444 if (!RC) {
445 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000446 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000447 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000448 if (OMD && OMD->isPropertyAccessor())
449 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
450 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
451 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000452 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000453 addRedeclaredMethods(OMD, Overridden);
454 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000455 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
456 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
457 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000458 }
Fariborz Jahanian6384fbb2013-05-02 15:44:16 +0000459 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000460 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000461 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000462 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000463 if (const TagType *TT = QT->getAs<TagType>())
464 if (const Decl *TD = TT->getDecl())
465 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000466 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000467 }
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000468 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
469 while (IC->getSuperClass()) {
470 IC = IC->getSuperClass();
471 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
472 return cloneFullComment(FC, D);
473 }
474 }
475 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
476 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
477 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
478 return cloneFullComment(FC, D);
479 }
480 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
481 if (!(RD = RD->getDefinition()))
482 return NULL;
483 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000484 for (const auto &I : RD->bases()) {
485 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000486 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000487 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000488 if (Ty.isNull())
489 continue;
490 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
491 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
492 continue;
493
494 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
495 return cloneFullComment(FC, D);
496 }
497 }
498 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000499 for (const auto &I : RD->vbases()) {
500 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000501 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000502 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000503 if (Ty.isNull())
504 continue;
505 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
506 if (!(VirtualBase= VirtualBase->getDefinition()))
507 continue;
508 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
509 return cloneFullComment(FC, D);
510 }
511 }
512 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000513 return NULL;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000514 }
515
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000516 // If the RawComment was attached to other redeclaration of this Decl, we
517 // should parse the comment in context of that other Decl. This is important
518 // because comments can contain references to parameter names which can be
519 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000520 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000521 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000522
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000523 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000524 ParsedComments[Canonical] = FC;
525 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000526}
527
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000528void
529ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
530 TemplateTemplateParmDecl *Parm) {
531 ID.AddInteger(Parm->getDepth());
532 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000533 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000534
535 TemplateParameterList *Params = Parm->getTemplateParameters();
536 ID.AddInteger(Params->size());
537 for (TemplateParameterList::const_iterator P = Params->begin(),
538 PEnd = Params->end();
539 P != PEnd; ++P) {
540 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
541 ID.AddInteger(0);
542 ID.AddBoolean(TTP->isParameterPack());
543 continue;
544 }
545
546 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
547 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000548 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000549 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000550 if (NTTP->isExpandedParameterPack()) {
551 ID.AddBoolean(true);
552 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000553 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
554 QualType T = NTTP->getExpansionType(I);
555 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
556 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000557 } else
558 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000559 continue;
560 }
561
562 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
563 ID.AddInteger(2);
564 Profile(ID, TTP);
565 }
566}
567
568TemplateTemplateParmDecl *
569ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000570 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000571 // Check if we already have a canonical template template parameter.
572 llvm::FoldingSetNodeID ID;
573 CanonicalTemplateTemplateParm::Profile(ID, TTP);
574 void *InsertPos = 0;
575 CanonicalTemplateTemplateParm *Canonical
576 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
577 if (Canonical)
578 return Canonical->getParam();
579
580 // Build a canonical template parameter list.
581 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000582 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000583 CanonParams.reserve(Params->size());
584 for (TemplateParameterList::const_iterator P = Params->begin(),
585 PEnd = Params->end();
586 P != PEnd; ++P) {
587 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
588 CanonParams.push_back(
589 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000590 SourceLocation(),
591 SourceLocation(),
592 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000593 TTP->getIndex(), 0, false,
594 TTP->isParameterPack()));
595 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000596 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
597 QualType T = getCanonicalType(NTTP->getType());
598 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
599 NonTypeTemplateParmDecl *Param;
600 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000601 SmallVector<QualType, 2> ExpandedTypes;
602 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000603 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
604 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
605 ExpandedTInfos.push_back(
606 getTrivialTypeSourceInfo(ExpandedTypes.back()));
607 }
608
609 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000610 SourceLocation(),
611 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000612 NTTP->getDepth(),
613 NTTP->getPosition(), 0,
614 T,
615 TInfo,
616 ExpandedTypes.data(),
617 ExpandedTypes.size(),
618 ExpandedTInfos.data());
619 } else {
620 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000621 SourceLocation(),
622 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000623 NTTP->getDepth(),
624 NTTP->getPosition(), 0,
625 T,
626 NTTP->isParameterPack(),
627 TInfo);
628 }
629 CanonParams.push_back(Param);
630
631 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000632 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
633 cast<TemplateTemplateParmDecl>(*P)));
634 }
635
636 TemplateTemplateParmDecl *CanonTTP
637 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
638 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000639 TTP->getPosition(),
640 TTP->isParameterPack(),
641 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000642 TemplateParameterList::Create(*this, SourceLocation(),
643 SourceLocation(),
644 CanonParams.data(),
645 CanonParams.size(),
646 SourceLocation()));
647
648 // Get the new insert position for the node we care about.
649 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
650 assert(Canonical == 0 && "Shouldn't be in the map!");
651 (void)Canonical;
652
653 // Create the canonical template template parameter entry.
654 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
655 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
656 return CanonTTP;
657}
658
Charles Davis53c59df2010-08-16 03:33:14 +0000659CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000660 if (!LangOpts.CPlusPlus) return 0;
661
John McCall359b8852013-01-25 22:30:49 +0000662 switch (T.getCXXABI().getKind()) {
663 case TargetCXXABI::GenericARM:
664 case TargetCXXABI::iOS:
John McCall86353412010-08-21 22:46:04 +0000665 return CreateARMCXXABI(*this);
Tim Northover9bb857a2013-01-31 12:13:10 +0000666 case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000667 case TargetCXXABI::GenericItanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000668 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000669 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000670 return CreateMicrosoftCXXABI(*this);
671 }
David Blaikie8a40f702012-01-17 06:56:22 +0000672 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000673}
674
Douglas Gregore8bbc122011-09-02 00:18:52 +0000675static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000676 const LangOptions &LOpts) {
677 if (LOpts.FakeAddressSpaceMap) {
678 // The fake address space map must have a distinct entry for each
679 // language-specific address space.
680 static const unsigned FakeAddrSpaceMap[] = {
681 1, // opencl_global
682 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000683 3, // opencl_constant
684 4, // cuda_device
685 5, // cuda_constant
686 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000687 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000688 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000689 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000690 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000691 }
692}
693
David Tweed31d09b02013-09-13 12:04:22 +0000694static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
695 const LangOptions &LangOpts) {
696 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000697 case LangOptions::ASMM_Target:
698 return TI.useAddressSpaceMapMangling();
699 case LangOptions::ASMM_On:
700 return true;
701 case LangOptions::ASMM_Off:
702 return false;
703 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000704 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000705}
706
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000707ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000708 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000709 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000710 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000711 unsigned size_reserve,
712 bool DelayInitialization)
713 : FunctionProtoTypes(this_()),
714 TemplateSpecializationTypes(this_()),
715 DependentTemplateSpecializationTypes(this_()),
716 SubstTemplateTemplateParmPacks(this_()),
717 GlobalNestedNameSpecifier(0),
Nico Webere1687c52013-06-20 21:44:55 +0000718 Int128Decl(0), UInt128Decl(0), Float128StubDecl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000719 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000720 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanianf2578572012-08-30 18:49:41 +0000721 BOOLDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000722 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000723 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000724 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
725 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
726 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000727 NullTypeSourceInfo(QualType()),
728 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000729 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000730 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000731 Idents(idents), Selectors(sels),
732 BuiltinInfo(builtins),
733 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000734 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000735 Comments(SM), CommentsLoaded(false),
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000736 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
Rafael Espindolace2168f2013-05-29 19:51:12 +0000737 LastSDM(0, 0)
Douglas Gregore8bbc122011-09-02 00:18:52 +0000738{
Mike Stump11289f42009-09-09 15:08:12 +0000739 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000740 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000741
742 if (!DelayInitialization) {
743 assert(t && "No target supplied for ASTContext initialization");
744 InitBuiltinTypes(*t);
745 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000746}
747
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000748ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000749 // Release the DenseMaps associated with DeclContext objects.
750 // FIXME: Is this the ideal solution?
751 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000752
Manuel Klimeka7328992013-06-03 13:51:33 +0000753 // Call all of the deallocation functions on all of their targets.
754 for (DeallocationMap::const_iterator I = Deallocations.begin(),
755 E = Deallocations.end(); I != E; ++I)
756 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
757 (I->first)((I->second)[J]);
758
Ted Kremenek076baeb2010-06-08 23:00:58 +0000759 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000760 // because they can contain DenseMaps.
761 for (llvm::DenseMap<const ObjCContainerDecl*,
762 const ASTRecordLayout*>::iterator
763 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
764 // Increment in loop to prevent using deallocated memory.
765 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
766 R->Destroy(*this);
767
Ted Kremenek076baeb2010-06-08 23:00:58 +0000768 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
769 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
770 // Increment in loop to prevent using deallocated memory.
771 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
772 R->Destroy(*this);
773 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000774
775 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
776 AEnd = DeclAttrs.end();
777 A != AEnd; ++A)
778 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000779
Reid Kleckner588c9372014-02-19 23:44:52 +0000780 llvm::DeleteContainerSeconds(MangleNumberingContexts);
Douglas Gregor561eceb2010-08-30 16:49:28 +0000781}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000782
Douglas Gregor1a809332010-05-23 18:26:36 +0000783void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimeka7328992013-06-03 13:51:33 +0000784 Deallocations[Callback].push_back(Data);
Douglas Gregor1a809332010-05-23 18:26:36 +0000785}
786
Mike Stump11289f42009-09-09 15:08:12 +0000787void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000788ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
789 ExternalSource = Source;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000790}
791
Chris Lattner4eb445d2007-01-26 01:27:23 +0000792void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000793 llvm::errs() << "\n*** AST Context Stats:\n";
794 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000795
Douglas Gregora30d0462009-05-26 14:40:08 +0000796 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000797#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000798#define ABSTRACT_TYPE(Name, Parent)
799#include "clang/AST/TypeNodes.def"
800 0 // Extra
801 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000802
Chris Lattner4eb445d2007-01-26 01:27:23 +0000803 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
804 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000805 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000806 }
807
Douglas Gregora30d0462009-05-26 14:40:08 +0000808 unsigned Idx = 0;
809 unsigned TotalBytes = 0;
810#define TYPE(Name, Parent) \
811 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000812 llvm::errs() << " " << counts[Idx] << " " << #Name \
813 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000814 TotalBytes += counts[Idx] * sizeof(Name##Type); \
815 ++Idx;
816#define ABSTRACT_TYPE(Name, Parent)
817#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000818
Chandler Carruth3c147a72011-07-04 05:32:14 +0000819 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
820
Douglas Gregor7454c562010-07-02 20:37:36 +0000821 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000822 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
823 << NumImplicitDefaultConstructors
824 << " implicit default constructors created\n";
825 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
826 << NumImplicitCopyConstructors
827 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000828 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000829 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
830 << NumImplicitMoveConstructors
831 << " implicit move constructors created\n";
832 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
833 << NumImplicitCopyAssignmentOperators
834 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000835 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000836 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
837 << NumImplicitMoveAssignmentOperators
838 << " implicit move assignment operators created\n";
839 llvm::errs() << NumImplicitDestructorsDeclared << "/"
840 << NumImplicitDestructors
841 << " implicit destructors created\n";
842
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000843 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000844 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000845 ExternalSource->PrintStats();
846 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000847
Douglas Gregor5b11d492010-07-25 17:53:33 +0000848 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000849}
850
Alp Toker2dea15b2013-12-17 01:22:38 +0000851RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
852 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000853 SourceLocation Loc;
854 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +0000855 if (getLangOpts().CPlusPlus)
856 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
857 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000858 else
Alp Toker2dea15b2013-12-17 01:22:38 +0000859 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
860 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000861 NewDecl->setImplicit();
862 return NewDecl;
863}
864
865TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
866 StringRef Name) const {
867 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
868 TypedefDecl *NewDecl = TypedefDecl::Create(
869 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
870 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
871 NewDecl->setImplicit();
872 return NewDecl;
873}
874
Douglas Gregor801c99d2011-08-12 06:49:56 +0000875TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000876 if (!Int128Decl)
877 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000878 return Int128Decl;
879}
880
881TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000882 if (!UInt128Decl)
883 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000884 return UInt128Decl;
885}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000886
Nico Webere1687c52013-06-20 21:44:55 +0000887TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber5b0b46f2013-06-21 01:29:36 +0000888 assert(LangOpts.CPlusPlus && "should only be called for c++");
Alp Toker56b5cc92013-12-15 10:36:26 +0000889 if (!Float128StubDecl)
Alp Toker2dea15b2013-12-17 01:22:38 +0000890 Float128StubDecl = buildImplicitRecord("__float128");
Alp Toker56b5cc92013-12-15 10:36:26 +0000891
Nico Webere1687c52013-06-20 21:44:55 +0000892 return Float128StubDecl;
893}
894
John McCall48f2d582009-10-23 23:03:21 +0000895void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000896 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000897 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000898 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000899}
900
Douglas Gregore8bbc122011-09-02 00:18:52 +0000901void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
902 assert((!this->Target || this->Target == &Target) &&
903 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000904 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000905
Douglas Gregore8bbc122011-09-02 00:18:52 +0000906 this->Target = &Target;
907
908 ABI.reset(createCXXABI(Target));
909 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +0000910 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000911
Chris Lattner970e54e2006-11-12 00:37:36 +0000912 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000913 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000914
Chris Lattner970e54e2006-11-12 00:37:36 +0000915 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000916 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000917 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000918 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000919 InitBuiltinType(CharTy, BuiltinType::Char_S);
920 else
921 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000922 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000923 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
924 InitBuiltinType(ShortTy, BuiltinType::Short);
925 InitBuiltinType(IntTy, BuiltinType::Int);
926 InitBuiltinType(LongTy, BuiltinType::Long);
927 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000928
Chris Lattner970e54e2006-11-12 00:37:36 +0000929 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000930 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
931 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
932 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
933 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
934 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000935
Chris Lattner970e54e2006-11-12 00:37:36 +0000936 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000937 InitBuiltinType(FloatTy, BuiltinType::Float);
938 InitBuiltinType(DoubleTy, BuiltinType::Double);
939 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000940
Chris Lattnerf122cef2009-04-30 02:43:43 +0000941 // GNU extension, 128-bit integers.
942 InitBuiltinType(Int128Ty, BuiltinType::Int128);
943 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
944
Hans Wennborg0d81e012013-05-10 10:08:40 +0000945 // C++ 3.9.1p5
946 if (TargetInfo::isTypeSigned(Target.getWCharType()))
947 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
948 else // -fshort-wchar makes wchar_t be unsigned.
949 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
950 if (LangOpts.CPlusPlus && LangOpts.WChar)
951 WideCharTy = WCharTy;
952 else {
953 // C99 (or C++ using -fno-wchar).
954 WideCharTy = getFromTargetType(Target.getWCharType());
955 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000956
James Molloy36365542012-05-04 10:55:22 +0000957 WIntTy = getFromTargetType(Target.getWIntType());
958
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000959 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
960 InitBuiltinType(Char16Ty, BuiltinType::Char16);
961 else // C99
962 Char16Ty = getFromTargetType(Target.getChar16Type());
963
964 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
965 InitBuiltinType(Char32Ty, BuiltinType::Char32);
966 else // C99
967 Char32Ty = getFromTargetType(Target.getChar32Type());
968
Douglas Gregor4619e432008-12-05 23:32:09 +0000969 // Placeholder type for type-dependent expressions whose type is
970 // completely unknown. No code should ever check a type against
971 // DependentTy and users should never see it; however, it is here to
972 // help diagnose failures to properly check for type-dependent
973 // expressions.
974 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000975
John McCall36e7fe32010-10-12 00:20:44 +0000976 // Placeholder type for functions.
977 InitBuiltinType(OverloadTy, BuiltinType::Overload);
978
John McCall0009fcc2011-04-26 20:42:42 +0000979 // Placeholder type for bound members.
980 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
981
John McCall526ab472011-10-25 17:37:35 +0000982 // Placeholder type for pseudo-objects.
983 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
984
John McCall31996342011-04-07 08:22:57 +0000985 // "any" type; useful for debugger-like clients.
986 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
987
John McCall8a6b59a2011-10-17 18:09:15 +0000988 // Placeholder type for unbridged ARC casts.
989 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
990
Eli Friedman34866c72012-08-31 00:14:07 +0000991 // Placeholder type for builtin functions.
992 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
993
Chris Lattner970e54e2006-11-12 00:37:36 +0000994 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000995 FloatComplexTy = getComplexType(FloatTy);
996 DoubleComplexTy = getComplexType(DoubleTy);
997 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000998
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000999 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001000 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1001 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001002 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001003
1004 if (LangOpts.OpenCL) {
1005 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1006 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1007 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1008 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1009 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
1010 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001011
Guy Benyei61054192013-02-07 10:55:47 +00001012 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001013 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001014 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001015
1016 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001017 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1018 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001019
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001020 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001021
1022 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001023
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001024 // void * type
1025 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001026
1027 // nullptr type (C++0x 2.14.7)
1028 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001029
1030 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1031 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001032
1033 // Builtin type used to help define __builtin_va_list.
1034 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +00001035}
1036
David Blaikie9c902b52011-09-25 23:23:43 +00001037DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001038 return SourceMgr.getDiagnostics();
1039}
1040
Douglas Gregor561eceb2010-08-30 16:49:28 +00001041AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1042 AttrVec *&Result = DeclAttrs[D];
1043 if (!Result) {
1044 void *Mem = Allocate(sizeof(AttrVec));
1045 Result = new (Mem) AttrVec;
1046 }
1047
1048 return *Result;
1049}
1050
1051/// \brief Erase the attributes corresponding to the given declaration.
1052void ASTContext::eraseDeclAttrs(const Decl *D) {
1053 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1054 if (Pos != DeclAttrs.end()) {
1055 Pos->second->~AttrVec();
1056 DeclAttrs.erase(Pos);
1057 }
1058}
1059
Larisse Voufo39a1e502013-08-06 01:03:05 +00001060// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001061MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001062ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001063 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001064 return getTemplateOrSpecializationInfo(Var)
1065 .dyn_cast<MemberSpecializationInfo *>();
1066}
1067
1068ASTContext::TemplateOrSpecializationInfo
1069ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1070 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1071 TemplateOrInstantiation.find(Var);
1072 if (Pos == TemplateOrInstantiation.end())
1073 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001074
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001075 return Pos->second;
1076}
1077
Mike Stump11289f42009-09-09 15:08:12 +00001078void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001079ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001080 TemplateSpecializationKind TSK,
1081 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001082 assert(Inst->isStaticDataMember() && "Not a static data member");
1083 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001084 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1085 Tmpl, TSK, PointOfInstantiation));
1086}
1087
1088void
1089ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1090 TemplateOrSpecializationInfo TSI) {
1091 assert(!TemplateOrInstantiation[Inst] &&
1092 "Already noted what the variable was instantiated from");
1093 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001094}
1095
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001096FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1097 const FunctionDecl *FD){
1098 assert(FD && "Specialization is 0");
1099 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001100 = ClassScopeSpecializationPattern.find(FD);
1101 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001102 return 0;
1103
1104 return Pos->second;
1105}
1106
1107void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1108 FunctionDecl *Pattern) {
1109 assert(FD && "Specialization is 0");
1110 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001111 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001112}
1113
John McCalle61f2ba2009-11-18 02:36:19 +00001114NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001115ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001116 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001117 = InstantiatedFromUsingDecl.find(UUD);
1118 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001119 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001120
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001121 return Pos->second;
1122}
1123
1124void
John McCallb96ec562009-12-04 22:46:56 +00001125ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1126 assert((isa<UsingDecl>(Pattern) ||
1127 isa<UnresolvedUsingValueDecl>(Pattern) ||
1128 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1129 "pattern decl is not a using decl");
1130 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1131 InstantiatedFromUsingDecl[Inst] = Pattern;
1132}
1133
1134UsingShadowDecl *
1135ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1136 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1137 = InstantiatedFromUsingShadowDecl.find(Inst);
1138 if (Pos == InstantiatedFromUsingShadowDecl.end())
1139 return 0;
1140
1141 return Pos->second;
1142}
1143
1144void
1145ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1146 UsingShadowDecl *Pattern) {
1147 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1148 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001149}
1150
Anders Carlsson5da84842009-09-01 04:26:58 +00001151FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1152 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1153 = InstantiatedFromUnnamedFieldDecl.find(Field);
1154 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1155 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001156
Anders Carlsson5da84842009-09-01 04:26:58 +00001157 return Pos->second;
1158}
1159
1160void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1161 FieldDecl *Tmpl) {
1162 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1163 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1164 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1165 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001166
Anders Carlsson5da84842009-09-01 04:26:58 +00001167 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1168}
1169
Douglas Gregor832940b2010-03-02 23:58:15 +00001170ASTContext::overridden_cxx_method_iterator
1171ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1172 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001173 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001174 if (Pos == OverriddenMethods.end())
1175 return 0;
1176
1177 return Pos->second.begin();
1178}
1179
1180ASTContext::overridden_cxx_method_iterator
1181ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1182 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001183 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001184 if (Pos == OverriddenMethods.end())
1185 return 0;
1186
1187 return Pos->second.end();
1188}
1189
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001190unsigned
1191ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1192 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001193 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001194 if (Pos == OverriddenMethods.end())
1195 return 0;
1196
1197 return Pos->second.size();
1198}
1199
Douglas Gregor832940b2010-03-02 23:58:15 +00001200void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1201 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001202 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001203 OverriddenMethods[Method].push_back(Overridden);
1204}
1205
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001206void ASTContext::getOverriddenMethods(
1207 const NamedDecl *D,
1208 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001209 assert(D);
1210
1211 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001212 Overridden.append(overridden_methods_begin(CXXMethod),
1213 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001214 return;
1215 }
1216
1217 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1218 if (!Method)
1219 return;
1220
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001221 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1222 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001223 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001224}
1225
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001226void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1227 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1228 assert(!Import->isFromASTFile() && "Non-local import declaration");
1229 if (!FirstLocalImport) {
1230 FirstLocalImport = Import;
1231 LastLocalImport = Import;
1232 return;
1233 }
1234
1235 LastLocalImport->NextLocalImport = Import;
1236 LastLocalImport = Import;
1237}
1238
Chris Lattner53cfe802007-07-18 17:52:12 +00001239//===----------------------------------------------------------------------===//
1240// Type Sizing and Analysis
1241//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001242
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001243/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1244/// scalar floating point type.
1245const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001246 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001247 assert(BT && "Not a floating point type!");
1248 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001249 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001250 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001251 case BuiltinType::Float: return Target->getFloatFormat();
1252 case BuiltinType::Double: return Target->getDoubleFormat();
1253 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001254 }
1255}
1256
Rafael Espindola71eccb32013-08-08 19:53:46 +00001257CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001258 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001259
John McCall94268702010-10-08 18:24:19 +00001260 bool UseAlignAttrOnly = false;
1261 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1262 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001263
John McCall94268702010-10-08 18:24:19 +00001264 // __attribute__((aligned)) can increase or decrease alignment
1265 // *except* on a struct or struct member, where it only increases
1266 // alignment unless 'packed' is also specified.
1267 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001268 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001269 // ignore that possibility; Sema should diagnose it.
1270 if (isa<FieldDecl>(D)) {
1271 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1272 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1273 } else {
1274 UseAlignAttrOnly = true;
1275 }
1276 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001277 else if (isa<FieldDecl>(D))
1278 UseAlignAttrOnly =
1279 D->hasAttr<PackedAttr>() ||
1280 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001281
John McCall4e819612011-01-20 07:57:12 +00001282 // If we're using the align attribute only, just ignore everything
1283 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001284 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001285 // do nothing
1286
John McCall94268702010-10-08 18:24:19 +00001287 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001288 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001289 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001290 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001291 T = RT->getPointeeType();
1292 else
1293 T = getPointerType(RT->getPointeeType());
1294 }
1295 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001296 // Adjust alignments of declarations with array type by the
1297 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001298 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001299 unsigned MinWidth = Target->getLargeArrayMinWidth();
1300 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001301 if (isa<VariableArrayType>(arrayType))
1302 Align = std::max(Align, Target->getLargeArrayAlign());
1303 else if (isa<ConstantArrayType>(arrayType) &&
1304 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1305 Align = std::max(Align, Target->getLargeArrayAlign());
1306 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001307
John McCall33ddac02011-01-19 10:06:00 +00001308 // Walk through any array types while we're at it.
1309 T = getBaseElementType(arrayType);
1310 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001311 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001312 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1313 if (VD->hasGlobalStorage())
1314 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1315 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001316 }
John McCall4e819612011-01-20 07:57:12 +00001317
1318 // Fields can be subject to extra alignment constraints, like if
1319 // the field is packed, the struct is packed, or the struct has a
1320 // a max-field-alignment constraint (#pragma pack). So calculate
1321 // the actual alignment of the field within the struct, and then
1322 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001323 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1324 const RecordDecl *Parent = Field->getParent();
1325 // We can only produce a sensible answer if the record is valid.
1326 if (!Parent->isInvalidDecl()) {
1327 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001328
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001329 // Start with the record's overall alignment.
1330 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001331
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001332 // Use the GCD of that and the offset within the record.
1333 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1334 if (Offset > 0) {
1335 // Alignment is always a power of 2, so the GCD will be a power of 2,
1336 // which means we get to do this crazy thing instead of Euclid's.
1337 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1338 if (LowBitOfOffset < FieldAlign)
1339 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1340 }
1341
1342 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001343 }
Charles Davis3fc51072010-02-23 04:52:00 +00001344 }
Chris Lattner68061312009-01-24 21:53:27 +00001345 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001346
Ken Dyckcc56c542011-01-15 18:38:59 +00001347 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001348}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001349
John McCallf1249922012-08-21 04:10:00 +00001350// getTypeInfoDataSizeInChars - Return the size of a type, in
1351// chars. If the type is a record, its data size is returned. This is
1352// the size of the memcpy that's performed when assigning this type
1353// using a trivial copy/move assignment operator.
1354std::pair<CharUnits, CharUnits>
1355ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1356 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1357
1358 // In C++, objects can sometimes be allocated into the tail padding
1359 // of a base-class subobject. We decide whether that's possible
1360 // during class layout, so here we can just trust the layout results.
1361 if (getLangOpts().CPlusPlus) {
1362 if (const RecordType *RT = T->getAs<RecordType>()) {
1363 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1364 sizeAndAlign.first = layout.getDataSize();
1365 }
1366 }
1367
1368 return sizeAndAlign;
1369}
1370
Richard Trieu04d2d942013-05-14 21:59:17 +00001371/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1372/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1373std::pair<CharUnits, CharUnits>
1374static getConstantArrayInfoInChars(const ASTContext &Context,
1375 const ConstantArrayType *CAT) {
1376 std::pair<CharUnits, CharUnits> EltInfo =
1377 Context.getTypeInfoInChars(CAT->getElementType());
1378 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001379 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1380 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001381 "Overflow in array type char size evaluation");
1382 uint64_t Width = EltInfo.first.getQuantity() * Size;
1383 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001384 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1385 Context.getTargetInfo().getPointerWidth(0) == 64)
1386 Width = llvm::RoundUpToAlignment(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001387 return std::make_pair(CharUnits::fromQuantity(Width),
1388 CharUnits::fromQuantity(Align));
1389}
1390
John McCall87fe5d52010-05-20 01:18:31 +00001391std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001392ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001393 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1394 return getConstantArrayInfoInChars(*this, CAT);
John McCall87fe5d52010-05-20 01:18:31 +00001395 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +00001396 return std::make_pair(toCharUnitsFromBits(Info.first),
1397 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +00001398}
1399
1400std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001401ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001402 return getTypeInfoInChars(T.getTypePtr());
1403}
1404
Daniel Dunbarc6475872012-03-09 04:12:54 +00001405std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1406 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1407 if (it != MemoizedTypeInfo.end())
1408 return it->second;
1409
1410 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1411 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1412 return Info;
1413}
1414
1415/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1416/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001417///
1418/// FIXME: Pointers into different addr spaces could have different sizes and
1419/// alignment requirements: getPointerInfo should take an AddrSpace, this
1420/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001421std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001422ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001423 uint64_t Width=0;
1424 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001425 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001426#define TYPE(Class, Base)
1427#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001428#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001429#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001430#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1431 case Type::Class: \
1432 assert(!T->isDependentType() && "should not see dependent types here"); \
1433 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001434#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001435 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001436
Chris Lattner355332d2007-07-13 22:27:08 +00001437 case Type::FunctionNoProto:
1438 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001439 // GCC extension: alignof(function) = 32 bits
1440 Width = 0;
1441 Align = 32;
1442 break;
1443
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001444 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001445 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001446 Width = 0;
1447 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1448 break;
1449
Steve Naroff5c131802007-08-30 01:06:46 +00001450 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001451 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001452
Chris Lattner37e05872008-03-05 18:54:05 +00001453 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001454 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001455 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1456 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001457 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001458 Align = EltInfo.second;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001459 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1460 getTargetInfo().getPointerWidth(0) == 64)
1461 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001462 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001463 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001464 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001465 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001466 const VectorType *VT = cast<VectorType>(T);
1467 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1468 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001469 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001470 // If the alignment is not a power of 2, round up to the next power of 2.
1471 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001472 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001473 Align = llvm::NextPowerOf2(Align);
1474 Width = llvm::RoundUpToAlignment(Width, Align);
1475 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001476 // Adjust the alignment based on the target max.
1477 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1478 if (TargetVectorAlign && TargetVectorAlign < Align)
1479 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001480 break;
1481 }
Chris Lattner647fb222007-07-18 18:26:58 +00001482
Chris Lattner7570e9c2008-03-08 08:52:55 +00001483 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001484 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001485 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001486 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001487 // GCC extension: alignof(void) = 8 bits.
1488 Width = 0;
1489 Align = 8;
1490 break;
1491
Chris Lattner6a4f7452007-12-19 19:23:28 +00001492 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001493 Width = Target->getBoolWidth();
1494 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001495 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001496 case BuiltinType::Char_S:
1497 case BuiltinType::Char_U:
1498 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001499 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001500 Width = Target->getCharWidth();
1501 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001502 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001503 case BuiltinType::WChar_S:
1504 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001505 Width = Target->getWCharWidth();
1506 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001507 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001508 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001509 Width = Target->getChar16Width();
1510 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001511 break;
1512 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001513 Width = Target->getChar32Width();
1514 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001515 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001516 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001517 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001518 Width = Target->getShortWidth();
1519 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001520 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001521 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001522 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001523 Width = Target->getIntWidth();
1524 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001525 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001526 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001527 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001528 Width = Target->getLongWidth();
1529 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001530 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001531 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001532 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001533 Width = Target->getLongLongWidth();
1534 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001535 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001536 case BuiltinType::Int128:
1537 case BuiltinType::UInt128:
1538 Width = 128;
1539 Align = 128; // int128_t is 128-bit aligned on all targets.
1540 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001541 case BuiltinType::Half:
1542 Width = Target->getHalfWidth();
1543 Align = Target->getHalfAlign();
1544 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001545 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001546 Width = Target->getFloatWidth();
1547 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001548 break;
1549 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001550 Width = Target->getDoubleWidth();
1551 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001552 break;
1553 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001554 Width = Target->getLongDoubleWidth();
1555 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001556 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001557 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001558 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1559 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001560 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001561 case BuiltinType::ObjCId:
1562 case BuiltinType::ObjCClass:
1563 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001564 Width = Target->getPointerWidth(0);
1565 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001566 break;
Guy Benyei61054192013-02-07 10:55:47 +00001567 case BuiltinType::OCLSampler:
1568 // Samplers are modeled as integers.
1569 Width = Target->getIntWidth();
1570 Align = Target->getIntAlign();
1571 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001572 case BuiltinType::OCLEvent:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001573 case BuiltinType::OCLImage1d:
1574 case BuiltinType::OCLImage1dArray:
1575 case BuiltinType::OCLImage1dBuffer:
1576 case BuiltinType::OCLImage2d:
1577 case BuiltinType::OCLImage2dArray:
1578 case BuiltinType::OCLImage3d:
1579 // Currently these types are pointers to opaque types.
1580 Width = Target->getPointerWidth(0);
1581 Align = Target->getPointerAlign(0);
1582 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001583 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001584 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001585 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001586 Width = Target->getPointerWidth(0);
1587 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001588 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001589 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001590 unsigned AS = getTargetAddressSpace(
1591 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001592 Width = Target->getPointerWidth(AS);
1593 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001594 break;
1595 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001596 case Type::LValueReference:
1597 case Type::RValueReference: {
1598 // alignof and sizeof should never enter this code path here, so we go
1599 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001600 unsigned AS = getTargetAddressSpace(
1601 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001602 Width = Target->getPointerWidth(AS);
1603 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001604 break;
1605 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001606 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001607 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001608 Width = Target->getPointerWidth(AS);
1609 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001610 break;
1611 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001612 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001613 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001614 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001615 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001616 }
Chris Lattner647fb222007-07-18 18:26:58 +00001617 case Type::Complex: {
1618 // Complex types have the same alignment as their elements, but twice the
1619 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001620 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001621 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001622 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001623 Align = EltInfo.second;
1624 break;
1625 }
John McCall8b07ec22010-05-15 11:32:37 +00001626 case Type::ObjCObject:
1627 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001628 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001629 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001630 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001631 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001632 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001633 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001634 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001635 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001636 break;
1637 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001638 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001639 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001640 const TagType *TT = cast<TagType>(T);
1641
1642 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001643 Width = 8;
1644 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001645 break;
1646 }
Mike Stump11289f42009-09-09 15:08:12 +00001647
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001648 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001649 return getTypeInfo(ET->getDecl()->getIntegerType());
1650
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001651 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001652 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001653 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001654 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001655 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001656 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001657
Chris Lattner63d2b362009-10-22 05:17:15 +00001658 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001659 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1660 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001661
Richard Smith30482bc2011-02-20 03:19:35 +00001662 case Type::Auto: {
1663 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001664 assert(!A->getDeducedType().isNull() &&
1665 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001666 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001667 }
1668
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001669 case Type::Paren:
1670 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1671
Douglas Gregoref462e62009-04-30 17:32:17 +00001672 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001673 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001674 std::pair<uint64_t, unsigned> Info
1675 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001676 // If the typedef has an aligned attribute on it, it overrides any computed
1677 // alignment we have. This violates the GCC documentation (which says that
1678 // attribute(aligned) can only round up) but matches its implementation.
1679 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1680 Align = AttrAlign;
1681 else
1682 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001683 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001684 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001685 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001686
Abramo Bagnara6150c882010-05-11 21:36:43 +00001687 case Type::Elaborated:
1688 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001689
John McCall81904512011-01-06 01:58:22 +00001690 case Type::Attributed:
1691 return getTypeInfo(
1692 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1693
Eli Friedman0dfb8892011-10-06 23:00:33 +00001694 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001695 // Start with the base type information.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001696 std::pair<uint64_t, unsigned> Info
1697 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1698 Width = Info.first;
1699 Align = Info.second;
John McCalla8ec7eb2013-03-07 21:37:17 +00001700
1701 // If the size of the type doesn't exceed the platform's max
1702 // atomic promotion width, make the size and alignment more
1703 // favorable to atomic operations:
1704 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1705 // Round the size up to a power of 2.
1706 if (!llvm::isPowerOf2_64(Width))
1707 Width = llvm::NextPowerOf2(Width);
1708
1709 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001710 Align = static_cast<unsigned>(Width);
1711 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001712 }
1713
Douglas Gregoref462e62009-04-30 17:32:17 +00001714 }
Mike Stump11289f42009-09-09 15:08:12 +00001715
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001716 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001717 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001718}
1719
Ken Dyckcc56c542011-01-15 18:38:59 +00001720/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1721CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1722 return CharUnits::fromQuantity(BitSize / getCharWidth());
1723}
1724
Ken Dyckb0fcc592011-02-11 01:54:29 +00001725/// toBits - Convert a size in characters to a size in characters.
1726int64_t ASTContext::toBits(CharUnits CharSize) const {
1727 return CharSize.getQuantity() * getCharWidth();
1728}
1729
Ken Dyck8c89d592009-12-22 14:23:30 +00001730/// getTypeSizeInChars - Return the size of the specified type, in characters.
1731/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001732CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001733 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001734}
Jay Foad39c79802011-01-12 09:06:06 +00001735CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001736 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001737}
1738
Ken Dycka6046ab2010-01-26 17:25:18 +00001739/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001740/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001741CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001742 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001743}
Jay Foad39c79802011-01-12 09:06:06 +00001744CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001745 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001746}
1747
Chris Lattnera3402cd2009-01-27 18:08:34 +00001748/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1749/// type for the current target in bits. This can be different than the ABI
1750/// alignment in cases where it is beneficial for performance to overalign
1751/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001752unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001753 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001754
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001755 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1756 return ABIAlign; // Never overalign on XCore.
1757
David Majnemer8b6bd572014-02-24 23:34:17 +00001758 const TypedefType *TT = T->getAs<TypedefType>();
1759
Eli Friedman7ab09572009-05-25 21:27:19 +00001760 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00001761 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001762 T = CT->getElementType().getTypePtr();
1763 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001764 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1765 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00001766 // Don't increase the alignment if an alignment attribute was specified on a
1767 // typedef declaration.
1768 if (!TT || !TT->getDecl()->getMaxAlignment())
1769 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00001770
Chris Lattnera3402cd2009-01-27 18:08:34 +00001771 return ABIAlign;
1772}
1773
Ulrich Weigandfa806422013-05-06 16:23:57 +00001774/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1775/// to a global variable of the specified type.
1776unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1777 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1778}
1779
1780/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1781/// should be given to a global variable of the specified type.
1782CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1783 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1784}
1785
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001786/// DeepCollectObjCIvars -
1787/// This routine first collects all declared, but not synthesized, ivars in
1788/// super class and then collects all ivars, including those synthesized for
1789/// current class. This routine is used for implementation of current class
1790/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001791///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001792void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1793 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001794 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001795 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1796 DeepCollectObjCIvars(SuperClass, false, Ivars);
1797 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00001798 for (const auto *I : OI->ivars())
1799 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001800 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001801 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001802 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001803 Iv= Iv->getNextIvar())
1804 Ivars.push_back(Iv);
1805 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001806}
1807
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001808/// CollectInheritedProtocols - Collect all protocols in current class and
1809/// those inherited by it.
1810void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001811 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001812 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001813 // We can use protocol_iterator here instead of
1814 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001815 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001816 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001817 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001818 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001819 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001820 CollectInheritedProtocols(*P, Protocols);
1821 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001822 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001823
1824 // Categories of this Interface.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001825 for (ObjCInterfaceDecl::visible_categories_iterator
1826 Cat = OI->visible_categories_begin(),
1827 CatEnd = OI->visible_categories_end();
1828 Cat != CatEnd; ++Cat) {
1829 CollectInheritedProtocols(*Cat, Protocols);
1830 }
1831
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001832 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1833 while (SD) {
1834 CollectInheritedProtocols(SD, Protocols);
1835 SD = SD->getSuperClass();
1836 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001837 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001838 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001839 PE = OC->protocol_end(); P != PE; ++P) {
1840 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001841 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001842 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1843 PE = Proto->protocol_end(); P != PE; ++P)
1844 CollectInheritedProtocols(*P, Protocols);
1845 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001846 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001847 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1848 PE = OP->protocol_end(); P != PE; ++P) {
1849 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001850 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001851 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1852 PE = Proto->protocol_end(); P != PE; ++P)
1853 CollectInheritedProtocols(*P, Protocols);
1854 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001855 }
1856}
1857
Jay Foad39c79802011-01-12 09:06:06 +00001858unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001859 unsigned count = 0;
1860 // Count ivars declared in class extension.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001861 for (ObjCInterfaceDecl::known_extensions_iterator
1862 Ext = OI->known_extensions_begin(),
1863 ExtEnd = OI->known_extensions_end();
1864 Ext != ExtEnd; ++Ext) {
1865 count += Ext->ivar_size();
1866 }
1867
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001868 // Count ivar defined in this class's implementation. This
1869 // includes synthesized ivars.
1870 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001871 count += ImplDecl->ivar_size();
1872
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001873 return count;
1874}
1875
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001876bool ASTContext::isSentinelNullExpr(const Expr *E) {
1877 if (!E)
1878 return false;
1879
1880 // nullptr_t is always treated as null.
1881 if (E->getType()->isNullPtrType()) return true;
1882
1883 if (E->getType()->isAnyPointerType() &&
1884 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1885 Expr::NPC_ValueDependentIsNull))
1886 return true;
1887
1888 // Unfortunately, __null has type 'int'.
1889 if (isa<GNUNullExpr>(E)) return true;
1890
1891 return false;
1892}
1893
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001894/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1895ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1896 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1897 I = ObjCImpls.find(D);
1898 if (I != ObjCImpls.end())
1899 return cast<ObjCImplementationDecl>(I->second);
1900 return 0;
1901}
1902/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1903ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1904 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1905 I = ObjCImpls.find(D);
1906 if (I != ObjCImpls.end())
1907 return cast<ObjCCategoryImplDecl>(I->second);
1908 return 0;
1909}
1910
1911/// \brief Set the implementation of ObjCInterfaceDecl.
1912void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1913 ObjCImplementationDecl *ImplD) {
1914 assert(IFaceD && ImplD && "Passed null params");
1915 ObjCImpls[IFaceD] = ImplD;
1916}
1917/// \brief Set the implementation of ObjCCategoryDecl.
1918void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1919 ObjCCategoryImplDecl *ImplD) {
1920 assert(CatD && ImplD && "Passed null params");
1921 ObjCImpls[CatD] = ImplD;
1922}
1923
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001924const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1925 const NamedDecl *ND) const {
1926 if (const ObjCInterfaceDecl *ID =
1927 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001928 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001929 if (const ObjCCategoryDecl *CD =
1930 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001931 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001932 if (const ObjCImplDecl *IMD =
1933 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001934 return IMD->getClassInterface();
1935
1936 return 0;
1937}
1938
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001939/// \brief Get the copy initialization expression of VarDecl,or NULL if
1940/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001941Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001942 assert(VD && "Passed null params");
1943 assert(VD->hasAttr<BlocksAttr>() &&
1944 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001945 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001946 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001947 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1948}
1949
1950/// \brief Set the copy inialization expression of a block var decl.
1951void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1952 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001953 assert(VD->hasAttr<BlocksAttr>() &&
1954 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001955 BlockVarCopyInits[VD] = Init;
1956}
1957
John McCallbcd03502009-12-07 02:54:59 +00001958TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001959 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001960 if (!DataSize)
1961 DataSize = TypeLoc::getFullDataSizeForType(T);
1962 else
1963 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001964 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001965
John McCallbcd03502009-12-07 02:54:59 +00001966 TypeSourceInfo *TInfo =
1967 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1968 new (TInfo) TypeSourceInfo(T);
1969 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001970}
1971
John McCallbcd03502009-12-07 02:54:59 +00001972TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001973 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001974 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001975 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001976 return DI;
1977}
1978
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001979const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001980ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001981 return getObjCLayout(D, 0);
1982}
1983
1984const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001985ASTContext::getASTObjCImplementationLayout(
1986 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001987 return getObjCLayout(D->getClassInterface(), D);
1988}
1989
Chris Lattner983a8bb2007-07-13 22:13:22 +00001990//===----------------------------------------------------------------------===//
1991// Type creation/memoization methods
1992//===----------------------------------------------------------------------===//
1993
Jay Foad39c79802011-01-12 09:06:06 +00001994QualType
John McCall33ddac02011-01-19 10:06:00 +00001995ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1996 unsigned fastQuals = quals.getFastQualifiers();
1997 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001998
1999 // Check if we've already instantiated this type.
2000 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002001 ExtQuals::Profile(ID, baseType, quals);
2002 void *insertPos = 0;
2003 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2004 assert(eq->getQualifiers() == quals);
2005 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002006 }
2007
John McCall33ddac02011-01-19 10:06:00 +00002008 // If the base type is not canonical, make the appropriate canonical type.
2009 QualType canon;
2010 if (!baseType->isCanonicalUnqualified()) {
2011 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002012 canonSplit.Quals.addConsistentQualifiers(quals);
2013 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002014
2015 // Re-find the insert position.
2016 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2017 }
2018
2019 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2020 ExtQualNodes.InsertNode(eq, insertPos);
2021 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002022}
2023
Jay Foad39c79802011-01-12 09:06:06 +00002024QualType
2025ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002026 QualType CanT = getCanonicalType(T);
2027 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002028 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002029
John McCall8ccfcb52009-09-24 19:53:00 +00002030 // If we are composing extended qualifiers together, merge together
2031 // into one ExtQuals node.
2032 QualifierCollector Quals;
2033 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002034
John McCall8ccfcb52009-09-24 19:53:00 +00002035 // If this type already has an address space specified, it cannot get
2036 // another one.
2037 assert(!Quals.hasAddressSpace() &&
2038 "Type cannot be in multiple addr spaces!");
2039 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002040
John McCall8ccfcb52009-09-24 19:53:00 +00002041 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002042}
2043
Chris Lattnerd60183d2009-02-18 22:53:11 +00002044QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002045 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002046 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002047 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002048 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002049
John McCall53fa7142010-12-24 02:08:15 +00002050 if (const PointerType *ptr = T->getAs<PointerType>()) {
2051 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002052 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002053 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2054 return getPointerType(ResultType);
2055 }
2056 }
Mike Stump11289f42009-09-09 15:08:12 +00002057
John McCall8ccfcb52009-09-24 19:53:00 +00002058 // If we are composing extended qualifiers together, merge together
2059 // into one ExtQuals node.
2060 QualifierCollector Quals;
2061 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002062
John McCall8ccfcb52009-09-24 19:53:00 +00002063 // If this type already has an ObjCGC specified, it cannot get
2064 // another one.
2065 assert(!Quals.hasObjCGCAttr() &&
2066 "Type cannot have multiple ObjCGCs!");
2067 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002068
John McCall8ccfcb52009-09-24 19:53:00 +00002069 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002070}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002071
John McCall4f5019e2010-12-19 02:44:49 +00002072const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2073 FunctionType::ExtInfo Info) {
2074 if (T->getExtInfo() == Info)
2075 return T;
2076
2077 QualType Result;
2078 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002079 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002080 } else {
2081 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2082 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2083 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002084 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002085 }
2086
2087 return cast<FunctionType>(Result.getTypePtr());
2088}
2089
Richard Smith2a7d4812013-05-04 07:00:32 +00002090void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2091 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002092 FD = FD->getMostRecentDecl();
2093 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002094 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2095 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002096 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002097 if (FunctionDecl *Next = FD->getPreviousDecl())
2098 FD = Next;
2099 else
2100 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002101 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002102 if (ASTMutationListener *L = getASTMutationListener())
2103 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002104}
2105
Chris Lattnerc6395932007-06-22 20:56:16 +00002106/// getComplexType - Return the uniqued reference to the type for a complex
2107/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002108QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002109 // Unique pointers, to guarantee there is only one pointer of a particular
2110 // structure.
2111 llvm::FoldingSetNodeID ID;
2112 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002113
Chris Lattnerc6395932007-06-22 20:56:16 +00002114 void *InsertPos = 0;
2115 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2116 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002117
Chris Lattnerc6395932007-06-22 20:56:16 +00002118 // If the pointee type isn't canonical, this won't be a canonical type either,
2119 // so fill in the canonical type field.
2120 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002121 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002122 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002123
Chris Lattnerc6395932007-06-22 20:56:16 +00002124 // Get the new insert position for the node we care about.
2125 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002126 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002127 }
John McCall90d1c2d2009-09-24 23:30:46 +00002128 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002129 Types.push_back(New);
2130 ComplexTypes.InsertNode(New, InsertPos);
2131 return QualType(New, 0);
2132}
2133
Chris Lattner970e54e2006-11-12 00:37:36 +00002134/// getPointerType - Return the uniqued reference to the type for a pointer to
2135/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002136QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002137 // Unique pointers, to guarantee there is only one pointer of a particular
2138 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002139 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002140 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002141
Chris Lattner67521df2007-01-27 01:29:36 +00002142 void *InsertPos = 0;
2143 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002144 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002145
Chris Lattner7ccecb92006-11-12 08:50:50 +00002146 // If the pointee type isn't canonical, this won't be a canonical type either,
2147 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002148 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002149 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002150 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002151
Bob Wilsonc8541f22013-03-15 17:12:43 +00002152 // Get the new insert position for the node we care about.
2153 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2154 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2155 }
John McCall90d1c2d2009-09-24 23:30:46 +00002156 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002157 Types.push_back(New);
2158 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002159 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002160}
2161
Reid Kleckner0503a872013-12-05 01:23:43 +00002162QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2163 llvm::FoldingSetNodeID ID;
2164 AdjustedType::Profile(ID, Orig, New);
2165 void *InsertPos = 0;
2166 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2167 if (AT)
2168 return QualType(AT, 0);
2169
2170 QualType Canonical = getCanonicalType(New);
2171
2172 // Get the new insert position for the node we care about.
2173 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2174 assert(AT == 0 && "Shouldn't be in the map!");
2175
2176 AT = new (*this, TypeAlignment)
2177 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2178 Types.push_back(AT);
2179 AdjustedTypes.InsertNode(AT, InsertPos);
2180 return QualType(AT, 0);
2181}
2182
Reid Kleckner8a365022013-06-24 17:51:48 +00002183QualType ASTContext::getDecayedType(QualType T) const {
2184 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2185
Reid Kleckner8a365022013-06-24 17:51:48 +00002186 QualType Decayed;
2187
2188 // C99 6.7.5.3p7:
2189 // A declaration of a parameter as "array of type" shall be
2190 // adjusted to "qualified pointer to type", where the type
2191 // qualifiers (if any) are those specified within the [ and ] of
2192 // the array type derivation.
2193 if (T->isArrayType())
2194 Decayed = getArrayDecayedType(T);
2195
2196 // C99 6.7.5.3p8:
2197 // A declaration of a parameter as "function returning type"
2198 // shall be adjusted to "pointer to function returning type", as
2199 // in 6.3.2.1.
2200 if (T->isFunctionType())
2201 Decayed = getPointerType(T);
2202
Reid Kleckner0503a872013-12-05 01:23:43 +00002203 llvm::FoldingSetNodeID ID;
2204 AdjustedType::Profile(ID, T, Decayed);
2205 void *InsertPos = 0;
2206 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2207 if (AT)
2208 return QualType(AT, 0);
2209
Reid Kleckner8a365022013-06-24 17:51:48 +00002210 QualType Canonical = getCanonicalType(Decayed);
2211
2212 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002213 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2214 assert(AT == 0 && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002215
Reid Kleckner0503a872013-12-05 01:23:43 +00002216 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2217 Types.push_back(AT);
2218 AdjustedTypes.InsertNode(AT, InsertPos);
2219 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002220}
2221
Mike Stump11289f42009-09-09 15:08:12 +00002222/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002223/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002224QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002225 assert(T->isFunctionType() && "block of function types only");
2226 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002227 // structure.
2228 llvm::FoldingSetNodeID ID;
2229 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002230
Steve Naroffec33ed92008-08-27 16:04:49 +00002231 void *InsertPos = 0;
2232 if (BlockPointerType *PT =
2233 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2234 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002235
2236 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002237 // type either so fill in the canonical type field.
2238 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002239 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002240 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002241
Steve Naroffec33ed92008-08-27 16:04:49 +00002242 // Get the new insert position for the node we care about.
2243 BlockPointerType *NewIP =
2244 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002245 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002246 }
John McCall90d1c2d2009-09-24 23:30:46 +00002247 BlockPointerType *New
2248 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002249 Types.push_back(New);
2250 BlockPointerTypes.InsertNode(New, InsertPos);
2251 return QualType(New, 0);
2252}
2253
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002254/// getLValueReferenceType - Return the uniqued reference to the type for an
2255/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002256QualType
2257ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002258 assert(getCanonicalType(T) != OverloadTy &&
2259 "Unresolved overloaded function type");
2260
Bill Wendling3708c182007-05-27 10:15:43 +00002261 // Unique pointers, to guarantee there is only one pointer of a particular
2262 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002263 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002264 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002265
2266 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002267 if (LValueReferenceType *RT =
2268 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002269 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002270
John McCallfc93cf92009-10-22 22:37:11 +00002271 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2272
Bill Wendling3708c182007-05-27 10:15:43 +00002273 // If the referencee type isn't canonical, this won't be a canonical type
2274 // either, so fill in the canonical type field.
2275 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002276 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2277 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2278 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002279
Bill Wendling3708c182007-05-27 10:15:43 +00002280 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002281 LValueReferenceType *NewIP =
2282 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002283 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002284 }
2285
John McCall90d1c2d2009-09-24 23:30:46 +00002286 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002287 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2288 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002289 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002290 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002291
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002292 return QualType(New, 0);
2293}
2294
2295/// getRValueReferenceType - Return the uniqued reference to the type for an
2296/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002297QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002298 // Unique pointers, to guarantee there is only one pointer of a particular
2299 // structure.
2300 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002301 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002302
2303 void *InsertPos = 0;
2304 if (RValueReferenceType *RT =
2305 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2306 return QualType(RT, 0);
2307
John McCallfc93cf92009-10-22 22:37:11 +00002308 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2309
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002310 // If the referencee type isn't canonical, this won't be a canonical type
2311 // either, so fill in the canonical type field.
2312 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002313 if (InnerRef || !T.isCanonical()) {
2314 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2315 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002316
2317 // Get the new insert position for the node we care about.
2318 RValueReferenceType *NewIP =
2319 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002320 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002321 }
2322
John McCall90d1c2d2009-09-24 23:30:46 +00002323 RValueReferenceType *New
2324 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002325 Types.push_back(New);
2326 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002327 return QualType(New, 0);
2328}
2329
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002330/// getMemberPointerType - Return the uniqued reference to the type for a
2331/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002332QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002333 // Unique pointers, to guarantee there is only one pointer of a particular
2334 // structure.
2335 llvm::FoldingSetNodeID ID;
2336 MemberPointerType::Profile(ID, T, Cls);
2337
2338 void *InsertPos = 0;
2339 if (MemberPointerType *PT =
2340 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2341 return QualType(PT, 0);
2342
2343 // If the pointee or class type isn't canonical, this won't be a canonical
2344 // type either, so fill in the canonical type field.
2345 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002346 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002347 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2348
2349 // Get the new insert position for the node we care about.
2350 MemberPointerType *NewIP =
2351 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002352 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002353 }
John McCall90d1c2d2009-09-24 23:30:46 +00002354 MemberPointerType *New
2355 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002356 Types.push_back(New);
2357 MemberPointerTypes.InsertNode(New, InsertPos);
2358 return QualType(New, 0);
2359}
2360
Mike Stump11289f42009-09-09 15:08:12 +00002361/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002362/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002363QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002364 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002365 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002366 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002367 assert((EltTy->isDependentType() ||
2368 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002369 "Constant array of VLAs is illegal!");
2370
Chris Lattnere2df3f92009-05-13 04:12:56 +00002371 // Convert the array size into a canonical width matching the pointer size for
2372 // the target.
2373 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002374 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002375 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002376
Chris Lattner23b7eb62007-06-15 23:05:46 +00002377 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002378 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002379
Chris Lattner36f8e652007-01-27 08:31:04 +00002380 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002381 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002382 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002383 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002384
John McCall33ddac02011-01-19 10:06:00 +00002385 // If the element type isn't canonical or has qualifiers, this won't
2386 // be a canonical type either, so fill in the canonical type field.
2387 QualType Canon;
2388 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2389 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002390 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002391 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002392 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002393
Chris Lattner36f8e652007-01-27 08:31:04 +00002394 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002395 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002396 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002397 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002398 }
Mike Stump11289f42009-09-09 15:08:12 +00002399
John McCall90d1c2d2009-09-24 23:30:46 +00002400 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002401 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002402 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002403 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002404 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002405}
2406
John McCall06549462011-01-18 08:40:38 +00002407/// getVariableArrayDecayedType - Turns the given type, which may be
2408/// variably-modified, into the corresponding type with all the known
2409/// sizes replaced with [*].
2410QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2411 // Vastly most common case.
2412 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002413
John McCall06549462011-01-18 08:40:38 +00002414 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002415
John McCall06549462011-01-18 08:40:38 +00002416 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002417 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002418 switch (ty->getTypeClass()) {
2419#define TYPE(Class, Base)
2420#define ABSTRACT_TYPE(Class, Base)
2421#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2422#include "clang/AST/TypeNodes.def"
2423 llvm_unreachable("didn't desugar past all non-canonical types?");
2424
2425 // These types should never be variably-modified.
2426 case Type::Builtin:
2427 case Type::Complex:
2428 case Type::Vector:
2429 case Type::ExtVector:
2430 case Type::DependentSizedExtVector:
2431 case Type::ObjCObject:
2432 case Type::ObjCInterface:
2433 case Type::ObjCObjectPointer:
2434 case Type::Record:
2435 case Type::Enum:
2436 case Type::UnresolvedUsing:
2437 case Type::TypeOfExpr:
2438 case Type::TypeOf:
2439 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002440 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002441 case Type::DependentName:
2442 case Type::InjectedClassName:
2443 case Type::TemplateSpecialization:
2444 case Type::DependentTemplateSpecialization:
2445 case Type::TemplateTypeParm:
2446 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002447 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002448 case Type::PackExpansion:
2449 llvm_unreachable("type should never be variably-modified");
2450
2451 // These types can be variably-modified but should never need to
2452 // further decay.
2453 case Type::FunctionNoProto:
2454 case Type::FunctionProto:
2455 case Type::BlockPointer:
2456 case Type::MemberPointer:
2457 return type;
2458
2459 // These types can be variably-modified. All these modifications
2460 // preserve structure except as noted by comments.
2461 // TODO: if we ever care about optimizing VLAs, there are no-op
2462 // optimizations available here.
2463 case Type::Pointer:
2464 result = getPointerType(getVariableArrayDecayedType(
2465 cast<PointerType>(ty)->getPointeeType()));
2466 break;
2467
2468 case Type::LValueReference: {
2469 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2470 result = getLValueReferenceType(
2471 getVariableArrayDecayedType(lv->getPointeeType()),
2472 lv->isSpelledAsLValue());
2473 break;
2474 }
2475
2476 case Type::RValueReference: {
2477 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2478 result = getRValueReferenceType(
2479 getVariableArrayDecayedType(lv->getPointeeType()));
2480 break;
2481 }
2482
Eli Friedman0dfb8892011-10-06 23:00:33 +00002483 case Type::Atomic: {
2484 const AtomicType *at = cast<AtomicType>(ty);
2485 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2486 break;
2487 }
2488
John McCall06549462011-01-18 08:40:38 +00002489 case Type::ConstantArray: {
2490 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2491 result = getConstantArrayType(
2492 getVariableArrayDecayedType(cat->getElementType()),
2493 cat->getSize(),
2494 cat->getSizeModifier(),
2495 cat->getIndexTypeCVRQualifiers());
2496 break;
2497 }
2498
2499 case Type::DependentSizedArray: {
2500 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2501 result = getDependentSizedArrayType(
2502 getVariableArrayDecayedType(dat->getElementType()),
2503 dat->getSizeExpr(),
2504 dat->getSizeModifier(),
2505 dat->getIndexTypeCVRQualifiers(),
2506 dat->getBracketsRange());
2507 break;
2508 }
2509
2510 // Turn incomplete types into [*] types.
2511 case Type::IncompleteArray: {
2512 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2513 result = getVariableArrayType(
2514 getVariableArrayDecayedType(iat->getElementType()),
2515 /*size*/ 0,
2516 ArrayType::Normal,
2517 iat->getIndexTypeCVRQualifiers(),
2518 SourceRange());
2519 break;
2520 }
2521
2522 // Turn VLA types into [*] types.
2523 case Type::VariableArray: {
2524 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2525 result = getVariableArrayType(
2526 getVariableArrayDecayedType(vat->getElementType()),
2527 /*size*/ 0,
2528 ArrayType::Star,
2529 vat->getIndexTypeCVRQualifiers(),
2530 vat->getBracketsRange());
2531 break;
2532 }
2533 }
2534
2535 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002536 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002537}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002538
Steve Naroffcadebd02007-08-30 18:14:25 +00002539/// getVariableArrayType - Returns a non-unique reference to the type for a
2540/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002541QualType ASTContext::getVariableArrayType(QualType EltTy,
2542 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002543 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002544 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002545 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002546 // Since we don't unique expressions, it isn't possible to unique VLA's
2547 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002548 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002549
John McCall33ddac02011-01-19 10:06:00 +00002550 // Be sure to pull qualifiers off the element type.
2551 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2552 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002553 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002554 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002555 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002556 }
2557
John McCall90d1c2d2009-09-24 23:30:46 +00002558 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002559 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002560
2561 VariableArrayTypes.push_back(New);
2562 Types.push_back(New);
2563 return QualType(New, 0);
2564}
2565
Douglas Gregor4619e432008-12-05 23:32:09 +00002566/// getDependentSizedArrayType - Returns a non-unique reference to
2567/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002568/// type.
John McCall33ddac02011-01-19 10:06:00 +00002569QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2570 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002571 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002572 unsigned elementTypeQuals,
2573 SourceRange brackets) const {
2574 assert((!numElements || numElements->isTypeDependent() ||
2575 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002576 "Size must be type- or value-dependent!");
2577
John McCall33ddac02011-01-19 10:06:00 +00002578 // Dependently-sized array types that do not have a specified number
2579 // of elements will have their sizes deduced from a dependent
2580 // initializer. We do no canonicalization here at all, which is okay
2581 // because they can't be used in most locations.
2582 if (!numElements) {
2583 DependentSizedArrayType *newType
2584 = new (*this, TypeAlignment)
2585 DependentSizedArrayType(*this, elementType, QualType(),
2586 numElements, ASM, elementTypeQuals,
2587 brackets);
2588 Types.push_back(newType);
2589 return QualType(newType, 0);
2590 }
2591
2592 // Otherwise, we actually build a new type every time, but we
2593 // also build a canonical type.
2594
2595 SplitQualType canonElementType = getCanonicalType(elementType).split();
2596
2597 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002598 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002599 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002600 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002601 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002602
John McCall33ddac02011-01-19 10:06:00 +00002603 // Look for an existing type with these properties.
2604 DependentSizedArrayType *canonTy =
2605 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002606
John McCall33ddac02011-01-19 10:06:00 +00002607 // If we don't have one, build one.
2608 if (!canonTy) {
2609 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002610 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002611 QualType(), numElements, ASM, elementTypeQuals,
2612 brackets);
2613 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2614 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002615 }
2616
John McCall33ddac02011-01-19 10:06:00 +00002617 // Apply qualifiers from the element type to the array.
2618 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002619 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002620
John McCall33ddac02011-01-19 10:06:00 +00002621 // If we didn't need extra canonicalization for the element type,
2622 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002623 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002624 return canon;
2625
2626 // Otherwise, we need to build a type which follows the spelling
2627 // of the element type.
2628 DependentSizedArrayType *sugaredType
2629 = new (*this, TypeAlignment)
2630 DependentSizedArrayType(*this, elementType, canon, numElements,
2631 ASM, elementTypeQuals, brackets);
2632 Types.push_back(sugaredType);
2633 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002634}
2635
John McCall33ddac02011-01-19 10:06:00 +00002636QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002637 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002638 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002639 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002640 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002641
John McCall33ddac02011-01-19 10:06:00 +00002642 void *insertPos = 0;
2643 if (IncompleteArrayType *iat =
2644 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2645 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002646
2647 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002648 // either, so fill in the canonical type field. We also have to pull
2649 // qualifiers off the element type.
2650 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002651
John McCall33ddac02011-01-19 10:06:00 +00002652 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2653 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002654 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002655 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002656 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002657
2658 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002659 IncompleteArrayType *existing =
2660 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2661 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002662 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002663
John McCall33ddac02011-01-19 10:06:00 +00002664 IncompleteArrayType *newType = new (*this, TypeAlignment)
2665 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002666
John McCall33ddac02011-01-19 10:06:00 +00002667 IncompleteArrayTypes.InsertNode(newType, insertPos);
2668 Types.push_back(newType);
2669 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002670}
2671
Steve Naroff91fcddb2007-07-18 18:00:27 +00002672/// getVectorType - Return the unique reference to a vector type of
2673/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002674QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002675 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002676 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002677
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002678 // Check if we've already instantiated a vector of this type.
2679 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002680 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002681
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002682 void *InsertPos = 0;
2683 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2684 return QualType(VTP, 0);
2685
2686 // If the element type isn't canonical, this won't be a canonical type either,
2687 // so fill in the canonical type field.
2688 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002689 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002690 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002691
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002692 // Get the new insert position for the node we care about.
2693 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002694 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002695 }
John McCall90d1c2d2009-09-24 23:30:46 +00002696 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002697 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002698 VectorTypes.InsertNode(New, InsertPos);
2699 Types.push_back(New);
2700 return QualType(New, 0);
2701}
2702
Nate Begemance4d7fc2008-04-18 23:10:10 +00002703/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002704/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002705QualType
2706ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002707 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002708
Steve Naroff91fcddb2007-07-18 18:00:27 +00002709 // Check if we've already instantiated a vector of this type.
2710 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002711 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002712 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002713 void *InsertPos = 0;
2714 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2715 return QualType(VTP, 0);
2716
2717 // If the element type isn't canonical, this won't be a canonical type either,
2718 // so fill in the canonical type field.
2719 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002720 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002721 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002722
Steve Naroff91fcddb2007-07-18 18:00:27 +00002723 // Get the new insert position for the node we care about.
2724 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002725 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002726 }
John McCall90d1c2d2009-09-24 23:30:46 +00002727 ExtVectorType *New = new (*this, TypeAlignment)
2728 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002729 VectorTypes.InsertNode(New, InsertPos);
2730 Types.push_back(New);
2731 return QualType(New, 0);
2732}
2733
Jay Foad39c79802011-01-12 09:06:06 +00002734QualType
2735ASTContext::getDependentSizedExtVectorType(QualType vecType,
2736 Expr *SizeExpr,
2737 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002738 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002739 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002740 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002741
Douglas Gregor352169a2009-07-31 03:54:25 +00002742 void *InsertPos = 0;
2743 DependentSizedExtVectorType *Canon
2744 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2745 DependentSizedExtVectorType *New;
2746 if (Canon) {
2747 // We already have a canonical version of this array type; use it as
2748 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002749 New = new (*this, TypeAlignment)
2750 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2751 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002752 } else {
2753 QualType CanonVecTy = getCanonicalType(vecType);
2754 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002755 New = new (*this, TypeAlignment)
2756 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2757 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002758
2759 DependentSizedExtVectorType *CanonCheck
2760 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2761 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2762 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002763 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2764 } else {
2765 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2766 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002767 New = new (*this, TypeAlignment)
2768 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002769 }
2770 }
Mike Stump11289f42009-09-09 15:08:12 +00002771
Douglas Gregor758a8692009-06-17 21:51:59 +00002772 Types.push_back(New);
2773 return QualType(New, 0);
2774}
2775
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002776/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002777///
Jay Foad39c79802011-01-12 09:06:06 +00002778QualType
2779ASTContext::getFunctionNoProtoType(QualType ResultTy,
2780 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002781 const CallingConv CallConv = Info.getCC();
2782
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002783 // Unique functions, to guarantee there is only one function of a particular
2784 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002785 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002786 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002787
Chris Lattner47955de2007-01-27 08:37:20 +00002788 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002789 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002790 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002791 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002792
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002793 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002794 if (!ResultTy.isCanonical()) {
2795 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002796
Chris Lattner47955de2007-01-27 08:37:20 +00002797 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002798 FunctionNoProtoType *NewIP =
2799 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002800 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002801 }
Mike Stump11289f42009-09-09 15:08:12 +00002802
Roman Divacky65b88cd2011-03-01 17:40:53 +00002803 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002804 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002805 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002806 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002807 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002808 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002809}
2810
Douglas Gregorcd780372013-01-17 23:36:45 +00002811/// \brief Determine whether \p T is canonical as the result type of a function.
2812static bool isCanonicalResultType(QualType T) {
2813 return T.isCanonical() &&
2814 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2815 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2816}
2817
Jay Foad39c79802011-01-12 09:06:06 +00002818QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002819ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002820 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002821 size_t NumArgs = ArgArray.size();
2822
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002823 // Unique functions, to guarantee there is only one function of a particular
2824 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002825 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002826 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2827 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002828
2829 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002830 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002831 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002832 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002833
2834 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002835 bool isCanonical =
Douglas Gregorcd780372013-01-17 23:36:45 +00002836 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002837 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002838 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002839 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002840 isCanonical = false;
2841
2842 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002843 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002844 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002845 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002846 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002847 CanonicalArgs.reserve(NumArgs);
2848 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002849 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002850
John McCalldb40c7f2010-12-14 08:05:40 +00002851 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002852 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002853 CanonicalEPI.ExceptionSpecType = EST_None;
2854 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002855
Douglas Gregorcd780372013-01-17 23:36:45 +00002856 // Result types do not have ARC lifetime qualifiers.
2857 QualType CanResultTy = getCanonicalType(ResultTy);
2858 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2859 Qualifiers Qs = CanResultTy.getQualifiers();
2860 Qs.removeObjCLifetime();
2861 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2862 }
2863
Jordan Rose5c382722013-03-08 21:51:21 +00002864 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002865
Chris Lattnerfd4de792007-01-27 01:15:32 +00002866 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002867 FunctionProtoType *NewIP =
2868 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002869 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002870 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002871
John McCall31168b02011-06-15 23:02:42 +00002872 // FunctionProtoType objects are allocated with extra bytes after
2873 // them for three variable size arrays at the end:
2874 // - parameter types
2875 // - exception types
2876 // - consumed-arguments flags
2877 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002878 // expression, or information used to resolve the exception
2879 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002880 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002881 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002882 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002883 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002884 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002885 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002886 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002887 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002888 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2889 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002890 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002891 if (EPI.ConsumedParameters)
John McCall31168b02011-06-15 23:02:42 +00002892 Size += NumArgs * sizeof(bool);
2893
John McCalldb40c7f2010-12-14 08:05:40 +00002894 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002895 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00002896 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002897 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002898 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002899 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002900}
Chris Lattneref51c202006-11-10 07:17:23 +00002901
John McCalle78aac42010-03-10 03:28:59 +00002902#ifndef NDEBUG
2903static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2904 if (!isa<CXXRecordDecl>(D)) return false;
2905 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2906 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2907 return true;
2908 if (RD->getDescribedClassTemplate() &&
2909 !isa<ClassTemplateSpecializationDecl>(RD))
2910 return true;
2911 return false;
2912}
2913#endif
2914
2915/// getInjectedClassNameType - Return the unique reference to the
2916/// injected class name type for the specified templated declaration.
2917QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002918 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002919 assert(NeedsInjectedClassNameType(Decl));
2920 if (Decl->TypeForDecl) {
2921 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002922 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002923 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2924 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2925 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2926 } else {
John McCall424cec92011-01-19 06:33:43 +00002927 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002928 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002929 Decl->TypeForDecl = newType;
2930 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002931 }
2932 return QualType(Decl->TypeForDecl, 0);
2933}
2934
Douglas Gregor83a586e2008-04-13 21:07:44 +00002935/// getTypeDeclType - Return the unique reference to the type for the
2936/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002937QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002938 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002939 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002940
Richard Smithdda56e42011-04-15 14:24:37 +00002941 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002942 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002943
John McCall96f0b5f2010-03-10 06:48:02 +00002944 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2945 "Template type parameter types are always available.");
2946
John McCall81e38502010-02-16 03:57:14 +00002947 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00002948 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00002949 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002950 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002951 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00002952 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002953 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002954 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002955 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002956 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2957 Decl->TypeForDecl = newType;
2958 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002959 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002960 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002961
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002962 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002963}
2964
Chris Lattner32d920b2007-01-26 02:01:53 +00002965/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002966/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002967QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002968ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2969 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002970 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002971
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002972 if (Canonical.isNull())
2973 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002974 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002975 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002976 Decl->TypeForDecl = newType;
2977 Types.push_back(newType);
2978 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002979}
2980
Jay Foad39c79802011-01-12 09:06:06 +00002981QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002982 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2983
Douglas Gregorec9fd132012-01-14 16:38:05 +00002984 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002985 if (PrevDecl->TypeForDecl)
2986 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2987
John McCall424cec92011-01-19 06:33:43 +00002988 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2989 Decl->TypeForDecl = newType;
2990 Types.push_back(newType);
2991 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002992}
2993
Jay Foad39c79802011-01-12 09:06:06 +00002994QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002995 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2996
Douglas Gregorec9fd132012-01-14 16:38:05 +00002997 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002998 if (PrevDecl->TypeForDecl)
2999 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3000
John McCall424cec92011-01-19 06:33:43 +00003001 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3002 Decl->TypeForDecl = newType;
3003 Types.push_back(newType);
3004 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003005}
3006
John McCall81904512011-01-06 01:58:22 +00003007QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3008 QualType modifiedType,
3009 QualType equivalentType) {
3010 llvm::FoldingSetNodeID id;
3011 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3012
3013 void *insertPos = 0;
3014 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3015 if (type) return QualType(type, 0);
3016
3017 QualType canon = getCanonicalType(equivalentType);
3018 type = new (*this, TypeAlignment)
3019 AttributedType(canon, attrKind, modifiedType, equivalentType);
3020
3021 Types.push_back(type);
3022 AttributedTypes.InsertNode(type, insertPos);
3023
3024 return QualType(type, 0);
3025}
3026
3027
John McCallcebee162009-10-18 09:09:24 +00003028/// \brief Retrieve a substitution-result type.
3029QualType
3030ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003031 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003032 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003033 && "replacement types must always be canonical");
3034
3035 llvm::FoldingSetNodeID ID;
3036 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3037 void *InsertPos = 0;
3038 SubstTemplateTypeParmType *SubstParm
3039 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3040
3041 if (!SubstParm) {
3042 SubstParm = new (*this, TypeAlignment)
3043 SubstTemplateTypeParmType(Parm, Replacement);
3044 Types.push_back(SubstParm);
3045 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3046 }
3047
3048 return QualType(SubstParm, 0);
3049}
3050
Douglas Gregorada4b792011-01-14 02:55:32 +00003051/// \brief Retrieve a
3052QualType ASTContext::getSubstTemplateTypeParmPackType(
3053 const TemplateTypeParmType *Parm,
3054 const TemplateArgument &ArgPack) {
3055#ifndef NDEBUG
3056 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
3057 PEnd = ArgPack.pack_end();
3058 P != PEnd; ++P) {
3059 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3060 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
3061 }
3062#endif
3063
3064 llvm::FoldingSetNodeID ID;
3065 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3066 void *InsertPos = 0;
3067 if (SubstTemplateTypeParmPackType *SubstParm
3068 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3069 return QualType(SubstParm, 0);
3070
3071 QualType Canon;
3072 if (!Parm->isCanonicalUnqualified()) {
3073 Canon = getCanonicalType(QualType(Parm, 0));
3074 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3075 ArgPack);
3076 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3077 }
3078
3079 SubstTemplateTypeParmPackType *SubstParm
3080 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3081 ArgPack);
3082 Types.push_back(SubstParm);
3083 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3084 return QualType(SubstParm, 0);
3085}
3086
Douglas Gregoreff93e02009-02-05 23:33:38 +00003087/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003088/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003089/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003090QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003091 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003092 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003093 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003094 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003095 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003096 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003097 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3098
3099 if (TypeParm)
3100 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003101
Chandler Carruth08836322011-05-01 00:51:33 +00003102 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003103 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003104 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003105
3106 TemplateTypeParmType *TypeCheck
3107 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3108 assert(!TypeCheck && "Template type parameter canonical type broken");
3109 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003110 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003111 TypeParm = new (*this, TypeAlignment)
3112 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003113
3114 Types.push_back(TypeParm);
3115 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3116
3117 return QualType(TypeParm, 0);
3118}
3119
John McCalle78aac42010-03-10 03:28:59 +00003120TypeSourceInfo *
3121ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3122 SourceLocation NameLoc,
3123 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003124 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003125 assert(!Name.getAsDependentTemplateName() &&
3126 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003127 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003128
3129 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003130 TemplateSpecializationTypeLoc TL =
3131 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003132 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003133 TL.setTemplateNameLoc(NameLoc);
3134 TL.setLAngleLoc(Args.getLAngleLoc());
3135 TL.setRAngleLoc(Args.getRAngleLoc());
3136 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3137 TL.setArgLocInfo(i, Args[i].getLocInfo());
3138 return DI;
3139}
3140
Mike Stump11289f42009-09-09 15:08:12 +00003141QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003142ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003143 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003144 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003145 assert(!Template.getAsDependentTemplateName() &&
3146 "No dependent template names here!");
3147
John McCall6b51f282009-11-23 01:53:49 +00003148 unsigned NumArgs = Args.size();
3149
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003150 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003151 ArgVec.reserve(NumArgs);
3152 for (unsigned i = 0; i != NumArgs; ++i)
3153 ArgVec.push_back(Args[i].getArgument());
3154
John McCall2408e322010-04-27 00:57:59 +00003155 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003156 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003157}
3158
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003159#ifndef NDEBUG
3160static bool hasAnyPackExpansions(const TemplateArgument *Args,
3161 unsigned NumArgs) {
3162 for (unsigned I = 0; I != NumArgs; ++I)
3163 if (Args[I].isPackExpansion())
3164 return true;
3165
3166 return true;
3167}
3168#endif
3169
John McCall0ad16662009-10-29 08:12:44 +00003170QualType
3171ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003172 const TemplateArgument *Args,
3173 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003174 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003175 assert(!Template.getAsDependentTemplateName() &&
3176 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003177 // Look through qualified template names.
3178 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3179 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003180
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003181 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003182 Template.getAsTemplateDecl() &&
3183 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003184 QualType CanonType;
3185 if (!Underlying.isNull())
3186 CanonType = getCanonicalType(Underlying);
3187 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003188 // We can get here with an alias template when the specialization contains
3189 // a pack expansion that does not match up with a parameter pack.
3190 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3191 "Caller must compute aliased type");
3192 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003193 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3194 NumArgs);
3195 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003196
Douglas Gregora8e02e72009-07-28 23:00:59 +00003197 // Allocate the (non-canonical) template specialization type, but don't
3198 // try to unique it: these types typically have location information that
3199 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003200 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3201 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003202 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003203 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003204 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003205 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3206 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003207
Douglas Gregor8bf42052009-02-09 18:46:07 +00003208 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003209 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003210}
3211
Mike Stump11289f42009-09-09 15:08:12 +00003212QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003213ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3214 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003215 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003216 assert(!Template.getAsDependentTemplateName() &&
3217 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003218
Douglas Gregore29139c2011-03-03 17:04:51 +00003219 // Look through qualified template names.
3220 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3221 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003222
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003223 // Build the canonical template specialization type.
3224 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003225 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003226 CanonArgs.reserve(NumArgs);
3227 for (unsigned I = 0; I != NumArgs; ++I)
3228 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3229
3230 // Determine whether this canonical template specialization type already
3231 // exists.
3232 llvm::FoldingSetNodeID ID;
3233 TemplateSpecializationType::Profile(ID, CanonTemplate,
3234 CanonArgs.data(), NumArgs, *this);
3235
3236 void *InsertPos = 0;
3237 TemplateSpecializationType *Spec
3238 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3239
3240 if (!Spec) {
3241 // Allocate a new canonical template specialization type.
3242 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3243 sizeof(TemplateArgument) * NumArgs),
3244 TypeAlignment);
3245 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3246 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003247 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003248 Types.push_back(Spec);
3249 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3250 }
3251
3252 assert(Spec->isDependentType() &&
3253 "Non-dependent template-id type must have a canonical type");
3254 return QualType(Spec, 0);
3255}
3256
3257QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003258ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3259 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003260 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003261 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003262 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003263
3264 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003265 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003266 if (T)
3267 return QualType(T, 0);
3268
Douglas Gregorc42075a2010-02-04 18:10:26 +00003269 QualType Canon = NamedType;
3270 if (!Canon.isCanonical()) {
3271 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003272 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3273 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003274 (void)CheckT;
3275 }
3276
Abramo Bagnara6150c882010-05-11 21:36:43 +00003277 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003278 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003279 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003280 return QualType(T, 0);
3281}
3282
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003283QualType
Jay Foad39c79802011-01-12 09:06:06 +00003284ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003285 llvm::FoldingSetNodeID ID;
3286 ParenType::Profile(ID, InnerType);
3287
3288 void *InsertPos = 0;
3289 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3290 if (T)
3291 return QualType(T, 0);
3292
3293 QualType Canon = InnerType;
3294 if (!Canon.isCanonical()) {
3295 Canon = getCanonicalType(InnerType);
3296 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3297 assert(!CheckT && "Paren canonical type broken");
3298 (void)CheckT;
3299 }
3300
3301 T = new (*this) ParenType(InnerType, Canon);
3302 Types.push_back(T);
3303 ParenTypes.InsertNode(T, InsertPos);
3304 return QualType(T, 0);
3305}
3306
Douglas Gregor02085352010-03-31 20:19:30 +00003307QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3308 NestedNameSpecifier *NNS,
3309 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003310 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003311 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3312
3313 if (Canon.isNull()) {
3314 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003315 ElaboratedTypeKeyword CanonKeyword = Keyword;
3316 if (Keyword == ETK_None)
3317 CanonKeyword = ETK_Typename;
3318
3319 if (CanonNNS != NNS || CanonKeyword != Keyword)
3320 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003321 }
3322
3323 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003324 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003325
3326 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003327 DependentNameType *T
3328 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003329 if (T)
3330 return QualType(T, 0);
3331
Douglas Gregor02085352010-03-31 20:19:30 +00003332 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003333 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003334 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003335 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003336}
3337
Mike Stump11289f42009-09-09 15:08:12 +00003338QualType
John McCallc392f372010-06-11 00:33:02 +00003339ASTContext::getDependentTemplateSpecializationType(
3340 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003341 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003342 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003343 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003344 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003345 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003346 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3347 ArgCopy.push_back(Args[I].getArgument());
3348 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3349 ArgCopy.size(),
3350 ArgCopy.data());
3351}
3352
3353QualType
3354ASTContext::getDependentTemplateSpecializationType(
3355 ElaboratedTypeKeyword Keyword,
3356 NestedNameSpecifier *NNS,
3357 const IdentifierInfo *Name,
3358 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003359 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003360 assert((!NNS || NNS->isDependent()) &&
3361 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003362
Douglas Gregorc42075a2010-02-04 18:10:26 +00003363 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003364 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3365 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003366
3367 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00003368 DependentTemplateSpecializationType *T
3369 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003370 if (T)
3371 return QualType(T, 0);
3372
John McCallc392f372010-06-11 00:33:02 +00003373 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003374
John McCallc392f372010-06-11 00:33:02 +00003375 ElaboratedTypeKeyword CanonKeyword = Keyword;
3376 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3377
3378 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003379 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003380 for (unsigned I = 0; I != NumArgs; ++I) {
3381 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3382 if (!CanonArgs[I].structurallyEquals(Args[I]))
3383 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003384 }
3385
John McCallc392f372010-06-11 00:33:02 +00003386 QualType Canon;
3387 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3388 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3389 Name, NumArgs,
3390 CanonArgs.data());
3391
3392 // Find the insert position again.
3393 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3394 }
3395
3396 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3397 sizeof(TemplateArgument) * NumArgs),
3398 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003399 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003400 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003401 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003402 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003403 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003404}
3405
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003406QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003407 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003408 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003409 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003410
3411 assert(Pattern->containsUnexpandedParameterPack() &&
3412 "Pack expansions must expand one or more parameter packs");
3413 void *InsertPos = 0;
3414 PackExpansionType *T
3415 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3416 if (T)
3417 return QualType(T, 0);
3418
3419 QualType Canon;
3420 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003421 Canon = getCanonicalType(Pattern);
3422 // The canonical type might not contain an unexpanded parameter pack, if it
3423 // contains an alias template specialization which ignores one of its
3424 // parameters.
3425 if (Canon->containsUnexpandedParameterPack()) {
3426 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003427
Richard Smith68eea502012-07-16 00:20:35 +00003428 // Find the insert position again, in case we inserted an element into
3429 // PackExpansionTypes and invalidated our insert position.
3430 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3431 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003432 }
3433
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003434 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003435 Types.push_back(T);
3436 PackExpansionTypes.InsertNode(T, InsertPos);
3437 return QualType(T, 0);
3438}
3439
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003440/// CmpProtocolNames - Comparison predicate for sorting protocols
3441/// alphabetically.
3442static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3443 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003444 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003445}
3446
John McCall8b07ec22010-05-15 11:32:37 +00003447static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003448 unsigned NumProtocols) {
3449 if (NumProtocols == 0) return true;
3450
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003451 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3452 return false;
3453
John McCallfc93cf92009-10-22 22:37:11 +00003454 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003455 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3456 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003457 return false;
3458 return true;
3459}
3460
3461static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003462 unsigned &NumProtocols) {
3463 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003464
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003465 // Sort protocols, keyed by name.
3466 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3467
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003468 // Canonicalize.
3469 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3470 Protocols[I] = Protocols[I]->getCanonicalDecl();
3471
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003472 // Remove duplicates.
3473 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3474 NumProtocols = ProtocolsEnd-Protocols;
3475}
3476
John McCall8b07ec22010-05-15 11:32:37 +00003477QualType ASTContext::getObjCObjectType(QualType BaseType,
3478 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003479 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003480 // If the base type is an interface and there aren't any protocols
3481 // to add, then the interface type will do just fine.
3482 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3483 return BaseType;
3484
3485 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003486 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003487 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003488 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003489 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3490 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003491
John McCall8b07ec22010-05-15 11:32:37 +00003492 // Build the canonical type, which has the canonical base type and
3493 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003494 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003495 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3496 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3497 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003498 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003499 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003500 unsigned UniqueCount = NumProtocols;
3501
John McCallfc93cf92009-10-22 22:37:11 +00003502 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003503 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3504 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003505 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003506 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3507 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003508 }
3509
3510 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003511 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3512 }
3513
3514 unsigned Size = sizeof(ObjCObjectTypeImpl);
3515 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3516 void *Mem = Allocate(Size, TypeAlignment);
3517 ObjCObjectTypeImpl *T =
3518 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3519
3520 Types.push_back(T);
3521 ObjCObjectTypes.InsertNode(T, InsertPos);
3522 return QualType(T, 0);
3523}
3524
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003525/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3526/// protocol list adopt all protocols in QT's qualified-id protocol
3527/// list.
3528bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3529 ObjCInterfaceDecl *IC) {
3530 if (!QT->isObjCQualifiedIdType())
3531 return false;
3532
3533 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3534 // If both the right and left sides have qualifiers.
3535 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3536 E = OPT->qual_end(); I != E; ++I) {
3537 ObjCProtocolDecl *Proto = *I;
3538 if (!IC->ClassImplementsProtocol(Proto, false))
3539 return false;
3540 }
3541 return true;
3542 }
3543 return false;
3544}
3545
3546/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3547/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3548/// of protocols.
3549bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3550 ObjCInterfaceDecl *IDecl) {
3551 if (!QT->isObjCQualifiedIdType())
3552 return false;
3553 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3554 if (!OPT)
3555 return false;
3556 if (!IDecl->hasDefinition())
3557 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003558 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3559 CollectInheritedProtocols(IDecl, InheritedProtocols);
3560 if (InheritedProtocols.empty())
3561 return false;
3562
3563 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator PI =
3564 InheritedProtocols.begin(),
3565 E = InheritedProtocols.end(); PI != E; ++PI) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003566 // If both the right and left sides have qualifiers.
3567 bool Adopts = false;
3568 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3569 E = OPT->qual_end(); I != E; ++I) {
3570 ObjCProtocolDecl *Proto = *I;
3571 // return 'true' if '*PI' is in the inheritance hierarchy of Proto
3572 if ((Adopts = ProtocolCompatibleWithProtocol(*PI, Proto)))
3573 break;
3574 }
3575 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003576 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003577 }
3578 return true;
3579}
3580
John McCall8b07ec22010-05-15 11:32:37 +00003581/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3582/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003583QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003584 llvm::FoldingSetNodeID ID;
3585 ObjCObjectPointerType::Profile(ID, ObjectT);
3586
3587 void *InsertPos = 0;
3588 if (ObjCObjectPointerType *QT =
3589 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3590 return QualType(QT, 0);
3591
3592 // Find the canonical object type.
3593 QualType Canonical;
3594 if (!ObjectT.isCanonical()) {
3595 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3596
3597 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003598 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3599 }
3600
Douglas Gregorf85bee62010-02-08 22:59:26 +00003601 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003602 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3603 ObjCObjectPointerType *QType =
3604 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003605
Steve Narofffb4330f2009-06-17 22:40:22 +00003606 Types.push_back(QType);
3607 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003608 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003609}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003610
Douglas Gregor1c283312010-08-11 12:19:30 +00003611/// getObjCInterfaceType - Return the unique reference to the type for the
3612/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003613QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3614 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003615 if (Decl->TypeForDecl)
3616 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003617
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003618 if (PrevDecl) {
3619 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3620 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3621 return QualType(PrevDecl->TypeForDecl, 0);
3622 }
3623
Douglas Gregor7671e532011-12-16 16:34:57 +00003624 // Prefer the definition, if there is one.
3625 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3626 Decl = Def;
3627
Douglas Gregor1c283312010-08-11 12:19:30 +00003628 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3629 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3630 Decl->TypeForDecl = T;
3631 Types.push_back(T);
3632 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003633}
3634
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003635/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3636/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003637/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003638/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003639/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003640QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003641 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003642 if (tofExpr->isTypeDependent()) {
3643 llvm::FoldingSetNodeID ID;
3644 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003645
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003646 void *InsertPos = 0;
3647 DependentTypeOfExprType *Canon
3648 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3649 if (Canon) {
3650 // We already have a "canonical" version of an identical, dependent
3651 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003652 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003653 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003654 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003655 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003656 Canon
3657 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003658 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3659 toe = Canon;
3660 }
3661 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003662 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003663 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003664 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003665 Types.push_back(toe);
3666 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003667}
3668
Steve Naroffa773cd52007-08-01 18:02:17 +00003669/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3670/// TypeOfType AST's. The only motivation to unique these nodes would be
3671/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003672/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003673/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003674QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003675 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003676 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003677 Types.push_back(tot);
3678 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003679}
3680
Anders Carlssonad6bd352009-06-24 21:24:56 +00003681
Anders Carlsson81df7b82009-06-24 19:06:50 +00003682/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3683/// DecltypeType AST's. The only motivation to unique these nodes would be
3684/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003685/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003686/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003687QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003688 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003689
3690 // C++0x [temp.type]p2:
3691 // If an expression e involves a template parameter, decltype(e) denotes a
3692 // unique dependent type. Two such decltype-specifiers refer to the same
3693 // type only if their expressions are equivalent (14.5.6.1).
3694 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003695 llvm::FoldingSetNodeID ID;
3696 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003697
Douglas Gregora21f6c32009-07-30 23:36:40 +00003698 void *InsertPos = 0;
3699 DependentDecltypeType *Canon
3700 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3701 if (Canon) {
3702 // We already have a "canonical" version of an equivalent, dependent
3703 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003704 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003705 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003706 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003707 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003708 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003709 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3710 dt = Canon;
3711 }
3712 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003713 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3714 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003715 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003716 Types.push_back(dt);
3717 return QualType(dt, 0);
3718}
3719
Alexis Hunte852b102011-05-24 22:41:36 +00003720/// getUnaryTransformationType - We don't unique these, since the memory
3721/// savings are minimal and these are rare.
3722QualType ASTContext::getUnaryTransformType(QualType BaseType,
3723 QualType UnderlyingType,
3724 UnaryTransformType::UTTKind Kind)
3725 const {
3726 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003727 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3728 Kind,
3729 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003730 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003731 Types.push_back(Ty);
3732 return QualType(Ty, 0);
3733}
3734
Richard Smith2a7d4812013-05-04 07:00:32 +00003735/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3736/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3737/// canonical deduced-but-dependent 'auto' type.
3738QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003739 bool IsDependent) const {
3740 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003741 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003742
Richard Smith2a7d4812013-05-04 07:00:32 +00003743 // Look in the folding set for an existing type.
Richard Smithb2bc2e62011-02-21 20:05:19 +00003744 void *InsertPos = 0;
Richard Smith2a7d4812013-05-04 07:00:32 +00003745 llvm::FoldingSetNodeID ID;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003746 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003747 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3748 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003749
Richard Smith74aeef52013-04-26 16:15:35 +00003750 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003751 IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003752 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003753 Types.push_back(AT);
3754 if (InsertPos)
3755 AutoTypes.InsertNode(AT, InsertPos);
3756 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003757}
3758
Eli Friedman0dfb8892011-10-06 23:00:33 +00003759/// getAtomicType - Return the uniqued reference to the atomic type for
3760/// the given value type.
3761QualType ASTContext::getAtomicType(QualType T) const {
3762 // Unique pointers, to guarantee there is only one pointer of a particular
3763 // structure.
3764 llvm::FoldingSetNodeID ID;
3765 AtomicType::Profile(ID, T);
3766
3767 void *InsertPos = 0;
3768 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3769 return QualType(AT, 0);
3770
3771 // If the atomic value type isn't canonical, this won't be a canonical type
3772 // either, so fill in the canonical type field.
3773 QualType Canonical;
3774 if (!T.isCanonical()) {
3775 Canonical = getAtomicType(getCanonicalType(T));
3776
3777 // Get the new insert position for the node we care about.
3778 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3779 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3780 }
3781 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3782 Types.push_back(New);
3783 AtomicTypes.InsertNode(New, InsertPos);
3784 return QualType(New, 0);
3785}
3786
Richard Smith02e85f32011-04-14 22:09:26 +00003787/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3788QualType ASTContext::getAutoDeductType() const {
3789 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00003790 AutoDeductTy = QualType(
3791 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003792 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00003793 0);
Richard Smith02e85f32011-04-14 22:09:26 +00003794 return AutoDeductTy;
3795}
3796
3797/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3798QualType ASTContext::getAutoRRefDeductType() const {
3799 if (AutoRRefDeductTy.isNull())
3800 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3801 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3802 return AutoRRefDeductTy;
3803}
3804
Chris Lattnerfb072462007-01-23 05:45:31 +00003805/// getTagDeclType - Return the unique reference to the type for the
3806/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003807QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003808 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003809 // FIXME: What is the design on getTagDeclType when it requires casting
3810 // away const? mutable?
3811 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003812}
3813
Mike Stump11289f42009-09-09 15:08:12 +00003814/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3815/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3816/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003817CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003818 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003819}
Chris Lattnerfb072462007-01-23 05:45:31 +00003820
Hans Wennborg27541db2011-10-27 08:29:09 +00003821/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3822CanQualType ASTContext::getIntMaxType() const {
3823 return getFromTargetType(Target->getIntMaxType());
3824}
3825
3826/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3827CanQualType ASTContext::getUIntMaxType() const {
3828 return getFromTargetType(Target->getUIntMaxType());
3829}
3830
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003831/// getSignedWCharType - Return the type of "signed wchar_t".
3832/// Used when in C++, as a GCC extension.
3833QualType ASTContext::getSignedWCharType() const {
3834 // FIXME: derive from "Target" ?
3835 return WCharTy;
3836}
3837
3838/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3839/// Used when in C++, as a GCC extension.
3840QualType ASTContext::getUnsignedWCharType() const {
3841 // FIXME: derive from "Target" ?
3842 return UnsignedIntTy;
3843}
3844
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00003845QualType ASTContext::getIntPtrType() const {
3846 return getFromTargetType(Target->getIntPtrType());
3847}
3848
3849QualType ASTContext::getUIntPtrType() const {
3850 return getCorrespondingUnsignedType(getIntPtrType());
3851}
3852
Hans Wennborg27541db2011-10-27 08:29:09 +00003853/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003854/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3855QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003856 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003857}
3858
Eli Friedman4e91899e2012-11-27 02:58:24 +00003859/// \brief Return the unique type for "pid_t" defined in
3860/// <sys/types.h>. We need this to compute the correct type for vfork().
3861QualType ASTContext::getProcessIDType() const {
3862 return getFromTargetType(Target->getProcessIDType());
3863}
3864
Chris Lattnera21ad802008-04-02 05:18:44 +00003865//===----------------------------------------------------------------------===//
3866// Type Operators
3867//===----------------------------------------------------------------------===//
3868
Jay Foad39c79802011-01-12 09:06:06 +00003869CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003870 // Push qualifiers into arrays, and then discard any remaining
3871 // qualifiers.
3872 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003873 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003874 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003875 QualType Result;
3876 if (isa<ArrayType>(Ty)) {
3877 Result = getArrayDecayedType(QualType(Ty,0));
3878 } else if (isa<FunctionType>(Ty)) {
3879 Result = getPointerType(QualType(Ty, 0));
3880 } else {
3881 Result = QualType(Ty, 0);
3882 }
3883
3884 return CanQualType::CreateUnsafe(Result);
3885}
3886
John McCall6c9dd522011-01-18 07:41:22 +00003887QualType ASTContext::getUnqualifiedArrayType(QualType type,
3888 Qualifiers &quals) {
3889 SplitQualType splitType = type.getSplitUnqualifiedType();
3890
3891 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3892 // the unqualified desugared type and then drops it on the floor.
3893 // We then have to strip that sugar back off with
3894 // getUnqualifiedDesugaredType(), which is silly.
3895 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003896 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003897
3898 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003899 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003900 quals = splitType.Quals;
3901 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003902 }
3903
John McCall6c9dd522011-01-18 07:41:22 +00003904 // Otherwise, recurse on the array's element type.
3905 QualType elementType = AT->getElementType();
3906 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3907
3908 // If that didn't change the element type, AT has no qualifiers, so we
3909 // can just use the results in splitType.
3910 if (elementType == unqualElementType) {
3911 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003912 quals = splitType.Quals;
3913 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003914 }
3915
3916 // Otherwise, add in the qualifiers from the outermost type, then
3917 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003918 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003919
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003920 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003921 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003922 CAT->getSizeModifier(), 0);
3923 }
3924
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003925 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003926 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003927 }
3928
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003929 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003930 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003931 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003932 VAT->getSizeModifier(),
3933 VAT->getIndexTypeCVRQualifiers(),
3934 VAT->getBracketsRange());
3935 }
3936
3937 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003938 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003939 DSAT->getSizeModifier(), 0,
3940 SourceRange());
3941}
3942
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003943/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3944/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3945/// they point to and return true. If T1 and T2 aren't pointer types
3946/// or pointer-to-member types, or if they are not similar at this
3947/// level, returns false and leaves T1 and T2 unchanged. Top-level
3948/// qualifiers on T1 and T2 are ignored. This function will typically
3949/// be called in a loop that successively "unwraps" pointer and
3950/// pointer-to-member types to compare them at each level.
3951bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3952 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3953 *T2PtrType = T2->getAs<PointerType>();
3954 if (T1PtrType && T2PtrType) {
3955 T1 = T1PtrType->getPointeeType();
3956 T2 = T2PtrType->getPointeeType();
3957 return true;
3958 }
3959
3960 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3961 *T2MPType = T2->getAs<MemberPointerType>();
3962 if (T1MPType && T2MPType &&
3963 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3964 QualType(T2MPType->getClass(), 0))) {
3965 T1 = T1MPType->getPointeeType();
3966 T2 = T2MPType->getPointeeType();
3967 return true;
3968 }
3969
David Blaikiebbafb8a2012-03-11 07:00:24 +00003970 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003971 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3972 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3973 if (T1OPType && T2OPType) {
3974 T1 = T1OPType->getPointeeType();
3975 T2 = T2OPType->getPointeeType();
3976 return true;
3977 }
3978 }
3979
3980 // FIXME: Block pointers, too?
3981
3982 return false;
3983}
3984
Jay Foad39c79802011-01-12 09:06:06 +00003985DeclarationNameInfo
3986ASTContext::getNameForTemplate(TemplateName Name,
3987 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003988 switch (Name.getKind()) {
3989 case TemplateName::QualifiedTemplate:
3990 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003991 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003992 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3993 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003994
John McCalld9dfe3a2011-06-30 08:33:18 +00003995 case TemplateName::OverloadedTemplate: {
3996 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3997 // DNInfo work in progress: CHECKME: what about DNLoc?
3998 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3999 }
4000
4001 case TemplateName::DependentTemplate: {
4002 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004003 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004004 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004005 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4006 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004007 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004008 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4009 // DNInfo work in progress: FIXME: source locations?
4010 DeclarationNameLoc DNLoc;
4011 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4012 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4013 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004014 }
4015 }
4016
John McCalld9dfe3a2011-06-30 08:33:18 +00004017 case TemplateName::SubstTemplateTemplateParm: {
4018 SubstTemplateTemplateParmStorage *subst
4019 = Name.getAsSubstTemplateTemplateParm();
4020 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4021 NameLoc);
4022 }
4023
4024 case TemplateName::SubstTemplateTemplateParmPack: {
4025 SubstTemplateTemplateParmPackStorage *subst
4026 = Name.getAsSubstTemplateTemplateParmPack();
4027 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4028 NameLoc);
4029 }
4030 }
4031
4032 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004033}
4034
Jay Foad39c79802011-01-12 09:06:06 +00004035TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004036 switch (Name.getKind()) {
4037 case TemplateName::QualifiedTemplate:
4038 case TemplateName::Template: {
4039 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004040 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004041 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004042 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4043
4044 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004045 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004046 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004047
John McCalld9dfe3a2011-06-30 08:33:18 +00004048 case TemplateName::OverloadedTemplate:
4049 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004050
John McCalld9dfe3a2011-06-30 08:33:18 +00004051 case TemplateName::DependentTemplate: {
4052 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4053 assert(DTN && "Non-dependent template names must refer to template decls.");
4054 return DTN->CanonicalTemplateName;
4055 }
4056
4057 case TemplateName::SubstTemplateTemplateParm: {
4058 SubstTemplateTemplateParmStorage *subst
4059 = Name.getAsSubstTemplateTemplateParm();
4060 return getCanonicalTemplateName(subst->getReplacement());
4061 }
4062
4063 case TemplateName::SubstTemplateTemplateParmPack: {
4064 SubstTemplateTemplateParmPackStorage *subst
4065 = Name.getAsSubstTemplateTemplateParmPack();
4066 TemplateTemplateParmDecl *canonParameter
4067 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4068 TemplateArgument canonArgPack
4069 = getCanonicalTemplateArgument(subst->getArgumentPack());
4070 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4071 }
4072 }
4073
4074 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004075}
4076
Douglas Gregoradee3e32009-11-11 23:06:43 +00004077bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4078 X = getCanonicalTemplateName(X);
4079 Y = getCanonicalTemplateName(Y);
4080 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4081}
4082
Mike Stump11289f42009-09-09 15:08:12 +00004083TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004084ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004085 switch (Arg.getKind()) {
4086 case TemplateArgument::Null:
4087 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004088
Douglas Gregora8e02e72009-07-28 23:00:59 +00004089 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004090 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004091
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004092 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004093 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4094 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004095 }
Mike Stump11289f42009-09-09 15:08:12 +00004096
Eli Friedmanb826a002012-09-26 02:36:12 +00004097 case TemplateArgument::NullPtr:
4098 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4099 /*isNullPtr*/true);
4100
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004101 case TemplateArgument::Template:
4102 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004103
4104 case TemplateArgument::TemplateExpansion:
4105 return TemplateArgument(getCanonicalTemplateName(
4106 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004107 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004108
Douglas Gregora8e02e72009-07-28 23:00:59 +00004109 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004110 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004111
Douglas Gregora8e02e72009-07-28 23:00:59 +00004112 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004113 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004114
Douglas Gregora8e02e72009-07-28 23:00:59 +00004115 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004116 if (Arg.pack_size() == 0)
4117 return Arg;
4118
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004119 TemplateArgument *CanonArgs
4120 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004121 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004122 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004123 AEnd = Arg.pack_end();
4124 A != AEnd; (void)++A, ++Idx)
4125 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004126
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004127 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00004128 }
4129 }
4130
4131 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004132 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004133}
4134
Douglas Gregor333489b2009-03-27 23:10:48 +00004135NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004136ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004137 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00004138 return 0;
4139
4140 switch (NNS->getKind()) {
4141 case NestedNameSpecifier::Identifier:
4142 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004143 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004144 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4145 NNS->getAsIdentifier());
4146
4147 case NestedNameSpecifier::Namespace:
4148 // A namespace is canonical; build a nested-name-specifier with
4149 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004150 return NestedNameSpecifier::Create(*this, 0,
4151 NNS->getAsNamespace()->getOriginalNamespace());
4152
4153 case NestedNameSpecifier::NamespaceAlias:
4154 // A namespace is canonical; build a nested-name-specifier with
4155 // this namespace and no prefix.
4156 return NestedNameSpecifier::Create(*this, 0,
4157 NNS->getAsNamespaceAlias()->getNamespace()
4158 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004159
4160 case NestedNameSpecifier::TypeSpec:
4161 case NestedNameSpecifier::TypeSpecWithTemplate: {
4162 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004163
4164 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4165 // break it apart into its prefix and identifier, then reconsititute those
4166 // as the canonical nested-name-specifier. This is required to canonicalize
4167 // a dependent nested-name-specifier involving typedefs of dependent-name
4168 // types, e.g.,
4169 // typedef typename T::type T1;
4170 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004171 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4172 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004173 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004174
Eli Friedman5358a0a2012-03-03 04:09:56 +00004175 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4176 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4177 // first place?
John McCall33ddac02011-01-19 10:06:00 +00004178 return NestedNameSpecifier::Create(*this, 0, false,
4179 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004180 }
4181
4182 case NestedNameSpecifier::Global:
4183 // The global specifier is canonical and unique.
4184 return NNS;
4185 }
4186
David Blaikie8a40f702012-01-17 06:56:22 +00004187 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004188}
4189
Chris Lattner7adf0762008-08-04 07:31:14 +00004190
Jay Foad39c79802011-01-12 09:06:06 +00004191const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004192 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004193 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004194 // Handle the common positive case fast.
4195 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4196 return AT;
4197 }
Mike Stump11289f42009-09-09 15:08:12 +00004198
John McCall8ccfcb52009-09-24 19:53:00 +00004199 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004200 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00004201 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004202
John McCall8ccfcb52009-09-24 19:53:00 +00004203 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004204 // implements C99 6.7.3p8: "If the specification of an array type includes
4205 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004206
Chris Lattner7adf0762008-08-04 07:31:14 +00004207 // If we get here, we either have type qualifiers on the type, or we have
4208 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004209 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004210
John McCall33ddac02011-01-19 10:06:00 +00004211 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004212 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004213
Chris Lattner7adf0762008-08-04 07:31:14 +00004214 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004215 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00004216 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004217 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004218
Chris Lattner7adf0762008-08-04 07:31:14 +00004219 // Otherwise, we have an array and we have qualifiers on it. Push the
4220 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004221 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004222
Chris Lattner7adf0762008-08-04 07:31:14 +00004223 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4224 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4225 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004226 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004227 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4228 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4229 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004230 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004231
Mike Stump11289f42009-09-09 15:08:12 +00004232 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004233 = dyn_cast<DependentSizedArrayType>(ATy))
4234 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004235 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004236 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004237 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004238 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004239 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004240
Chris Lattner7adf0762008-08-04 07:31:14 +00004241 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004242 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004243 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004244 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004245 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004246 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004247}
4248
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004249QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004250 if (T->isArrayType() || T->isFunctionType())
4251 return getDecayedType(T);
4252 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004253}
4254
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004255QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004256 T = getVariableArrayDecayedType(T);
4257 T = getAdjustedParameterType(T);
4258 return T.getUnqualifiedType();
4259}
4260
Chris Lattnera21ad802008-04-02 05:18:44 +00004261/// getArrayDecayedType - Return the properly qualified result of decaying the
4262/// specified array type to a pointer. This operation is non-trivial when
4263/// handling typedefs etc. The canonical type of "T" must be an array type,
4264/// this returns a pointer to a properly qualified element of the array.
4265///
4266/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004267QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004268 // Get the element type with 'getAsArrayType' so that we don't lose any
4269 // typedefs in the element type of the array. This also handles propagation
4270 // of type qualifiers from the array type into the element type if present
4271 // (C99 6.7.3p8).
4272 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4273 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004274
Chris Lattner7adf0762008-08-04 07:31:14 +00004275 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004276
4277 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004278 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004279}
4280
John McCall33ddac02011-01-19 10:06:00 +00004281QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4282 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004283}
4284
John McCall33ddac02011-01-19 10:06:00 +00004285QualType ASTContext::getBaseElementType(QualType type) const {
4286 Qualifiers qs;
4287 while (true) {
4288 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004289 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004290 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004291
John McCall33ddac02011-01-19 10:06:00 +00004292 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004293 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004294 }
Mike Stump11289f42009-09-09 15:08:12 +00004295
John McCall33ddac02011-01-19 10:06:00 +00004296 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004297}
4298
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004299/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004300uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004301ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4302 uint64_t ElementCount = 1;
4303 do {
4304 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004305 CA = dyn_cast_or_null<ConstantArrayType>(
4306 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004307 } while (CA);
4308 return ElementCount;
4309}
4310
Steve Naroff0af91202007-04-27 21:51:21 +00004311/// getFloatingRank - Return a relative rank for floating point types.
4312/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004313static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004314 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004315 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004316
John McCall9dd450b2009-09-21 23:43:11 +00004317 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4318 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004319 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004320 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004321 case BuiltinType::Float: return FloatRank;
4322 case BuiltinType::Double: return DoubleRank;
4323 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004324 }
4325}
4326
Mike Stump11289f42009-09-09 15:08:12 +00004327/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4328/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004329/// 'typeDomain' is a real floating point or complex type.
4330/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004331QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4332 QualType Domain) const {
4333 FloatingRank EltRank = getFloatingRank(Size);
4334 if (Domain->isComplexType()) {
4335 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004336 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004337 case FloatRank: return FloatComplexTy;
4338 case DoubleRank: return DoubleComplexTy;
4339 case LongDoubleRank: return LongDoubleComplexTy;
4340 }
Steve Naroff0af91202007-04-27 21:51:21 +00004341 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004342
4343 assert(Domain->isRealFloatingType() && "Unknown domain!");
4344 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004345 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004346 case FloatRank: return FloatTy;
4347 case DoubleRank: return DoubleTy;
4348 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004349 }
David Blaikief47fa302012-01-17 02:30:50 +00004350 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004351}
4352
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004353/// getFloatingTypeOrder - Compare the rank of the two specified floating
4354/// point types, ignoring the domain of the type (i.e. 'double' ==
4355/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004356/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004357int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004358 FloatingRank LHSR = getFloatingRank(LHS);
4359 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004360
Chris Lattnerb90739d2008-04-06 23:38:49 +00004361 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004362 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004363 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004364 return 1;
4365 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004366}
4367
Chris Lattner76a00cf2008-04-06 22:59:24 +00004368/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4369/// routine will assert if passed a built-in type that isn't an integer or enum,
4370/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004371unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004372 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004373
Chris Lattner76a00cf2008-04-06 22:59:24 +00004374 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004375 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004376 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004377 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004378 case BuiltinType::Char_S:
4379 case BuiltinType::Char_U:
4380 case BuiltinType::SChar:
4381 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004382 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004383 case BuiltinType::Short:
4384 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004385 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004386 case BuiltinType::Int:
4387 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004388 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004389 case BuiltinType::Long:
4390 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004391 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004392 case BuiltinType::LongLong:
4393 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004394 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004395 case BuiltinType::Int128:
4396 case BuiltinType::UInt128:
4397 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004398 }
4399}
4400
Eli Friedman629ffb92009-08-20 04:21:42 +00004401/// \brief Whether this is a promotable bitfield reference according
4402/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4403///
4404/// \returns the type this bit-field will promote to, or NULL if no
4405/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004406QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004407 if (E->isTypeDependent() || E->isValueDependent())
4408 return QualType();
4409
John McCalld25db7e2013-05-06 21:39:12 +00004410 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004411 if (!Field)
4412 return QualType();
4413
4414 QualType FT = Field->getType();
4415
Richard Smithcaf33902011-10-10 18:28:20 +00004416 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004417 uint64_t IntSize = getTypeSize(IntTy);
4418 // GCC extension compatibility: if the bit-field size is less than or equal
4419 // to the size of int, it gets promoted no matter what its type is.
4420 // For instance, unsigned long bf : 4 gets promoted to signed int.
4421 if (BitWidth < IntSize)
4422 return IntTy;
4423
4424 if (BitWidth == IntSize)
4425 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4426
4427 // Types bigger than int are not subject to promotions, and therefore act
4428 // like the base type.
4429 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4430 // is ridiculous.
4431 return QualType();
4432}
4433
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004434/// getPromotedIntegerType - Returns the type that Promotable will
4435/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4436/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004437QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004438 assert(!Promotable.isNull());
4439 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004440 if (const EnumType *ET = Promotable->getAs<EnumType>())
4441 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004442
4443 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4444 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4445 // (3.9.1) can be converted to a prvalue of the first of the following
4446 // types that can represent all the values of its underlying type:
4447 // int, unsigned int, long int, unsigned long int, long long int, or
4448 // unsigned long long int [...]
4449 // FIXME: Is there some better way to compute this?
4450 if (BT->getKind() == BuiltinType::WChar_S ||
4451 BT->getKind() == BuiltinType::WChar_U ||
4452 BT->getKind() == BuiltinType::Char16 ||
4453 BT->getKind() == BuiltinType::Char32) {
4454 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4455 uint64_t FromSize = getTypeSize(BT);
4456 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4457 LongLongTy, UnsignedLongLongTy };
4458 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4459 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4460 if (FromSize < ToSize ||
4461 (FromSize == ToSize &&
4462 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4463 return PromoteTypes[Idx];
4464 }
4465 llvm_unreachable("char type should fit into long long");
4466 }
4467 }
4468
4469 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004470 if (Promotable->isSignedIntegerType())
4471 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004472 uint64_t PromotableSize = getIntWidth(Promotable);
4473 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004474 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4475 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4476}
4477
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004478/// \brief Recurses in pointer/array types until it finds an objc retainable
4479/// type and returns its ownership.
4480Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4481 while (!T.isNull()) {
4482 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4483 return T.getObjCLifetime();
4484 if (T->isArrayType())
4485 T = getBaseElementType(T);
4486 else if (const PointerType *PT = T->getAs<PointerType>())
4487 T = PT->getPointeeType();
4488 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004489 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004490 else
4491 break;
4492 }
4493
4494 return Qualifiers::OCL_None;
4495}
4496
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004497static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4498 // Incomplete enum types are not treated as integer types.
4499 // FIXME: In C++, enum types are never integer types.
4500 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4501 return ET->getDecl()->getIntegerType().getTypePtr();
4502 return NULL;
4503}
4504
Mike Stump11289f42009-09-09 15:08:12 +00004505/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004506/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004507/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004508int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004509 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4510 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004511
4512 // Unwrap enums to their underlying type.
4513 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4514 LHSC = getIntegerTypeForEnum(ET);
4515 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4516 RHSC = getIntegerTypeForEnum(ET);
4517
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004518 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004519
Chris Lattner76a00cf2008-04-06 22:59:24 +00004520 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4521 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004522
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004523 unsigned LHSRank = getIntegerRank(LHSC);
4524 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004525
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004526 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4527 if (LHSRank == RHSRank) return 0;
4528 return LHSRank > RHSRank ? 1 : -1;
4529 }
Mike Stump11289f42009-09-09 15:08:12 +00004530
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004531 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4532 if (LHSUnsigned) {
4533 // If the unsigned [LHS] type is larger, return it.
4534 if (LHSRank >= RHSRank)
4535 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004536
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004537 // If the signed type can represent all values of the unsigned type, it
4538 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004539 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004540 return -1;
4541 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004542
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004543 // If the unsigned [RHS] type is larger, return it.
4544 if (RHSRank >= LHSRank)
4545 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004546
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004547 // If the signed type can represent all values of the unsigned type, it
4548 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004549 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004550 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004551}
Anders Carlsson98f07902007-08-17 05:31:46 +00004552
Mike Stump11289f42009-09-09 15:08:12 +00004553// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004554QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004555 if (!CFConstantStringTypeDecl) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004556 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
John McCallae580fe2010-02-05 01:33:36 +00004557 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004558
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004559 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004560
Anders Carlsson98f07902007-08-17 05:31:46 +00004561 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004562 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004563 // int flags;
4564 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004565 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004566 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004567 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004568 FieldTypes[3] = LongTy;
4569
Anders Carlsson98f07902007-08-17 05:31:46 +00004570 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004571 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004572 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004573 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004574 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004575 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004576 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004577 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004578 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004579 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004580 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004581 }
4582
Douglas Gregord5058122010-02-11 01:19:42 +00004583 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004584 }
Mike Stump11289f42009-09-09 15:08:12 +00004585
Anders Carlsson98f07902007-08-17 05:31:46 +00004586 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004587}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004588
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004589QualType ASTContext::getObjCSuperType() const {
4590 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004591 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004592 TUDecl->addDecl(ObjCSuperTypeDecl);
4593 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4594 }
4595 return ObjCSuperType;
4596}
4597
Douglas Gregor512b0772009-04-23 22:29:11 +00004598void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004599 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004600 assert(Rec && "Invalid CFConstantStringType");
4601 CFConstantStringTypeDecl = Rec->getDecl();
4602}
4603
Jay Foad39c79802011-01-12 09:06:06 +00004604QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004605 if (BlockDescriptorType)
4606 return getTagDeclType(BlockDescriptorType);
4607
Alp Toker2dea15b2013-12-17 01:22:38 +00004608 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004609 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004610 RD = buildImplicitRecord("__block_descriptor");
4611 RD->startDefinition();
4612
Mike Stumpd0153282009-10-20 02:12:22 +00004613 QualType FieldTypes[] = {
4614 UnsignedLongTy,
4615 UnsignedLongTy,
4616 };
4617
Craig Topperd6d31ac2013-07-15 08:24:27 +00004618 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004619 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004620 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004621 };
4622
4623 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004624 FieldDecl *Field = FieldDecl::Create(
4625 *this, RD, SourceLocation(), SourceLocation(),
4626 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/0,
4627 /*BitWidth=*/0, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004628 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004629 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004630 }
4631
Alp Toker2dea15b2013-12-17 01:22:38 +00004632 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004633
Alp Toker2dea15b2013-12-17 01:22:38 +00004634 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004635
4636 return getTagDeclType(BlockDescriptorType);
4637}
4638
Jay Foad39c79802011-01-12 09:06:06 +00004639QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004640 if (BlockDescriptorExtendedType)
4641 return getTagDeclType(BlockDescriptorExtendedType);
4642
Alp Toker2dea15b2013-12-17 01:22:38 +00004643 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004644 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004645 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4646 RD->startDefinition();
4647
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004648 QualType FieldTypes[] = {
4649 UnsignedLongTy,
4650 UnsignedLongTy,
4651 getPointerType(VoidPtrTy),
4652 getPointerType(VoidPtrTy)
4653 };
4654
Craig Topperd6d31ac2013-07-15 08:24:27 +00004655 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004656 "reserved",
4657 "Size",
4658 "CopyFuncPtr",
4659 "DestroyFuncPtr"
4660 };
4661
4662 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004663 FieldDecl *Field = FieldDecl::Create(
4664 *this, RD, SourceLocation(), SourceLocation(),
4665 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/0,
4666 /*BitWidth=*/0,
4667 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004668 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004669 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004670 }
4671
Alp Toker2dea15b2013-12-17 01:22:38 +00004672 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004673
Alp Toker2dea15b2013-12-17 01:22:38 +00004674 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004675 return getTagDeclType(BlockDescriptorExtendedType);
4676}
4677
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004678/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4679/// requires copy/dispose. Note that this must match the logic
4680/// in buildByrefHelpers.
4681bool ASTContext::BlockRequiresCopying(QualType Ty,
4682 const VarDecl *D) {
4683 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4684 const Expr *copyExpr = getBlockVarCopyInits(D);
4685 if (!copyExpr && record->hasTrivialDestructor()) return false;
4686
Mike Stump94967902009-10-21 18:16:27 +00004687 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004688 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004689
4690 if (!Ty->isObjCRetainableType()) return false;
4691
4692 Qualifiers qs = Ty.getQualifiers();
4693
4694 // If we have lifetime, that dominates.
4695 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4696 assert(getLangOpts().ObjCAutoRefCount);
4697
4698 switch (lifetime) {
4699 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4700
4701 // These are just bits as far as the runtime is concerned.
4702 case Qualifiers::OCL_ExplicitNone:
4703 case Qualifiers::OCL_Autoreleasing:
4704 return false;
4705
4706 // Tell the runtime that this is ARC __weak, called by the
4707 // byref routines.
4708 case Qualifiers::OCL_Weak:
4709 // ARC __strong __block variables need to be retained.
4710 case Qualifiers::OCL_Strong:
4711 return true;
4712 }
4713 llvm_unreachable("fell out of lifetime switch!");
4714 }
4715 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4716 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004717}
4718
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004719bool ASTContext::getByrefLifetime(QualType Ty,
4720 Qualifiers::ObjCLifetime &LifeTime,
4721 bool &HasByrefExtendedLayout) const {
4722
4723 if (!getLangOpts().ObjC1 ||
4724 getLangOpts().getGC() != LangOptions::NonGC)
4725 return false;
4726
4727 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004728 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004729 HasByrefExtendedLayout = true;
4730 LifeTime = Qualifiers::OCL_None;
4731 }
4732 else if (getLangOpts().ObjCAutoRefCount)
4733 LifeTime = Ty.getObjCLifetime();
4734 // MRR.
4735 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4736 LifeTime = Qualifiers::OCL_ExplicitNone;
4737 else
4738 LifeTime = Qualifiers::OCL_None;
4739 return true;
4740}
4741
Douglas Gregorbab8a962011-09-08 01:46:34 +00004742TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4743 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00004744 ObjCInstanceTypeDecl =
4745 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00004746 return ObjCInstanceTypeDecl;
4747}
4748
Anders Carlsson18acd442007-10-29 06:33:42 +00004749// This returns true if a type has been typedefed to BOOL:
4750// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004751static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004752 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004753 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4754 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004755
Anders Carlssond8499822007-10-29 05:01:08 +00004756 return false;
4757}
4758
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004759/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004760/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004761CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004762 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4763 return CharUnits::Zero();
4764
Ken Dyck40775002010-01-11 17:06:35 +00004765 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004766
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004767 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004768 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004769 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004770 // Treat arrays as pointers, since that's how they're passed in.
4771 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004772 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004773 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004774}
4775
4776static inline
4777std::string charUnitsToString(const CharUnits &CU) {
4778 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004779}
4780
John McCall351762c2011-02-07 10:33:21 +00004781/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004782/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004783std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4784 std::string S;
4785
David Chisnall950a9512009-11-17 19:33:30 +00004786 const BlockDecl *Decl = Expr->getBlockDecl();
4787 QualType BlockTy =
4788 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4789 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004790 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00004791 getObjCEncodingForMethodParameter(
4792 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
4793 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004794 else
Alp Toker314cc812014-01-25 16:55:45 +00004795 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004796 // Compute size of all parameters.
4797 // Start with computing size of a pointer in number of bytes.
4798 // FIXME: There might(should) be a better way of doing this computation!
4799 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004800 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4801 CharUnits ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00004802 for (auto PI : Decl->params()) {
4803 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004804 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004805 if (sz.isZero())
4806 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004807 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004808 ParmOffset += sz;
4809 }
4810 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004811 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004812 // Block pointer and offset.
4813 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004814
4815 // Argument types.
4816 ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00004817 for (auto PVDecl : Decl->params()) {
David Chisnall950a9512009-11-17 19:33:30 +00004818 QualType PType = PVDecl->getOriginalType();
4819 if (const ArrayType *AT =
4820 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4821 // Use array's original type only if it has known number of
4822 // elements.
4823 if (!isa<ConstantArrayType>(AT))
4824 PType = PVDecl->getType();
4825 } else if (PType->isFunctionType())
4826 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004827 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004828 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4829 S, true /*Extended*/);
4830 else
4831 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004832 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004833 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004834 }
John McCall351762c2011-02-07 10:33:21 +00004835
4836 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004837}
4838
Douglas Gregora9d84932011-05-27 01:19:52 +00004839bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004840 std::string& S) {
4841 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00004842 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00004843 CharUnits ParmOffset;
4844 // Compute size of all parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00004845 for (auto PI : Decl->params()) {
4846 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00004847 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004848 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004849 continue;
4850
David Chisnall50e4eba2010-12-30 14:05:53 +00004851 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004852 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004853 ParmOffset += sz;
4854 }
4855 S += charUnitsToString(ParmOffset);
4856 ParmOffset = CharUnits::Zero();
4857
4858 // Argument types.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00004859 for (auto PVDecl : Decl->params()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00004860 QualType PType = PVDecl->getOriginalType();
4861 if (const ArrayType *AT =
4862 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4863 // Use array's original type only if it has known number of
4864 // elements.
4865 if (!isa<ConstantArrayType>(AT))
4866 PType = PVDecl->getType();
4867 } else if (PType->isFunctionType())
4868 PType = PVDecl->getType();
4869 getObjCEncodingForType(PType, S);
4870 S += charUnitsToString(ParmOffset);
4871 ParmOffset += getObjCEncodingTypeSize(PType);
4872 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004873
4874 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004875}
4876
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004877/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4878/// method parameter or return type. If Extended, include class names and
4879/// block object types.
4880void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4881 QualType T, std::string& S,
4882 bool Extended) const {
4883 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4884 getObjCEncodingForTypeQualifier(QT, S);
4885 // Encode parameter type.
4886 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4887 true /*OutermostType*/,
4888 false /*EncodingProperty*/,
4889 false /*StructField*/,
4890 Extended /*EncodeBlockParameters*/,
4891 Extended /*EncodeClassNames*/);
4892}
4893
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004894/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004895/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004896bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004897 std::string& S,
4898 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004899 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004900 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00004901 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4902 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004903 // Compute size of all parameters.
4904 // Start with computing size of a pointer in number of bytes.
4905 // FIXME: There might(should) be a better way of doing this computation!
4906 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004907 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004908 // The first two arguments (self and _cmd) are pointers; account for
4909 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004910 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004911 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004912 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004913 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004914 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004915 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004916 continue;
4917
Ken Dyck40775002010-01-11 17:06:35 +00004918 assert (sz.isPositive() &&
4919 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004920 ParmOffset += sz;
4921 }
Ken Dyck40775002010-01-11 17:06:35 +00004922 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004923 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004924 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004925
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004926 // Argument types.
4927 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004928 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004929 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004930 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004931 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004932 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004933 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4934 // Use array's original type only if it has known number of
4935 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004936 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004937 PType = PVDecl->getType();
4938 } else if (PType->isFunctionType())
4939 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004940 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4941 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004942 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004943 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004944 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004945
4946 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004947}
4948
Fariborz Jahaniandad96302014-01-22 19:02:20 +00004949ObjCPropertyImplDecl *
4950ASTContext::getObjCPropertyImplDeclForPropertyDecl(
4951 const ObjCPropertyDecl *PD,
4952 const Decl *Container) const {
4953 if (!Container)
4954 return 0;
4955 if (const ObjCCategoryImplDecl *CID =
4956 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4957 for (ObjCCategoryImplDecl::propimpl_iterator
4958 i = CID->propimpl_begin(), e = CID->propimpl_end();
4959 i != e; ++i) {
4960 ObjCPropertyImplDecl *PID = *i;
4961 if (PID->getPropertyDecl() == PD)
4962 return PID;
4963 }
4964 } else {
4965 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
4966 for (ObjCCategoryImplDecl::propimpl_iterator
4967 i = OID->propimpl_begin(), e = OID->propimpl_end();
4968 i != e; ++i) {
4969 ObjCPropertyImplDecl *PID = *i;
4970 if (PID->getPropertyDecl() == PD)
4971 return PID;
4972 }
4973 }
4974 return 0;
4975}
4976
Daniel Dunbar4932b362008-08-28 04:38:10 +00004977/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004978/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004979/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4980/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004981/// Property attributes are stored as a comma-delimited C string. The simple
4982/// attributes readonly and bycopy are encoded as single characters. The
4983/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4984/// encoded as single characters, followed by an identifier. Property types
4985/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004986/// these attributes are defined by the following enumeration:
4987/// @code
4988/// enum PropertyAttributes {
4989/// kPropertyReadOnly = 'R', // property is read-only.
4990/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4991/// kPropertyByref = '&', // property is a reference to the value last assigned
4992/// kPropertyDynamic = 'D', // property is dynamic
4993/// kPropertyGetter = 'G', // followed by getter selector name
4994/// kPropertySetter = 'S', // followed by setter selector name
4995/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004996/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004997/// kPropertyWeak = 'W' // 'weak' property
4998/// kPropertyStrong = 'P' // property GC'able
4999/// kPropertyNonAtomic = 'N' // property non-atomic
5000/// };
5001/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005002void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005003 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005004 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005005 // Collect information from the property implementation decl(s).
5006 bool Dynamic = false;
5007 ObjCPropertyImplDecl *SynthesizePID = 0;
5008
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005009 if (ObjCPropertyImplDecl *PropertyImpDecl =
5010 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5011 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5012 Dynamic = true;
5013 else
5014 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005015 }
5016
5017 // FIXME: This is not very efficient.
5018 S = "T";
5019
5020 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005021 // GCC has some special rules regarding encoding of properties which
5022 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00005023 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005024 true /* outermost type */,
5025 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005026
5027 if (PD->isReadOnly()) {
5028 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005029 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5030 S += ",C";
5031 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5032 S += ",&";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005033 } else {
5034 switch (PD->getSetterKind()) {
5035 case ObjCPropertyDecl::Assign: break;
5036 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005037 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005038 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005039 }
5040 }
5041
5042 // It really isn't clear at all what this means, since properties
5043 // are "dynamic by default".
5044 if (Dynamic)
5045 S += ",D";
5046
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005047 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5048 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005049
Daniel Dunbar4932b362008-08-28 04:38:10 +00005050 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5051 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005052 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005053 }
5054
5055 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5056 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005057 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005058 }
5059
5060 if (SynthesizePID) {
5061 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5062 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005063 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005064 }
5065
5066 // FIXME: OBJCGC: weak & strong
5067}
5068
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005069/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005070/// Another legacy compatibility encoding: 32-bit longs are encoded as
5071/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005072/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5073///
5074void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005075 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005076 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005077 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005078 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005079 else
Jay Foad39c79802011-01-12 09:06:06 +00005080 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005081 PointeeTy = IntTy;
5082 }
5083 }
5084}
5085
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005086void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00005087 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005088 // We follow the behavior of gcc, expanding structures which are
5089 // directly pointed to, and expanding embedded structures. Note that
5090 // these rules are sufficient to prevent recursive encoding of the
5091 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005092 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00005093 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005094}
5095
John McCall393a78d2012-12-20 02:45:14 +00005096static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5097 BuiltinType::Kind kind) {
5098 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005099 case BuiltinType::Void: return 'v';
5100 case BuiltinType::Bool: return 'B';
5101 case BuiltinType::Char_U:
5102 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005103 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005104 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005105 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005106 case BuiltinType::UInt: return 'I';
5107 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005108 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005109 case BuiltinType::UInt128: return 'T';
5110 case BuiltinType::ULongLong: return 'Q';
5111 case BuiltinType::Char_S:
5112 case BuiltinType::SChar: return 'c';
5113 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005114 case BuiltinType::WChar_S:
5115 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005116 case BuiltinType::Int: return 'i';
5117 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005118 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005119 case BuiltinType::LongLong: return 'q';
5120 case BuiltinType::Int128: return 't';
5121 case BuiltinType::Float: return 'f';
5122 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005123 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005124 case BuiltinType::NullPtr: return '*'; // like char*
5125
5126 case BuiltinType::Half:
5127 // FIXME: potentially need @encodes for these!
5128 return ' ';
5129
5130 case BuiltinType::ObjCId:
5131 case BuiltinType::ObjCClass:
5132 case BuiltinType::ObjCSel:
5133 llvm_unreachable("@encoding ObjC primitive type");
5134
5135 // OpenCL and placeholder types don't need @encodings.
5136 case BuiltinType::OCLImage1d:
5137 case BuiltinType::OCLImage1dArray:
5138 case BuiltinType::OCLImage1dBuffer:
5139 case BuiltinType::OCLImage2d:
5140 case BuiltinType::OCLImage2dArray:
5141 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005142 case BuiltinType::OCLEvent:
Guy Benyei61054192013-02-07 10:55:47 +00005143 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005144 case BuiltinType::Dependent:
5145#define BUILTIN_TYPE(KIND, ID)
5146#define PLACEHOLDER_TYPE(KIND, ID) \
5147 case BuiltinType::KIND:
5148#include "clang/AST/BuiltinTypes.def"
5149 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005150 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005151 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005152}
5153
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005154static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5155 EnumDecl *Enum = ET->getDecl();
5156
5157 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5158 if (!Enum->isFixed())
5159 return 'i';
5160
5161 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005162 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5163 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005164}
5165
Jay Foad39c79802011-01-12 09:06:06 +00005166static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005167 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005168 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005169 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005170 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5171 // The GNU runtime requires more information; bitfields are encoded as b,
5172 // then the offset (in bits) of the first element, then the type of the
5173 // bitfield, then the size in bits. For example, in this structure:
5174 //
5175 // struct
5176 // {
5177 // int integer;
5178 // int flags:2;
5179 // };
5180 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5181 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5182 // information is not especially sensible, but we're stuck with it for
5183 // compatibility with GCC, although providing it breaks anything that
5184 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005185 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005186 const RecordDecl *RD = FD->getParent();
5187 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005188 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005189 if (const EnumType *ET = T->getAs<EnumType>())
5190 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005191 else {
5192 const BuiltinType *BT = T->castAs<BuiltinType>();
5193 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5194 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005195 }
Richard Smithcaf33902011-10-10 18:28:20 +00005196 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005197}
5198
Daniel Dunbar07d07852009-10-18 21:17:35 +00005199// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005200void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5201 bool ExpandPointedToStructures,
5202 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005203 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005204 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005205 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005206 bool StructField,
5207 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005208 bool EncodeClassNames,
5209 bool EncodePointerToObjCTypedef) const {
John McCall393a78d2012-12-20 02:45:14 +00005210 CanQualType CT = getCanonicalType(T);
5211 switch (CT->getTypeClass()) {
5212 case Type::Builtin:
5213 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005214 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005215 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005216 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5217 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5218 else
5219 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005220 return;
Mike Stump11289f42009-09-09 15:08:12 +00005221
John McCall393a78d2012-12-20 02:45:14 +00005222 case Type::Complex: {
5223 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005224 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00005225 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00005226 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005227 return;
5228 }
John McCall393a78d2012-12-20 02:45:14 +00005229
5230 case Type::Atomic: {
5231 const AtomicType *AT = T->castAs<AtomicType>();
5232 S += 'A';
5233 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5234 false, false);
5235 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005236 }
John McCall393a78d2012-12-20 02:45:14 +00005237
5238 // encoding for pointer or reference types.
5239 case Type::Pointer:
5240 case Type::LValueReference:
5241 case Type::RValueReference: {
5242 QualType PointeeTy;
5243 if (isa<PointerType>(CT)) {
5244 const PointerType *PT = T->castAs<PointerType>();
5245 if (PT->isObjCSelType()) {
5246 S += ':';
5247 return;
5248 }
5249 PointeeTy = PT->getPointeeType();
5250 } else {
5251 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5252 }
5253
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005254 bool isReadOnly = false;
5255 // For historical/compatibility reasons, the read-only qualifier of the
5256 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5257 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005258 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005259 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005260 if (OutermostType && T.isConstQualified()) {
5261 isReadOnly = true;
5262 S += 'r';
5263 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005264 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005265 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005266 while (P->getAs<PointerType>())
5267 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005268 if (P.isConstQualified()) {
5269 isReadOnly = true;
5270 S += 'r';
5271 }
5272 }
5273 if (isReadOnly) {
5274 // Another legacy compatibility encoding. Some ObjC qualifier and type
5275 // combinations need to be rearranged.
5276 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005277 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005278 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005279 }
Mike Stump11289f42009-09-09 15:08:12 +00005280
Anders Carlssond8499822007-10-29 05:01:08 +00005281 if (PointeeTy->isCharType()) {
5282 // char pointer types should be encoded as '*' unless it is a
5283 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005284 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005285 S += '*';
5286 return;
5287 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005288 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005289 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5290 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5291 S += '#';
5292 return;
5293 }
5294 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5295 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5296 S += '@';
5297 return;
5298 }
5299 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005300 }
Anders Carlssond8499822007-10-29 05:01:08 +00005301 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005302 getLegacyIntegralTypeEncoding(PointeeTy);
5303
Mike Stump11289f42009-09-09 15:08:12 +00005304 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005305 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005306 return;
5307 }
John McCall393a78d2012-12-20 02:45:14 +00005308
5309 case Type::ConstantArray:
5310 case Type::IncompleteArray:
5311 case Type::VariableArray: {
5312 const ArrayType *AT = cast<ArrayType>(CT);
5313
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005314 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005315 // Incomplete arrays are encoded as a pointer to the array element.
5316 S += '^';
5317
Mike Stump11289f42009-09-09 15:08:12 +00005318 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005319 false, ExpandStructures, FD);
5320 } else {
5321 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005322
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005323 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5324 S += llvm::utostr(CAT->getSize().getZExtValue());
5325 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005326 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005327 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5328 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005329 S += '0';
5330 }
Mike Stump11289f42009-09-09 15:08:12 +00005331
5332 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005333 false, ExpandStructures, FD);
5334 S += ']';
5335 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005336 return;
5337 }
Mike Stump11289f42009-09-09 15:08:12 +00005338
John McCall393a78d2012-12-20 02:45:14 +00005339 case Type::FunctionNoProto:
5340 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005341 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005342 return;
Mike Stump11289f42009-09-09 15:08:12 +00005343
John McCall393a78d2012-12-20 02:45:14 +00005344 case Type::Record: {
5345 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005346 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005347 // Anonymous structures print as '?'
5348 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5349 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005350 if (ClassTemplateSpecializationDecl *Spec
5351 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5352 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005353 llvm::raw_string_ostream OS(S);
5354 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005355 TemplateArgs.data(),
5356 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005357 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005358 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005359 } else {
5360 S += '?';
5361 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005362 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005363 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005364 if (!RDecl->isUnion()) {
5365 getObjCEncodingForStructureImpl(RDecl, S, FD);
5366 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005367 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005368 if (FD) {
5369 S += '"';
5370 S += Field->getNameAsString();
5371 S += '"';
5372 }
Mike Stump11289f42009-09-09 15:08:12 +00005373
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005374 // Special case bit-fields.
5375 if (Field->isBitField()) {
5376 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005377 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005378 } else {
5379 QualType qt = Field->getType();
5380 getLegacyIntegralTypeEncoding(qt);
5381 getObjCEncodingForTypeImpl(qt, S, false, true,
5382 FD, /*OutermostType*/false,
5383 /*EncodingProperty*/false,
5384 /*StructField*/true);
5385 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005386 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005387 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005388 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005389 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005390 return;
5391 }
Mike Stump11289f42009-09-09 15:08:12 +00005392
John McCall393a78d2012-12-20 02:45:14 +00005393 case Type::BlockPointer: {
5394 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005395 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005396 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005397 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005398
5399 S += '<';
5400 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005401 getObjCEncodingForTypeImpl(
5402 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5403 FD, false /* OutermostType */, EncodingProperty,
5404 false /* StructField */, EncodeBlockParameters, EncodeClassNames);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005405 // Block self
5406 S += "@?";
5407 // Block parameters
5408 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Alp Toker9cacbab2014-01-20 20:26:09 +00005409 for (FunctionProtoType::param_type_iterator I = FPT->param_type_begin(),
5410 E = FPT->param_type_end();
5411 I && (I != E); ++I) {
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005412 getObjCEncodingForTypeImpl(*I, S,
5413 ExpandPointedToStructures,
5414 ExpandStructures,
5415 FD,
5416 false /* OutermostType */,
5417 EncodingProperty,
5418 false /* StructField */,
5419 EncodeBlockParameters,
5420 EncodeClassNames);
5421 }
5422 }
5423 S += '>';
5424 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005425 return;
5426 }
Mike Stump11289f42009-09-09 15:08:12 +00005427
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005428 case Type::ObjCObject: {
5429 // hack to match legacy encoding of *id and *Class
5430 QualType Ty = getObjCObjectPointerType(CT);
5431 if (Ty->isObjCIdType()) {
5432 S += "{objc_object=}";
5433 return;
5434 }
5435 else if (Ty->isObjCClassType()) {
5436 S += "{objc_class=}";
5437 return;
5438 }
5439 }
5440
John McCall393a78d2012-12-20 02:45:14 +00005441 case Type::ObjCInterface: {
5442 // Ignore protocol qualifiers when mangling at this level.
5443 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005444
John McCall393a78d2012-12-20 02:45:14 +00005445 // The assumption seems to be that this assert will succeed
5446 // because nested levels will have filtered out 'id' and 'Class'.
5447 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005448 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005449 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005450 S += '{';
5451 const IdentifierInfo *II = OI->getIdentifier();
5452 S += II->getName();
5453 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005454 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005455 DeepCollectObjCIvars(OI, true, Ivars);
5456 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005457 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005458 if (Field->isBitField())
5459 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005460 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005461 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5462 false, false, false, false, false,
5463 EncodePointerToObjCTypedef);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005464 }
5465 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005466 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005467 }
Mike Stump11289f42009-09-09 15:08:12 +00005468
John McCall393a78d2012-12-20 02:45:14 +00005469 case Type::ObjCObjectPointer: {
5470 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005471 if (OPT->isObjCIdType()) {
5472 S += '@';
5473 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005474 }
Mike Stump11289f42009-09-09 15:08:12 +00005475
Steve Narofff0c86112009-10-28 22:03:49 +00005476 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5477 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5478 // Since this is a binary compatibility issue, need to consult with runtime
5479 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005480 S += '#';
5481 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005482 }
Mike Stump11289f42009-09-09 15:08:12 +00005483
Chris Lattnere7cabb92009-07-13 00:10:46 +00005484 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005485 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005486 ExpandPointedToStructures,
5487 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005488 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005489 // Note that we do extended encoding of protocol qualifer list
5490 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005491 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00005492 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5493 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005494 S += '<';
5495 S += (*I)->getNameAsString();
5496 S += '>';
5497 }
5498 S += '"';
5499 }
5500 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005501 }
Mike Stump11289f42009-09-09 15:08:12 +00005502
Chris Lattnere7cabb92009-07-13 00:10:46 +00005503 QualType PointeeTy = OPT->getPointeeType();
5504 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005505 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5506 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005507 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005508 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005509 // {...};
5510 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005511 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005512 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005513 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5514 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5515 DeepCollectObjCIvars(OI, true, Ivars);
5516 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5517 if (cast<FieldDecl>(Ivars[i]) == FD) {
5518 S += '{';
5519 S += OI->getIdentifier()->getName();
5520 S += '}';
5521 return;
5522 }
5523 }
5524 }
Mike Stump11289f42009-09-09 15:08:12 +00005525 getObjCEncodingForTypeImpl(PointeeTy, S,
5526 false, ExpandPointedToStructures,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005527 NULL,
5528 false, false, false, false, false,
5529 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005530 return;
5531 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005532
5533 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005534 if (OPT->getInterfaceDecl() &&
5535 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005536 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005537 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00005538 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5539 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005540 S += '<';
5541 S += (*I)->getNameAsString();
5542 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005543 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005544 S += '"';
5545 }
5546 return;
5547 }
Mike Stump11289f42009-09-09 15:08:12 +00005548
John McCalla9e6e8d2010-05-17 23:56:34 +00005549 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005550 // FIXME: we shoul do better than that. 'M' is available.
5551 case Type::MemberPointer:
John McCalla9e6e8d2010-05-17 23:56:34 +00005552 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005553
John McCall393a78d2012-12-20 02:45:14 +00005554 case Type::Vector:
5555 case Type::ExtVector:
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005556 // This matches gcc's encoding, even though technically it is
5557 // insufficient.
5558 // FIXME. We should do a better job than gcc.
5559 return;
John McCall393a78d2012-12-20 02:45:14 +00005560
Richard Smith27d807c2013-04-30 13:56:41 +00005561 case Type::Auto:
5562 // We could see an undeduced auto type here during error recovery.
5563 // Just ignore it.
5564 return;
5565
John McCall393a78d2012-12-20 02:45:14 +00005566#define ABSTRACT_TYPE(KIND, BASE)
5567#define TYPE(KIND, BASE)
5568#define DEPENDENT_TYPE(KIND, BASE) \
5569 case Type::KIND:
5570#define NON_CANONICAL_TYPE(KIND, BASE) \
5571 case Type::KIND:
5572#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5573 case Type::KIND:
5574#include "clang/AST/TypeNodes.def"
5575 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005576 }
John McCall393a78d2012-12-20 02:45:14 +00005577 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005578}
5579
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005580void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5581 std::string &S,
5582 const FieldDecl *FD,
5583 bool includeVBases) const {
5584 assert(RDecl && "Expected non-null RecordDecl");
5585 assert(!RDecl->isUnion() && "Should not be called for unions");
5586 if (!RDecl->getDefinition())
5587 return;
5588
5589 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5590 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5591 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5592
5593 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00005594 for (const auto &BI : CXXRec->bases()) {
5595 if (!BI.isVirtual()) {
5596 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005597 if (base->isEmpty())
5598 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005599 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005600 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5601 std::make_pair(offs, base));
5602 }
5603 }
5604 }
5605
5606 unsigned i = 0;
5607 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5608 FieldEnd = RDecl->field_end();
5609 Field != FieldEnd; ++Field, ++i) {
5610 uint64_t offs = layout.getFieldOffset(i);
5611 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005612 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005613 }
5614
5615 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005616 for (const auto &BI : CXXRec->vbases()) {
5617 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005618 if (base->isEmpty())
5619 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005620 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005621 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5622 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005623 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5624 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005625 }
5626 }
5627
5628 CharUnits size;
5629 if (CXXRec) {
5630 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5631 } else {
5632 size = layout.getSize();
5633 }
5634
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005635#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005636 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005637#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005638 std::multimap<uint64_t, NamedDecl *>::iterator
5639 CurLayObj = FieldOrBaseOffsets.begin();
5640
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005641 if (CXXRec && CXXRec->isDynamicClass() &&
5642 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005643 if (FD) {
5644 S += "\"_vptr$";
5645 std::string recname = CXXRec->getNameAsString();
5646 if (recname.empty()) recname = "?";
5647 S += recname;
5648 S += '"';
5649 }
5650 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005651#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005652 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005653#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005654 }
5655
5656 if (!RDecl->hasFlexibleArrayMember()) {
5657 // Mark the end of the structure.
5658 uint64_t offs = toBits(size);
5659 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5660 std::make_pair(offs, (NamedDecl*)0));
5661 }
5662
5663 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005664#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005665 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005666 if (CurOffs < CurLayObj->first) {
5667 uint64_t padding = CurLayObj->first - CurOffs;
5668 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5669 // packing/alignment of members is different that normal, in which case
5670 // the encoding will be out-of-sync with the real layout.
5671 // If the runtime switches to just consider the size of types without
5672 // taking into account alignment, we could make padding explicit in the
5673 // encoding (e.g. using arrays of chars). The encoding strings would be
5674 // longer then though.
5675 CurOffs += padding;
5676 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005677#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005678
5679 NamedDecl *dcl = CurLayObj->second;
5680 if (dcl == 0)
5681 break; // reached end of structure.
5682
5683 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5684 // We expand the bases without their virtual bases since those are going
5685 // in the initial structure. Note that this differs from gcc which
5686 // expands virtual bases each time one is encountered in the hierarchy,
5687 // making the encoding type bigger than it really is.
5688 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005689 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005690#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005691 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005692#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005693 } else {
5694 FieldDecl *field = cast<FieldDecl>(dcl);
5695 if (FD) {
5696 S += '"';
5697 S += field->getNameAsString();
5698 S += '"';
5699 }
5700
5701 if (field->isBitField()) {
5702 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005703#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00005704 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005705#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005706 } else {
5707 QualType qt = field->getType();
5708 getLegacyIntegralTypeEncoding(qt);
5709 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5710 /*OutermostType*/false,
5711 /*EncodingProperty*/false,
5712 /*StructField*/true);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005713#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005714 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005715#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005716 }
5717 }
5718 }
5719}
5720
Mike Stump11289f42009-09-09 15:08:12 +00005721void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005722 std::string& S) const {
5723 if (QT & Decl::OBJC_TQ_In)
5724 S += 'n';
5725 if (QT & Decl::OBJC_TQ_Inout)
5726 S += 'N';
5727 if (QT & Decl::OBJC_TQ_Out)
5728 S += 'o';
5729 if (QT & Decl::OBJC_TQ_Bycopy)
5730 S += 'O';
5731 if (QT & Decl::OBJC_TQ_Byref)
5732 S += 'R';
5733 if (QT & Decl::OBJC_TQ_Oneway)
5734 S += 'V';
5735}
5736
Douglas Gregor3ea72692011-08-12 05:46:01 +00005737TypedefDecl *ASTContext::getObjCIdDecl() const {
5738 if (!ObjCIdDecl) {
5739 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5740 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005741 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00005742 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00005743 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005744}
5745
Douglas Gregor52e02802011-08-12 06:17:30 +00005746TypedefDecl *ASTContext::getObjCSelDecl() const {
5747 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005748 QualType T = getPointerType(ObjCBuiltinSelTy);
5749 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00005750 }
5751 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005752}
5753
Douglas Gregor0a586182011-08-12 05:59:41 +00005754TypedefDecl *ASTContext::getObjCClassDecl() const {
5755 if (!ObjCClassDecl) {
5756 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5757 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005758 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00005759 }
Douglas Gregor0a586182011-08-12 05:59:41 +00005760 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005761}
5762
Douglas Gregord53ae832012-01-17 18:09:05 +00005763ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5764 if (!ObjCProtocolClassDecl) {
5765 ObjCProtocolClassDecl
5766 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5767 SourceLocation(),
5768 &Idents.get("Protocol"),
5769 /*PrevDecl=*/0,
5770 SourceLocation(), true);
5771 }
5772
5773 return ObjCProtocolClassDecl;
5774}
5775
Meador Inge5d3fb222012-06-16 03:34:49 +00005776//===----------------------------------------------------------------------===//
5777// __builtin_va_list Construction Functions
5778//===----------------------------------------------------------------------===//
5779
5780static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5781 // typedef char* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005782 QualType T = Context->getPointerType(Context->CharTy);
5783 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005784}
5785
5786static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5787 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005788 QualType T = Context->getPointerType(Context->VoidTy);
5789 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005790}
5791
Tim Northover9bb857a2013-01-31 12:13:10 +00005792static TypedefDecl *
5793CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005794 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00005795 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005796 if (Context->getLangOpts().CPlusPlus) {
5797 // namespace std { struct __va_list {
5798 NamespaceDecl *NS;
5799 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5800 Context->getTranslationUnitDecl(),
5801 /*Inline*/false, SourceLocation(),
5802 SourceLocation(), &Context->Idents.get("std"),
5803 /*PrevDecl*/0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005804 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00005805 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00005806 }
5807
5808 VaListTagDecl->startDefinition();
5809
5810 const size_t NumFields = 5;
5811 QualType FieldTypes[NumFields];
5812 const char *FieldNames[NumFields];
5813
5814 // void *__stack;
5815 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5816 FieldNames[0] = "__stack";
5817
5818 // void *__gr_top;
5819 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5820 FieldNames[1] = "__gr_top";
5821
5822 // void *__vr_top;
5823 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5824 FieldNames[2] = "__vr_top";
5825
5826 // int __gr_offs;
5827 FieldTypes[3] = Context->IntTy;
5828 FieldNames[3] = "__gr_offs";
5829
5830 // int __vr_offs;
5831 FieldTypes[4] = Context->IntTy;
5832 FieldNames[4] = "__vr_offs";
5833
5834 // Create fields
5835 for (unsigned i = 0; i < NumFields; ++i) {
5836 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5837 VaListTagDecl,
5838 SourceLocation(),
5839 SourceLocation(),
5840 &Context->Idents.get(FieldNames[i]),
5841 FieldTypes[i], /*TInfo=*/0,
5842 /*BitWidth=*/0,
5843 /*Mutable=*/false,
5844 ICIS_NoInit);
5845 Field->setAccess(AS_public);
5846 VaListTagDecl->addDecl(Field);
5847 }
5848 VaListTagDecl->completeDefinition();
5849 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5850 Context->VaListTagTy = VaListTagType;
5851
5852 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005853 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005854}
5855
Meador Inge5d3fb222012-06-16 03:34:49 +00005856static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5857 // typedef struct __va_list_tag {
5858 RecordDecl *VaListTagDecl;
5859
Alp Toker2dea15b2013-12-17 01:22:38 +00005860 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005861 VaListTagDecl->startDefinition();
5862
5863 const size_t NumFields = 5;
5864 QualType FieldTypes[NumFields];
5865 const char *FieldNames[NumFields];
5866
5867 // unsigned char gpr;
5868 FieldTypes[0] = Context->UnsignedCharTy;
5869 FieldNames[0] = "gpr";
5870
5871 // unsigned char fpr;
5872 FieldTypes[1] = Context->UnsignedCharTy;
5873 FieldNames[1] = "fpr";
5874
5875 // unsigned short reserved;
5876 FieldTypes[2] = Context->UnsignedShortTy;
5877 FieldNames[2] = "reserved";
5878
5879 // void* overflow_arg_area;
5880 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5881 FieldNames[3] = "overflow_arg_area";
5882
5883 // void* reg_save_area;
5884 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5885 FieldNames[4] = "reg_save_area";
5886
5887 // Create fields
5888 for (unsigned i = 0; i < NumFields; ++i) {
5889 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5890 SourceLocation(),
5891 SourceLocation(),
5892 &Context->Idents.get(FieldNames[i]),
5893 FieldTypes[i], /*TInfo=*/0,
5894 /*BitWidth=*/0,
5895 /*Mutable=*/false,
5896 ICIS_NoInit);
5897 Field->setAccess(AS_public);
5898 VaListTagDecl->addDecl(Field);
5899 }
5900 VaListTagDecl->completeDefinition();
5901 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005902 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005903
5904 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00005905 TypedefDecl *VaListTagTypedefDecl =
5906 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
5907
Meador Inge5d3fb222012-06-16 03:34:49 +00005908 QualType VaListTagTypedefType =
5909 Context->getTypedefType(VaListTagTypedefDecl);
5910
5911 // typedef __va_list_tag __builtin_va_list[1];
5912 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5913 QualType VaListTagArrayType
5914 = Context->getConstantArrayType(VaListTagTypedefType,
5915 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005916 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005917}
5918
5919static TypedefDecl *
5920CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5921 // typedef struct __va_list_tag {
5922 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00005923 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005924 VaListTagDecl->startDefinition();
5925
5926 const size_t NumFields = 4;
5927 QualType FieldTypes[NumFields];
5928 const char *FieldNames[NumFields];
5929
5930 // unsigned gp_offset;
5931 FieldTypes[0] = Context->UnsignedIntTy;
5932 FieldNames[0] = "gp_offset";
5933
5934 // unsigned fp_offset;
5935 FieldTypes[1] = Context->UnsignedIntTy;
5936 FieldNames[1] = "fp_offset";
5937
5938 // void* overflow_arg_area;
5939 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5940 FieldNames[2] = "overflow_arg_area";
5941
5942 // void* reg_save_area;
5943 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5944 FieldNames[3] = "reg_save_area";
5945
5946 // Create fields
5947 for (unsigned i = 0; i < NumFields; ++i) {
5948 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5949 VaListTagDecl,
5950 SourceLocation(),
5951 SourceLocation(),
5952 &Context->Idents.get(FieldNames[i]),
5953 FieldTypes[i], /*TInfo=*/0,
5954 /*BitWidth=*/0,
5955 /*Mutable=*/false,
5956 ICIS_NoInit);
5957 Field->setAccess(AS_public);
5958 VaListTagDecl->addDecl(Field);
5959 }
5960 VaListTagDecl->completeDefinition();
5961 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005962 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005963
5964 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00005965 TypedefDecl *VaListTagTypedefDecl =
5966 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
5967
Meador Inge5d3fb222012-06-16 03:34:49 +00005968 QualType VaListTagTypedefType =
5969 Context->getTypedefType(VaListTagTypedefDecl);
5970
5971 // typedef __va_list_tag __builtin_va_list[1];
5972 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5973 QualType VaListTagArrayType
5974 = Context->getConstantArrayType(VaListTagTypedefType,
5975 Size, ArrayType::Normal,0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005976 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005977}
5978
5979static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5980 // typedef int __builtin_va_list[4];
5981 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5982 QualType IntArrayType
5983 = Context->getConstantArrayType(Context->IntTy,
5984 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005985 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005986}
5987
Logan Chien57086ce2012-10-10 06:56:20 +00005988static TypedefDecl *
5989CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005990 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00005991 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00005992 if (Context->getLangOpts().CPlusPlus) {
5993 // namespace std { struct __va_list {
5994 NamespaceDecl *NS;
5995 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5996 Context->getTranslationUnitDecl(),
5997 /*Inline*/false, SourceLocation(),
5998 SourceLocation(), &Context->Idents.get("std"),
5999 /*PrevDecl*/0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006000 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006001 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006002 }
6003
6004 VaListDecl->startDefinition();
6005
6006 // void * __ap;
6007 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6008 VaListDecl,
6009 SourceLocation(),
6010 SourceLocation(),
6011 &Context->Idents.get("__ap"),
6012 Context->getPointerType(Context->VoidTy),
6013 /*TInfo=*/0,
6014 /*BitWidth=*/0,
6015 /*Mutable=*/false,
6016 ICIS_NoInit);
6017 Field->setAccess(AS_public);
6018 VaListDecl->addDecl(Field);
6019
6020 // };
6021 VaListDecl->completeDefinition();
6022
6023 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006024 QualType T = Context->getRecordType(VaListDecl);
6025 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006026}
6027
Ulrich Weigand47445072013-05-06 16:26:41 +00006028static TypedefDecl *
6029CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6030 // typedef struct __va_list_tag {
6031 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006032 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006033 VaListTagDecl->startDefinition();
6034
6035 const size_t NumFields = 4;
6036 QualType FieldTypes[NumFields];
6037 const char *FieldNames[NumFields];
6038
6039 // long __gpr;
6040 FieldTypes[0] = Context->LongTy;
6041 FieldNames[0] = "__gpr";
6042
6043 // long __fpr;
6044 FieldTypes[1] = Context->LongTy;
6045 FieldNames[1] = "__fpr";
6046
6047 // void *__overflow_arg_area;
6048 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6049 FieldNames[2] = "__overflow_arg_area";
6050
6051 // void *__reg_save_area;
6052 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6053 FieldNames[3] = "__reg_save_area";
6054
6055 // Create fields
6056 for (unsigned i = 0; i < NumFields; ++i) {
6057 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6058 VaListTagDecl,
6059 SourceLocation(),
6060 SourceLocation(),
6061 &Context->Idents.get(FieldNames[i]),
6062 FieldTypes[i], /*TInfo=*/0,
6063 /*BitWidth=*/0,
6064 /*Mutable=*/false,
6065 ICIS_NoInit);
6066 Field->setAccess(AS_public);
6067 VaListTagDecl->addDecl(Field);
6068 }
6069 VaListTagDecl->completeDefinition();
6070 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6071 Context->VaListTagTy = VaListTagType;
6072
6073 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006074 TypedefDecl *VaListTagTypedefDecl =
6075 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006076 QualType VaListTagTypedefType =
6077 Context->getTypedefType(VaListTagTypedefDecl);
6078
6079 // typedef __va_list_tag __builtin_va_list[1];
6080 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6081 QualType VaListTagArrayType
6082 = Context->getConstantArrayType(VaListTagTypedefType,
6083 Size, ArrayType::Normal,0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006084
Alp Toker56b5cc92013-12-15 10:36:26 +00006085 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006086}
6087
Meador Inge5d3fb222012-06-16 03:34:49 +00006088static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6089 TargetInfo::BuiltinVaListKind Kind) {
6090 switch (Kind) {
6091 case TargetInfo::CharPtrBuiltinVaList:
6092 return CreateCharPtrBuiltinVaListDecl(Context);
6093 case TargetInfo::VoidPtrBuiltinVaList:
6094 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006095 case TargetInfo::AArch64ABIBuiltinVaList:
6096 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006097 case TargetInfo::PowerABIBuiltinVaList:
6098 return CreatePowerABIBuiltinVaListDecl(Context);
6099 case TargetInfo::X86_64ABIBuiltinVaList:
6100 return CreateX86_64ABIBuiltinVaListDecl(Context);
6101 case TargetInfo::PNaClABIBuiltinVaList:
6102 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006103 case TargetInfo::AAPCSABIBuiltinVaList:
6104 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006105 case TargetInfo::SystemZBuiltinVaList:
6106 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006107 }
6108
6109 llvm_unreachable("Unhandled __builtin_va_list type kind");
6110}
6111
6112TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006113 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006114 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006115 assert(BuiltinVaListDecl->isImplicit());
6116 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006117
6118 return BuiltinVaListDecl;
6119}
6120
Meador Ingecfb60902012-07-01 15:57:25 +00006121QualType ASTContext::getVaListTagType() const {
6122 // Force the creation of VaListTagTy by building the __builtin_va_list
6123 // declaration.
6124 if (VaListTagTy.isNull())
6125 (void) getBuiltinVaListDecl();
6126
6127 return VaListTagTy;
6128}
6129
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006130void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006131 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006132 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006133
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006134 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006135}
6136
John McCalld28ae272009-12-02 08:04:21 +00006137/// \brief Retrieve the template name that corresponds to a non-empty
6138/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006139TemplateName
6140ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6141 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006142 unsigned size = End - Begin;
6143 assert(size > 1 && "set is not overloaded!");
6144
6145 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6146 size * sizeof(FunctionTemplateDecl*));
6147 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6148
6149 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006150 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006151 NamedDecl *D = *I;
6152 assert(isa<FunctionTemplateDecl>(D) ||
6153 (isa<UsingShadowDecl>(D) &&
6154 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6155 *Storage++ = D;
6156 }
6157
6158 return TemplateName(OT);
6159}
6160
Douglas Gregordc572a32009-03-30 22:58:21 +00006161/// \brief Retrieve the template name that represents a qualified
6162/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006163TemplateName
6164ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6165 bool TemplateKeyword,
6166 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006167 assert(NNS && "Missing nested-name-specifier in qualified template name");
6168
Douglas Gregorc42075a2010-02-04 18:10:26 +00006169 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006170 llvm::FoldingSetNodeID ID;
6171 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6172
6173 void *InsertPos = 0;
6174 QualifiedTemplateName *QTN =
6175 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6176 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006177 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6178 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006179 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6180 }
6181
6182 return TemplateName(QTN);
6183}
6184
6185/// \brief Retrieve the template name that represents a dependent
6186/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006187TemplateName
6188ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6189 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006190 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006191 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006192
6193 llvm::FoldingSetNodeID ID;
6194 DependentTemplateName::Profile(ID, NNS, Name);
6195
6196 void *InsertPos = 0;
6197 DependentTemplateName *QTN =
6198 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6199
6200 if (QTN)
6201 return TemplateName(QTN);
6202
6203 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6204 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006205 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6206 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006207 } else {
6208 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006209 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6210 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006211 DependentTemplateName *CheckQTN =
6212 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6213 assert(!CheckQTN && "Dependent type name canonicalization broken");
6214 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006215 }
6216
6217 DependentTemplateNames.InsertNode(QTN, InsertPos);
6218 return TemplateName(QTN);
6219}
6220
Douglas Gregor71395fa2009-11-04 00:56:37 +00006221/// \brief Retrieve the template name that represents a dependent
6222/// template name such as \c MetaFun::template operator+.
6223TemplateName
6224ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006225 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006226 assert((!NNS || NNS->isDependent()) &&
6227 "Nested name specifier must be dependent");
6228
6229 llvm::FoldingSetNodeID ID;
6230 DependentTemplateName::Profile(ID, NNS, Operator);
6231
6232 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006233 DependentTemplateName *QTN
6234 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006235
6236 if (QTN)
6237 return TemplateName(QTN);
6238
6239 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6240 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006241 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6242 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006243 } else {
6244 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006245 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6246 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006247
6248 DependentTemplateName *CheckQTN
6249 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6250 assert(!CheckQTN && "Dependent template name canonicalization broken");
6251 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006252 }
6253
6254 DependentTemplateNames.InsertNode(QTN, InsertPos);
6255 return TemplateName(QTN);
6256}
6257
Douglas Gregor5590be02011-01-15 06:45:20 +00006258TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006259ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6260 TemplateName replacement) const {
6261 llvm::FoldingSetNodeID ID;
6262 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6263
6264 void *insertPos = 0;
6265 SubstTemplateTemplateParmStorage *subst
6266 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6267
6268 if (!subst) {
6269 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6270 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6271 }
6272
6273 return TemplateName(subst);
6274}
6275
6276TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006277ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6278 const TemplateArgument &ArgPack) const {
6279 ASTContext &Self = const_cast<ASTContext &>(*this);
6280 llvm::FoldingSetNodeID ID;
6281 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6282
6283 void *InsertPos = 0;
6284 SubstTemplateTemplateParmPackStorage *Subst
6285 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6286
6287 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006288 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006289 ArgPack.pack_size(),
6290 ArgPack.pack_begin());
6291 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6292 }
6293
6294 return TemplateName(Subst);
6295}
6296
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006297/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006298/// TargetInfo, produce the corresponding type. The unsigned @p Type
6299/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006300CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006301 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006302 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006303 case TargetInfo::SignedChar: return SignedCharTy;
6304 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006305 case TargetInfo::SignedShort: return ShortTy;
6306 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6307 case TargetInfo::SignedInt: return IntTy;
6308 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6309 case TargetInfo::SignedLong: return LongTy;
6310 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6311 case TargetInfo::SignedLongLong: return LongLongTy;
6312 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6313 }
6314
David Blaikie83d382b2011-09-23 05:06:16 +00006315 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006316}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006317
6318//===----------------------------------------------------------------------===//
6319// Type Predicates.
6320//===----------------------------------------------------------------------===//
6321
Fariborz Jahanian96207692009-02-18 21:49:28 +00006322/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6323/// garbage collection attribute.
6324///
John McCall553d45a2011-01-12 00:34:59 +00006325Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006326 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006327 return Qualifiers::GCNone;
6328
David Blaikiebbafb8a2012-03-11 07:00:24 +00006329 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006330 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6331
6332 // Default behaviour under objective-C's gc is for ObjC pointers
6333 // (or pointers to them) be treated as though they were declared
6334 // as __strong.
6335 if (GCAttrs == Qualifiers::GCNone) {
6336 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6337 return Qualifiers::Strong;
6338 else if (Ty->isPointerType())
6339 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6340 } else {
6341 // It's not valid to set GC attributes on anything that isn't a
6342 // pointer.
6343#ifndef NDEBUG
6344 QualType CT = Ty->getCanonicalTypeInternal();
6345 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6346 CT = AT->getElementType();
6347 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6348#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006349 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006350 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006351}
6352
Chris Lattner49af6a42008-04-07 06:51:04 +00006353//===----------------------------------------------------------------------===//
6354// Type Compatibility Testing
6355//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006356
Mike Stump11289f42009-09-09 15:08:12 +00006357/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006358/// compatible.
6359static bool areCompatVectorTypes(const VectorType *LHS,
6360 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006361 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006362 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006363 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006364}
6365
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006366bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6367 QualType SecondVec) {
6368 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6369 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6370
6371 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6372 return true;
6373
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006374 // Treat Neon vector types and most AltiVec vector types as if they are the
6375 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006376 const VectorType *First = FirstVec->getAs<VectorType>();
6377 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006378 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006379 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006380 First->getVectorKind() != VectorType::AltiVecPixel &&
6381 First->getVectorKind() != VectorType::AltiVecBool &&
6382 Second->getVectorKind() != VectorType::AltiVecPixel &&
6383 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006384 return true;
6385
6386 return false;
6387}
6388
Steve Naroff8e6aee52009-07-23 01:01:38 +00006389//===----------------------------------------------------------------------===//
6390// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6391//===----------------------------------------------------------------------===//
6392
6393/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6394/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006395bool
6396ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6397 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006398 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006399 return true;
6400 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6401 E = rProto->protocol_end(); PI != E; ++PI)
6402 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6403 return true;
6404 return false;
6405}
6406
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006407/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6408/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006409bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6410 QualType rhs) {
6411 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6412 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6413 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6414
6415 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6416 E = lhsQID->qual_end(); I != E; ++I) {
6417 bool match = false;
6418 ObjCProtocolDecl *lhsProto = *I;
6419 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6420 E = rhsOPT->qual_end(); J != E; ++J) {
6421 ObjCProtocolDecl *rhsProto = *J;
6422 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6423 match = true;
6424 break;
6425 }
6426 }
6427 if (!match)
6428 return false;
6429 }
6430 return true;
6431}
6432
Steve Naroff8e6aee52009-07-23 01:01:38 +00006433/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6434/// ObjCQualifiedIDType.
6435bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6436 bool compare) {
6437 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006438 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006439 lhs->isObjCIdType() || lhs->isObjCClassType())
6440 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006441 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006442 rhs->isObjCIdType() || rhs->isObjCClassType())
6443 return true;
6444
6445 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006446 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006447
Steve Naroff8e6aee52009-07-23 01:01:38 +00006448 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006449
Steve Naroff8e6aee52009-07-23 01:01:38 +00006450 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006451 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006452 // make sure we check the class hierarchy.
6453 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6454 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6455 E = lhsQID->qual_end(); I != E; ++I) {
6456 // when comparing an id<P> on lhs with a static type on rhs,
6457 // see if static class implements all of id's protocols, directly or
6458 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006459 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006460 return false;
6461 }
6462 }
6463 // If there are no qualifiers and no interface, we have an 'id'.
6464 return true;
6465 }
Mike Stump11289f42009-09-09 15:08:12 +00006466 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006467 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6468 E = lhsQID->qual_end(); I != E; ++I) {
6469 ObjCProtocolDecl *lhsProto = *I;
6470 bool match = false;
6471
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.
6475 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6476 E = rhsOPT->qual_end(); J != E; ++J) {
6477 ObjCProtocolDecl *rhsProto = *J;
6478 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6479 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6480 match = true;
6481 break;
6482 }
6483 }
Mike Stump11289f42009-09-09 15:08:12 +00006484 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006485 // make sure we check the class hierarchy.
6486 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6487 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6488 E = lhsQID->qual_end(); I != E; ++I) {
6489 // when comparing an id<P> on lhs with a static type on rhs,
6490 // see if static class implements all of id's protocols, directly or
6491 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006492 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006493 match = true;
6494 break;
6495 }
6496 }
6497 }
6498 if (!match)
6499 return false;
6500 }
Mike Stump11289f42009-09-09 15:08:12 +00006501
Steve Naroff8e6aee52009-07-23 01:01:38 +00006502 return true;
6503 }
Mike Stump11289f42009-09-09 15:08:12 +00006504
Steve Naroff8e6aee52009-07-23 01:01:38 +00006505 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6506 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6507
Mike Stump11289f42009-09-09 15:08:12 +00006508 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006509 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006510 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006511 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6512 E = lhsOPT->qual_end(); I != E; ++I) {
6513 ObjCProtocolDecl *lhsProto = *I;
6514 bool match = false;
6515
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006516 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006517 // see if static class implements all of id's protocols, directly or
6518 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006519 // First, lhs protocols in the qualifier list must be found, direct
6520 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006521 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6522 E = rhsQID->qual_end(); J != E; ++J) {
6523 ObjCProtocolDecl *rhsProto = *J;
6524 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6525 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6526 match = true;
6527 break;
6528 }
6529 }
6530 if (!match)
6531 return false;
6532 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006533
6534 // Static class's protocols, or its super class or category protocols
6535 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6536 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6537 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6538 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6539 // This is rather dubious but matches gcc's behavior. If lhs has
6540 // no type qualifier and its class has no static protocol(s)
6541 // assume that it is mismatch.
6542 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6543 return false;
6544 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6545 LHSInheritedProtocols.begin(),
6546 E = LHSInheritedProtocols.end(); I != E; ++I) {
6547 bool match = false;
6548 ObjCProtocolDecl *lhsProto = (*I);
6549 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6550 E = rhsQID->qual_end(); J != E; ++J) {
6551 ObjCProtocolDecl *rhsProto = *J;
6552 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6553 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6554 match = true;
6555 break;
6556 }
6557 }
6558 if (!match)
6559 return false;
6560 }
6561 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006562 return true;
6563 }
6564 return false;
6565}
6566
Eli Friedman47f77112008-08-22 00:56:42 +00006567/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006568/// compatible for assignment from RHS to LHS. This handles validation of any
6569/// protocol qualifiers on the LHS or RHS.
6570///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006571bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6572 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006573 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6574 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6575
Steve Naroff1329fa02009-07-15 18:40:39 +00006576 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006577 if (LHS->isObjCUnqualifiedIdOrClass() ||
6578 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006579 return true;
6580
John McCall8b07ec22010-05-15 11:32:37 +00006581 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006582 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6583 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006584 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006585
6586 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6587 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6588 QualType(RHSOPT,0));
6589
John McCall8b07ec22010-05-15 11:32:37 +00006590 // If we have 2 user-defined types, fall into that path.
6591 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006592 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006593
Steve Naroff8e6aee52009-07-23 01:01:38 +00006594 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006595}
6596
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006597/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006598/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006599/// arguments in block literals. When passed as arguments, passing 'A*' where
6600/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6601/// not OK. For the return type, the opposite is not OK.
6602bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6603 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006604 const ObjCObjectPointerType *RHSOPT,
6605 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006606 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006607 return true;
6608
6609 if (LHSOPT->isObjCBuiltinType()) {
6610 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6611 }
6612
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006613 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006614 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6615 QualType(RHSOPT,0),
6616 false);
6617
6618 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6619 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6620 if (LHS && RHS) { // We have 2 user-defined types.
6621 if (LHS != RHS) {
6622 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006623 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006624 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006625 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006626 }
6627 else
6628 return true;
6629 }
6630 return false;
6631}
6632
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006633/// getIntersectionOfProtocols - This routine finds the intersection of set
6634/// of protocols inherited from two distinct objective-c pointer objects.
6635/// It is used to build composite qualifier list of the composite type of
6636/// the conditional expression involving two objective-c pointer objects.
6637static
6638void getIntersectionOfProtocols(ASTContext &Context,
6639 const ObjCObjectPointerType *LHSOPT,
6640 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006641 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006642
John McCall8b07ec22010-05-15 11:32:37 +00006643 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6644 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6645 assert(LHS->getInterface() && "LHS must have an interface base");
6646 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006647
6648 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6649 unsigned LHSNumProtocols = LHS->getNumProtocols();
6650 if (LHSNumProtocols > 0)
6651 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6652 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006653 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006654 Context.CollectInheritedProtocols(LHS->getInterface(),
6655 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006656 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6657 LHSInheritedProtocols.end());
6658 }
6659
6660 unsigned RHSNumProtocols = RHS->getNumProtocols();
6661 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006662 ObjCProtocolDecl **RHSProtocols =
6663 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006664 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6665 if (InheritedProtocolSet.count(RHSProtocols[i]))
6666 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006667 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006668 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006669 Context.CollectInheritedProtocols(RHS->getInterface(),
6670 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006671 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6672 RHSInheritedProtocols.begin(),
6673 E = RHSInheritedProtocols.end(); I != E; ++I)
6674 if (InheritedProtocolSet.count((*I)))
6675 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006676 }
6677}
6678
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006679/// areCommonBaseCompatible - Returns common base class of the two classes if
6680/// one found. Note that this is O'2 algorithm. But it will be called as the
6681/// last type comparison in a ?-exp of ObjC pointer types before a
6682/// warning is issued. So, its invokation is extremely rare.
6683QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006684 const ObjCObjectPointerType *Lptr,
6685 const ObjCObjectPointerType *Rptr) {
6686 const ObjCObjectType *LHS = Lptr->getObjectType();
6687 const ObjCObjectType *RHS = Rptr->getObjectType();
6688 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6689 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006690 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006691 return QualType();
6692
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006693 do {
John McCall8b07ec22010-05-15 11:32:37 +00006694 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006695 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006696 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006697 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6698
6699 QualType Result = QualType(LHS, 0);
6700 if (!Protocols.empty())
6701 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6702 Result = getObjCObjectPointerType(Result);
6703 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006704 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006705 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006706
6707 return QualType();
6708}
6709
John McCall8b07ec22010-05-15 11:32:37 +00006710bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6711 const ObjCObjectType *RHS) {
6712 assert(LHS->getInterface() && "LHS is not an interface type");
6713 assert(RHS->getInterface() && "RHS is not an interface type");
6714
Chris Lattner49af6a42008-04-07 06:51:04 +00006715 // Verify that the base decls are compatible: the RHS must be a subclass of
6716 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006717 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006718 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006719
Chris Lattner49af6a42008-04-07 06:51:04 +00006720 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6721 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006722 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006723 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006724
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006725 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6726 // more detailed analysis is required.
6727 if (RHS->getNumProtocols() == 0) {
6728 // OK, if LHS is a superclass of RHS *and*
6729 // this superclass is assignment compatible with LHS.
6730 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006731 bool IsSuperClass =
6732 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6733 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006734 // OK if conversion of LHS to SuperClass results in narrowing of types
6735 // ; i.e., SuperClass may implement at least one of the protocols
6736 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6737 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6738 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006739 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006740 // If super class has no protocols, it is not a match.
6741 if (SuperClassInheritedProtocols.empty())
6742 return false;
6743
6744 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6745 LHSPE = LHS->qual_end();
6746 LHSPI != LHSPE; LHSPI++) {
6747 bool SuperImplementsProtocol = false;
6748 ObjCProtocolDecl *LHSProto = (*LHSPI);
6749
6750 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6751 SuperClassInheritedProtocols.begin(),
6752 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6753 ObjCProtocolDecl *SuperClassProto = (*I);
6754 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6755 SuperImplementsProtocol = true;
6756 break;
6757 }
6758 }
6759 if (!SuperImplementsProtocol)
6760 return false;
6761 }
6762 return true;
6763 }
6764 return false;
6765 }
Mike Stump11289f42009-09-09 15:08:12 +00006766
John McCall8b07ec22010-05-15 11:32:37 +00006767 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6768 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006769 LHSPI != LHSPE; LHSPI++) {
6770 bool RHSImplementsProtocol = false;
6771
6772 // If the RHS doesn't implement the protocol on the left, the types
6773 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006774 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6775 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006776 RHSPI != RHSPE; RHSPI++) {
6777 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006778 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006779 break;
6780 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006781 }
6782 // FIXME: For better diagnostics, consider passing back the protocol name.
6783 if (!RHSImplementsProtocol)
6784 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006785 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006786 // The RHS implements all protocols listed on the LHS.
6787 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006788}
6789
Steve Naroffb7605152009-02-12 17:52:19 +00006790bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6791 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006792 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6793 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006794
Steve Naroff7cae42b2009-07-10 23:34:53 +00006795 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006796 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006797
6798 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6799 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006800}
6801
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006802bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6803 return canAssignObjCInterfaces(
6804 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6805 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6806}
6807
Mike Stump11289f42009-09-09 15:08:12 +00006808/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006809/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006810/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006811/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006812bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6813 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006814 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006815 return hasSameType(LHS, RHS);
6816
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006817 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006818}
6819
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006820bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006821 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006822}
6823
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006824bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6825 return !mergeTypes(LHS, RHS, true).isNull();
6826}
6827
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006828/// mergeTransparentUnionType - if T is a transparent union type and a member
6829/// of T is compatible with SubType, return the merged type, else return
6830/// QualType()
6831QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6832 bool OfBlockPointer,
6833 bool Unqualified) {
6834 if (const RecordType *UT = T->getAsUnionType()) {
6835 RecordDecl *UD = UT->getDecl();
6836 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006837 for (const auto *I : UD->fields()) {
6838 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006839 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6840 if (!MT.isNull())
6841 return MT;
6842 }
6843 }
6844 }
6845
6846 return QualType();
6847}
6848
Alp Toker9cacbab2014-01-20 20:26:09 +00006849/// mergeFunctionParameterTypes - merge two types which appear as function
6850/// parameter types
6851QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
6852 bool OfBlockPointer,
6853 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006854 // GNU extension: two types are compatible if they appear as a function
6855 // argument, one of the types is a transparent union type and the other
6856 // type is compatible with a union member
6857 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6858 Unqualified);
6859 if (!lmerge.isNull())
6860 return lmerge;
6861
6862 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6863 Unqualified);
6864 if (!rmerge.isNull())
6865 return rmerge;
6866
6867 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6868}
6869
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006870QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006871 bool OfBlockPointer,
6872 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006873 const FunctionType *lbase = lhs->getAs<FunctionType>();
6874 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006875 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6876 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006877 bool allLTypes = true;
6878 bool allRTypes = true;
6879
6880 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006881 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006882 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00006883 QualType RHS = rbase->getReturnType();
6884 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00006885 bool UnqualifiedResult = Unqualified;
6886 if (!UnqualifiedResult)
6887 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006888 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006889 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006890 else
Alp Toker314cc812014-01-25 16:55:45 +00006891 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00006892 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006893 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006894
6895 if (Unqualified)
6896 retType = retType.getUnqualifiedType();
6897
Alp Toker314cc812014-01-25 16:55:45 +00006898 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
6899 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006900 if (Unqualified) {
6901 LRetType = LRetType.getUnqualifiedType();
6902 RRetType = RRetType.getUnqualifiedType();
6903 }
6904
6905 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006906 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006907 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006908 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006909
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006910 // FIXME: double check this
6911 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6912 // rbase->getRegParmAttr() != 0 &&
6913 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006914 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6915 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006916
Douglas Gregor8c940862010-01-18 17:14:39 +00006917 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00006918 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00006919 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006920
John McCall8c6b56f2010-12-15 01:06:38 +00006921 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006922 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6923 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006924 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6925 return QualType();
6926
John McCall31168b02011-06-15 23:02:42 +00006927 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6928 return QualType();
6929
John McCall8c6b56f2010-12-15 01:06:38 +00006930 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6931 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006932
Rafael Espindola8778c282012-11-29 16:09:03 +00006933 if (lbaseInfo.getNoReturn() != NoReturn)
6934 allLTypes = false;
6935 if (rbaseInfo.getNoReturn() != NoReturn)
6936 allRTypes = false;
6937
John McCall31168b02011-06-15 23:02:42 +00006938 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006939
Eli Friedman47f77112008-08-22 00:56:42 +00006940 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006941 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6942 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00006943 // Compatible functions must have the same number of parameters
6944 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00006945 return QualType();
6946
6947 // Variadic and non-variadic functions aren't compatible
6948 if (lproto->isVariadic() != rproto->isVariadic())
6949 return QualType();
6950
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006951 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6952 return QualType();
6953
Fariborz Jahanian97676972011-09-28 21:52:05 +00006954 if (LangOpts.ObjCAutoRefCount &&
6955 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6956 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00006957
6958 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006959 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00006960 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
6961 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
6962 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
6963 QualType paramType = mergeFunctionParameterTypes(
6964 lParamType, rParamType, OfBlockPointer, Unqualified);
6965 if (paramType.isNull())
6966 return QualType();
6967
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006968 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00006969 paramType = paramType.getUnqualifiedType();
6970
6971 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006972 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00006973 lParamType = lParamType.getUnqualifiedType();
6974 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006975 }
Alp Toker601b22c2014-01-21 23:35:24 +00006976
6977 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00006978 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00006979 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00006980 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006981 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006982
Eli Friedman47f77112008-08-22 00:56:42 +00006983 if (allLTypes) return lhs;
6984 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006985
6986 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6987 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00006988 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006989 }
6990
6991 if (lproto) allRTypes = false;
6992 if (rproto) allLTypes = false;
6993
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006994 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006995 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006996 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006997 if (proto->isVariadic()) return QualType();
6998 // Check that the types are compatible with the types that
6999 // would result from default argument promotions (C99 6.7.5.3p15).
7000 // The only types actually affected are promotable integer
7001 // types and floats, which would be passed as a different
7002 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007003 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7004 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007005
Eli Friedman448ce402012-08-30 00:44:15 +00007006 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007007 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007008 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7009 paramTy = Enum->getDecl()->getIntegerType();
7010 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007011 return QualType();
7012 }
Alp Toker601b22c2014-01-21 23:35:24 +00007013
7014 if (paramTy->isPromotableIntegerType() ||
7015 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007016 return QualType();
7017 }
7018
7019 if (allLTypes) return lhs;
7020 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007021
7022 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7023 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007024 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007025 }
7026
7027 if (allLTypes) return lhs;
7028 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007029 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007030}
7031
John McCall433c2e62013-03-21 00:10:07 +00007032/// Given that we have an enum type and a non-enum type, try to merge them.
7033static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7034 QualType other, bool isBlockReturnType) {
7035 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7036 // a signed integer type, or an unsigned integer type.
7037 // Compatibility is based on the underlying type, not the promotion
7038 // type.
7039 QualType underlyingType = ET->getDecl()->getIntegerType();
7040 if (underlyingType.isNull()) return QualType();
7041 if (Context.hasSameType(underlyingType, other))
7042 return other;
7043
7044 // In block return types, we're more permissive and accept any
7045 // integral type of the same size.
7046 if (isBlockReturnType && other->isIntegerType() &&
7047 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7048 return other;
7049
7050 return QualType();
7051}
7052
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007053QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007054 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007055 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007056 // C++ [expr]: If an expression initially has the type "reference to T", the
7057 // type is adjusted to "T" prior to any further analysis, the expression
7058 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007059 // expression is an lvalue unless the reference is an rvalue reference and
7060 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007061 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7062 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007063
7064 if (Unqualified) {
7065 LHS = LHS.getUnqualifiedType();
7066 RHS = RHS.getUnqualifiedType();
7067 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007068
Eli Friedman47f77112008-08-22 00:56:42 +00007069 QualType LHSCan = getCanonicalType(LHS),
7070 RHSCan = getCanonicalType(RHS);
7071
7072 // If two types are identical, they are compatible.
7073 if (LHSCan == RHSCan)
7074 return LHS;
7075
John McCall8ccfcb52009-09-24 19:53:00 +00007076 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007077 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7078 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007079 if (LQuals != RQuals) {
7080 // If any of these qualifiers are different, we have a type
7081 // mismatch.
7082 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007083 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7084 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007085 return QualType();
7086
7087 // Exactly one GC qualifier difference is allowed: __strong is
7088 // okay if the other type has no GC qualifier but is an Objective
7089 // C object pointer (i.e. implicitly strong by default). We fix
7090 // this by pretending that the unqualified type was actually
7091 // qualified __strong.
7092 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7093 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7094 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7095
7096 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7097 return QualType();
7098
7099 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7100 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7101 }
7102 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7103 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7104 }
Eli Friedman47f77112008-08-22 00:56:42 +00007105 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007106 }
7107
7108 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007109
Eli Friedmandcca6332009-06-01 01:22:52 +00007110 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7111 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007112
Chris Lattnerfd652912008-01-14 05:45:46 +00007113 // We want to consider the two function types to be the same for these
7114 // comparisons, just force one to the other.
7115 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7116 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007117
7118 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007119 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7120 LHSClass = Type::ConstantArray;
7121 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7122 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007123
John McCall8b07ec22010-05-15 11:32:37 +00007124 // ObjCInterfaces are just specialized ObjCObjects.
7125 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7126 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7127
Nate Begemance4d7fc2008-04-18 23:10:10 +00007128 // Canonicalize ExtVector -> Vector.
7129 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7130 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007131
Chris Lattner95554662008-04-07 05:43:21 +00007132 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007133 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007134 // Note that we only have special rules for turning block enum
7135 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007136 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007137 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007138 }
John McCall9dd450b2009-09-21 23:43:11 +00007139 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007140 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007141 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007142 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007143 if (OfBlockPointer && !BlockReturnType) {
7144 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7145 return LHS;
7146 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7147 return RHS;
7148 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007149
Eli Friedman47f77112008-08-22 00:56:42 +00007150 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007151 }
Eli Friedman47f77112008-08-22 00:56:42 +00007152
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007153 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007154 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007155#define TYPE(Class, Base)
7156#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007157#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007158#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7159#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7160#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007161 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007162
Richard Smith27d807c2013-04-30 13:56:41 +00007163 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007164 case Type::LValueReference:
7165 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007166 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007167 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007168
John McCall8b07ec22010-05-15 11:32:37 +00007169 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007170 case Type::IncompleteArray:
7171 case Type::VariableArray:
7172 case Type::FunctionProto:
7173 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007174 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007175
Chris Lattnerfd652912008-01-14 05:45:46 +00007176 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007177 {
7178 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007179 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7180 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007181 if (Unqualified) {
7182 LHSPointee = LHSPointee.getUnqualifiedType();
7183 RHSPointee = RHSPointee.getUnqualifiedType();
7184 }
7185 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7186 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007187 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007188 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007189 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007190 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007191 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007192 return getPointerType(ResultType);
7193 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007194 case Type::BlockPointer:
7195 {
7196 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007197 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7198 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007199 if (Unqualified) {
7200 LHSPointee = LHSPointee.getUnqualifiedType();
7201 RHSPointee = RHSPointee.getUnqualifiedType();
7202 }
7203 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7204 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007205 if (ResultType.isNull()) return QualType();
7206 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7207 return LHS;
7208 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7209 return RHS;
7210 return getBlockPointerType(ResultType);
7211 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007212 case Type::Atomic:
7213 {
7214 // Merge two pointer types, while trying to preserve typedef info
7215 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7216 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7217 if (Unqualified) {
7218 LHSValue = LHSValue.getUnqualifiedType();
7219 RHSValue = RHSValue.getUnqualifiedType();
7220 }
7221 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7222 Unqualified);
7223 if (ResultType.isNull()) return QualType();
7224 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7225 return LHS;
7226 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7227 return RHS;
7228 return getAtomicType(ResultType);
7229 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007230 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007231 {
7232 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7233 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7234 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7235 return QualType();
7236
7237 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7238 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007239 if (Unqualified) {
7240 LHSElem = LHSElem.getUnqualifiedType();
7241 RHSElem = RHSElem.getUnqualifiedType();
7242 }
7243
7244 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007245 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007246 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7247 return LHS;
7248 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7249 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007250 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7251 ArrayType::ArraySizeModifier(), 0);
7252 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7253 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007254 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7255 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007256 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7257 return LHS;
7258 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7259 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007260 if (LVAT) {
7261 // FIXME: This isn't correct! But tricky to implement because
7262 // the array's size has to be the size of LHS, but the type
7263 // has to be different.
7264 return LHS;
7265 }
7266 if (RVAT) {
7267 // FIXME: This isn't correct! But tricky to implement because
7268 // the array's size has to be the size of RHS, but the type
7269 // has to be different.
7270 return RHS;
7271 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007272 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7273 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007274 return getIncompleteArrayType(ResultType,
7275 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007276 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007277 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007278 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007279 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007280 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007281 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007282 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007283 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007284 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007285 case Type::Complex:
7286 // Distinct complex types are incompatible.
7287 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007288 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007289 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007290 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7291 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007292 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007293 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007294 case Type::ObjCObject: {
7295 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007296 // FIXME: This should be type compatibility, e.g. whether
7297 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007298 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7299 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7300 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007301 return LHS;
7302
Eli Friedman47f77112008-08-22 00:56:42 +00007303 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007304 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007305 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007306 if (OfBlockPointer) {
7307 if (canAssignObjCInterfacesInBlockPointer(
7308 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007309 RHS->getAs<ObjCObjectPointerType>(),
7310 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007311 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007312 return QualType();
7313 }
John McCall9dd450b2009-09-21 23:43:11 +00007314 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7315 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007316 return LHS;
7317
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007318 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007319 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007320 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007321
David Blaikie8a40f702012-01-17 06:56:22 +00007322 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007323}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007324
Fariborz Jahanian97676972011-09-28 21:52:05 +00007325bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7326 const FunctionProtoType *FromFunctionType,
7327 const FunctionProtoType *ToFunctionType) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007328 if (FromFunctionType->hasAnyConsumedParams() !=
7329 ToFunctionType->hasAnyConsumedParams())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007330 return false;
7331 FunctionProtoType::ExtProtoInfo FromEPI =
7332 FromFunctionType->getExtProtoInfo();
7333 FunctionProtoType::ExtProtoInfo ToEPI =
7334 ToFunctionType->getExtProtoInfo();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007335 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
Alp Toker601b22c2014-01-21 23:35:24 +00007336 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7337 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
Fariborz Jahanian97676972011-09-28 21:52:05 +00007338 return false;
7339 }
7340 return true;
7341}
7342
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007343/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7344/// 'RHS' attributes and returns the merged version; including for function
7345/// return types.
7346QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7347 QualType LHSCan = getCanonicalType(LHS),
7348 RHSCan = getCanonicalType(RHS);
7349 // If two types are identical, they are compatible.
7350 if (LHSCan == RHSCan)
7351 return LHS;
7352 if (RHSCan->isFunctionType()) {
7353 if (!LHSCan->isFunctionType())
7354 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007355 QualType OldReturnType =
7356 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007357 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007358 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007359 QualType ResReturnType =
7360 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7361 if (ResReturnType.isNull())
7362 return QualType();
7363 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7364 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7365 // In either case, use OldReturnType to build the new function type.
7366 const FunctionType *F = LHS->getAs<FunctionType>();
7367 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007368 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7369 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007370 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007371 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007372 return ResultType;
7373 }
7374 }
7375 return QualType();
7376 }
7377
7378 // If the qualifiers are different, the types can still be merged.
7379 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7380 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7381 if (LQuals != RQuals) {
7382 // If any of these qualifiers are different, we have a type mismatch.
7383 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7384 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7385 return QualType();
7386
7387 // Exactly one GC qualifier difference is allowed: __strong is
7388 // okay if the other type has no GC qualifier but is an Objective
7389 // C object pointer (i.e. implicitly strong by default). We fix
7390 // this by pretending that the unqualified type was actually
7391 // qualified __strong.
7392 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7393 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7394 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7395
7396 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7397 return QualType();
7398
7399 if (GC_L == Qualifiers::Strong)
7400 return LHS;
7401 if (GC_R == Qualifiers::Strong)
7402 return RHS;
7403 return QualType();
7404 }
7405
7406 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7407 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7408 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7409 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7410 if (ResQT == LHSBaseQT)
7411 return LHS;
7412 if (ResQT == RHSBaseQT)
7413 return RHS;
7414 }
7415 return QualType();
7416}
7417
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007418//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007419// Integer Predicates
7420//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007421
Jay Foad39c79802011-01-12 09:06:06 +00007422unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007423 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007424 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007425 if (T->isBooleanType())
7426 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007427 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007428 return (unsigned)getTypeSize(T);
7429}
7430
Abramo Bagnara13640492012-09-09 10:21:24 +00007431QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007432 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007433
7434 // Turn <4 x signed int> -> <4 x unsigned int>
7435 if (const VectorType *VTy = T->getAs<VectorType>())
7436 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007437 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007438
7439 // For enums, we return the unsigned version of the base type.
7440 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007441 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007442
7443 const BuiltinType *BTy = T->getAs<BuiltinType>();
7444 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007445 switch (BTy->getKind()) {
7446 case BuiltinType::Char_S:
7447 case BuiltinType::SChar:
7448 return UnsignedCharTy;
7449 case BuiltinType::Short:
7450 return UnsignedShortTy;
7451 case BuiltinType::Int:
7452 return UnsignedIntTy;
7453 case BuiltinType::Long:
7454 return UnsignedLongTy;
7455 case BuiltinType::LongLong:
7456 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007457 case BuiltinType::Int128:
7458 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007459 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007460 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007461 }
7462}
7463
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007464ASTMutationListener::~ASTMutationListener() { }
7465
Richard Smith1fa5d642013-05-11 05:45:24 +00007466void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7467 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007468
7469//===----------------------------------------------------------------------===//
7470// Builtin Type Computation
7471//===----------------------------------------------------------------------===//
7472
7473/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007474/// pointer over the consumed characters. This returns the resultant type. If
7475/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7476/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7477/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007478///
7479/// RequiresICE is filled in on return to indicate whether the value is required
7480/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007481static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007482 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007483 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007484 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007485 // Modifiers.
7486 int HowLong = 0;
7487 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007488 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007489
Chris Lattnerdc226c22010-10-01 22:42:38 +00007490 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007491 bool Done = false;
7492 while (!Done) {
7493 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007494 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007495 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007496 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007497 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007498 case 'S':
7499 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7500 assert(!Signed && "Can't use 'S' modifier multiple times!");
7501 Signed = true;
7502 break;
7503 case 'U':
7504 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7505 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7506 Unsigned = true;
7507 break;
7508 case 'L':
7509 assert(HowLong <= 2 && "Can't have LLLL modifier");
7510 ++HowLong;
7511 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00007512 case 'W':
7513 // This modifier represents int64 type.
7514 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7515 switch (Context.getTargetInfo().getInt64Type()) {
7516 default:
7517 llvm_unreachable("Unexpected integer type");
7518 case TargetInfo::SignedLong:
7519 HowLong = 1;
7520 break;
7521 case TargetInfo::SignedLongLong:
7522 HowLong = 2;
7523 break;
7524 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00007525 }
7526 }
7527
7528 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007529
Chris Lattnerecd79c62009-06-14 00:45:47 +00007530 // Read the base type.
7531 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007532 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007533 case 'v':
7534 assert(HowLong == 0 && !Signed && !Unsigned &&
7535 "Bad modifiers used with 'v'!");
7536 Type = Context.VoidTy;
7537 break;
Jack Carter24bef982013-08-15 15:16:57 +00007538 case 'h':
7539 assert(HowLong == 0 && !Signed && !Unsigned &&
7540 "Bad modifiers used with 'f'!");
7541 Type = Context.HalfTy;
7542 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007543 case 'f':
7544 assert(HowLong == 0 && !Signed && !Unsigned &&
7545 "Bad modifiers used with 'f'!");
7546 Type = Context.FloatTy;
7547 break;
7548 case 'd':
7549 assert(HowLong < 2 && !Signed && !Unsigned &&
7550 "Bad modifiers used with 'd'!");
7551 if (HowLong)
7552 Type = Context.LongDoubleTy;
7553 else
7554 Type = Context.DoubleTy;
7555 break;
7556 case 's':
7557 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7558 if (Unsigned)
7559 Type = Context.UnsignedShortTy;
7560 else
7561 Type = Context.ShortTy;
7562 break;
7563 case 'i':
7564 if (HowLong == 3)
7565 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7566 else if (HowLong == 2)
7567 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7568 else if (HowLong == 1)
7569 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7570 else
7571 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7572 break;
7573 case 'c':
7574 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7575 if (Signed)
7576 Type = Context.SignedCharTy;
7577 else if (Unsigned)
7578 Type = Context.UnsignedCharTy;
7579 else
7580 Type = Context.CharTy;
7581 break;
7582 case 'b': // boolean
7583 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7584 Type = Context.BoolTy;
7585 break;
7586 case 'z': // size_t.
7587 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7588 Type = Context.getSizeType();
7589 break;
7590 case 'F':
7591 Type = Context.getCFConstantStringType();
7592 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007593 case 'G':
7594 Type = Context.getObjCIdType();
7595 break;
7596 case 'H':
7597 Type = Context.getObjCSelType();
7598 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007599 case 'M':
7600 Type = Context.getObjCSuperType();
7601 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007602 case 'a':
7603 Type = Context.getBuiltinVaListType();
7604 assert(!Type.isNull() && "builtin va list type not initialized!");
7605 break;
7606 case 'A':
7607 // This is a "reference" to a va_list; however, what exactly
7608 // this means depends on how va_list is defined. There are two
7609 // different kinds of va_list: ones passed by value, and ones
7610 // passed by reference. An example of a by-value va_list is
7611 // x86, where va_list is a char*. An example of by-ref va_list
7612 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7613 // we want this argument to be a char*&; for x86-64, we want
7614 // it to be a __va_list_tag*.
7615 Type = Context.getBuiltinVaListType();
7616 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007617 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007618 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007619 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007620 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007621 break;
7622 case 'V': {
7623 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007624 unsigned NumElements = strtoul(Str, &End, 10);
7625 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007626 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007627
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007628 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7629 RequiresICE, false);
7630 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007631
7632 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007633 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007634 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007635 break;
7636 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007637 case 'E': {
7638 char *End;
7639
7640 unsigned NumElements = strtoul(Str, &End, 10);
7641 assert(End != Str && "Missing vector size");
7642
7643 Str = End;
7644
7645 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7646 false);
7647 Type = Context.getExtVectorType(ElementType, NumElements);
7648 break;
7649 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007650 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007651 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7652 false);
7653 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007654 Type = Context.getComplexType(ElementType);
7655 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007656 }
7657 case 'Y' : {
7658 Type = Context.getPointerDiffType();
7659 break;
7660 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007661 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007662 Type = Context.getFILEType();
7663 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007664 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007665 return QualType();
7666 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007667 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007668 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007669 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007670 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007671 else
7672 Type = Context.getjmp_bufType();
7673
Mike Stump2adb4da2009-07-28 23:47:15 +00007674 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007675 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007676 return QualType();
7677 }
7678 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007679 case 'K':
7680 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7681 Type = Context.getucontext_tType();
7682
7683 if (Type.isNull()) {
7684 Error = ASTContext::GE_Missing_ucontext;
7685 return QualType();
7686 }
7687 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007688 case 'p':
7689 Type = Context.getProcessIDType();
7690 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007691 }
Mike Stump11289f42009-09-09 15:08:12 +00007692
Chris Lattnerdc226c22010-10-01 22:42:38 +00007693 // If there are modifiers and if we're allowed to parse them, go for it.
7694 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007695 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007696 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007697 default: Done = true; --Str; break;
7698 case '*':
7699 case '&': {
7700 // Both pointers and references can have their pointee types
7701 // qualified with an address space.
7702 char *End;
7703 unsigned AddrSpace = strtoul(Str, &End, 10);
7704 if (End != Str && AddrSpace != 0) {
7705 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7706 Str = End;
7707 }
7708 if (c == '*')
7709 Type = Context.getPointerType(Type);
7710 else
7711 Type = Context.getLValueReferenceType(Type);
7712 break;
7713 }
7714 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7715 case 'C':
7716 Type = Type.withConst();
7717 break;
7718 case 'D':
7719 Type = Context.getVolatileType(Type);
7720 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007721 case 'R':
7722 Type = Type.withRestrict();
7723 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007724 }
7725 }
Chris Lattner84733392010-10-01 07:13:18 +00007726
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007727 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007728 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007729
Chris Lattnerecd79c62009-06-14 00:45:47 +00007730 return Type;
7731}
7732
7733/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007734QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007735 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007736 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007737 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007738
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007739 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007740
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007741 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007742 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007743 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7744 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007745 if (Error != GE_None)
7746 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007747
7748 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7749
Chris Lattnerecd79c62009-06-14 00:45:47 +00007750 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007751 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007752 if (Error != GE_None)
7753 return QualType();
7754
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007755 // If this argument is required to be an IntegerConstantExpression and the
7756 // caller cares, fill in the bitmask we return.
7757 if (RequiresICE && IntegerConstantArgs)
7758 *IntegerConstantArgs |= 1 << ArgTypes.size();
7759
Chris Lattnerecd79c62009-06-14 00:45:47 +00007760 // Do array -> pointer decay. The builtin should use the decayed type.
7761 if (Ty->isArrayType())
7762 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007763
Chris Lattnerecd79c62009-06-14 00:45:47 +00007764 ArgTypes.push_back(Ty);
7765 }
7766
7767 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7768 "'.' should only occur at end of builtin type list!");
7769
Reid Kleckner78af0702013-08-27 23:08:25 +00007770 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00007771 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7772
7773 bool Variadic = (TypeStr[0] == '.');
7774
7775 // We really shouldn't be making a no-proto type here, especially in C++.
7776 if (ArgTypes.empty() && Variadic)
7777 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007778
John McCalldb40c7f2010-12-14 08:05:40 +00007779 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007780 EPI.ExtInfo = EI;
7781 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007782
Jordan Rose5c382722013-03-08 21:51:21 +00007783 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007784}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007785
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007786GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007787 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007788 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007789
Rafael Espindola3ae00052013-05-13 00:12:11 +00007790 GVALinkage External = GVA_StrongExternal;
7791 switch (FD->getTemplateSpecializationKind()) {
7792 case TSK_Undeclared:
7793 case TSK_ExplicitSpecialization:
7794 External = GVA_StrongExternal;
7795 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007796
Rafael Espindola3ae00052013-05-13 00:12:11 +00007797 case TSK_ExplicitInstantiationDefinition:
7798 return GVA_ExplicitTemplateInstantiation;
7799
7800 case TSK_ExplicitInstantiationDeclaration:
7801 case TSK_ImplicitInstantiation:
7802 External = GVA_TemplateInstantiation;
7803 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007804 }
7805
7806 if (!FD->isInlined())
7807 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00007808
Alp Tokerbfa39342014-01-14 12:51:41 +00007809 if ((!getLangOpts().CPlusPlus && !getLangOpts().MSVCCompat) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00007810 FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007811 // GNU or C99 inline semantics. Determine whether this symbol should be
7812 // externally visible.
7813 if (FD->isInlineDefinitionExternallyVisible())
7814 return External;
7815
7816 // C99 inline semantics, where the symbol is not externally visible.
7817 return GVA_C99Inline;
7818 }
7819
7820 // C++0x [temp.explicit]p9:
7821 // [ Note: The intent is that an inline function that is the subject of
7822 // an explicit instantiation declaration will still be implicitly
7823 // instantiated when used so that the body can be considered for
7824 // inlining, but that no out-of-line copy of the inline function would be
7825 // generated in the translation unit. -- end note ]
7826 if (FD->getTemplateSpecializationKind()
7827 == TSK_ExplicitInstantiationDeclaration)
7828 return GVA_C99Inline;
7829
7830 return GVA_CXXInline;
7831}
7832
7833GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007834 if (!VD->isExternallyVisible())
7835 return GVA_Internal;
7836
Richard Smith8809a0c2013-09-27 20:14:12 +00007837 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007838 case TSK_Undeclared:
7839 case TSK_ExplicitSpecialization:
7840 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007841
Rafael Espindola3ae00052013-05-13 00:12:11 +00007842 case TSK_ExplicitInstantiationDeclaration:
7843 llvm_unreachable("Variable should not be instantiated");
7844 // Fall through to treat this like any other instantiation.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007845
Rafael Espindola3ae00052013-05-13 00:12:11 +00007846 case TSK_ExplicitInstantiationDefinition:
7847 return GVA_ExplicitTemplateInstantiation;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007848
Rafael Espindola3ae00052013-05-13 00:12:11 +00007849 case TSK_ImplicitInstantiation:
7850 return GVA_TemplateInstantiation;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007851 }
Rafael Espindola27699c82013-05-13 14:05:53 +00007852
7853 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007854}
7855
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007856bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007857 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7858 if (!VD->isFileVarDecl())
7859 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00007860 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7861 // We never need to emit an uninstantiated function template.
7862 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7863 return false;
7864 } else
7865 return false;
7866
7867 // If this is a member of a class template, we do not need to emit it.
7868 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007869 return false;
7870
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007871 // Weak references don't produce any output by themselves.
7872 if (D->hasAttr<WeakRefAttr>())
7873 return false;
7874
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007875 // Aliases and used decls are required.
7876 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7877 return true;
7878
7879 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7880 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007881 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007882 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007883
7884 // Constructors and destructors are required.
7885 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7886 return true;
7887
John McCall6bd2a892013-01-25 22:31:03 +00007888 // The key function for a class is required. This rule only comes
7889 // into play when inline functions can be key functions, though.
7890 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7891 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7892 const CXXRecordDecl *RD = MD->getParent();
7893 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7894 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7895 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7896 return true;
7897 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007898 }
7899 }
7900
7901 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7902
7903 // static, static inline, always_inline, and extern inline functions can
7904 // always be deferred. Normal inline functions can be deferred in C99/C++.
7905 // Implicit template instantiations can also be deferred in C++.
7906 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007907 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007908 return false;
7909 return true;
7910 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007911
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007912 const VarDecl *VD = cast<VarDecl>(D);
7913 assert(VD->isFileVarDecl() && "Expected file scoped var");
7914
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007915 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7916 return false;
7917
Richard Smitha0e5e542012-11-12 21:38:00 +00007918 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007919 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smitha0e5e542012-11-12 21:38:00 +00007920 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7921 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007922
Richard Smitha0e5e542012-11-12 21:38:00 +00007923 // Variables that have destruction with side-effects are required.
7924 if (VD->getType().isDestructedType())
7925 return true;
7926
7927 // Variables that have initialization with side-effects are required.
7928 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7929 return true;
7930
7931 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007932}
Charles Davis53c59df2010-08-16 03:33:14 +00007933
Reid Kleckner78af0702013-08-27 23:08:25 +00007934CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
7935 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00007936 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00007937 if (IsCXXMethod)
7938 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007939
Reid Kleckner78af0702013-08-27 23:08:25 +00007940 return (LangOpts.MRTD && !IsVariadic) ? CC_X86StdCall : CC_C;
Charles Davis99202b32010-11-09 18:04:24 +00007941}
7942
Jay Foad39c79802011-01-12 09:06:06 +00007943bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007944 // Pass through to the C++ ABI object
7945 return ABI->isNearlyEmpty(RD);
7946}
7947
Reid Kleckner96f8f932014-02-05 17:27:08 +00007948VTableContextBase *ASTContext::getVTableContext() {
7949 if (!VTContext.get()) {
7950 if (Target->getCXXABI().isMicrosoft())
7951 VTContext.reset(new MicrosoftVTableContext(*this));
7952 else
7953 VTContext.reset(new ItaniumVTableContext(*this));
7954 }
7955 return VTContext.get();
7956}
7957
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007958MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00007959 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00007960 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00007961 case TargetCXXABI::GenericItanium:
7962 case TargetCXXABI::GenericARM:
7963 case TargetCXXABI::iOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00007964 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00007965 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00007966 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007967 }
David Blaikie83d382b2011-09-23 05:06:16 +00007968 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007969}
7970
Charles Davis53c59df2010-08-16 03:33:14 +00007971CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007972
7973size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00007974 return ASTRecordLayouts.getMemorySize() +
7975 llvm::capacity_in_bytes(ObjCLayouts) +
7976 llvm::capacity_in_bytes(KeyFunctions) +
7977 llvm::capacity_in_bytes(ObjCImpls) +
7978 llvm::capacity_in_bytes(BlockVarCopyInits) +
7979 llvm::capacity_in_bytes(DeclAttrs) +
7980 llvm::capacity_in_bytes(TemplateOrInstantiation) +
7981 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
7982 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
7983 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
7984 llvm::capacity_in_bytes(OverriddenMethods) +
7985 llvm::capacity_in_bytes(Types) +
7986 llvm::capacity_in_bytes(VariableArrayTypes) +
7987 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007988}
Ted Kremenek540017e2011-10-06 05:00:56 +00007989
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007990/// getIntTypeForBitwidth -
7991/// sets integer QualTy according to specified details:
7992/// bitwidth, signed/unsigned.
7993/// Returns empty type if there is no appropriate target types.
7994QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
7995 unsigned Signed) const {
7996 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
7997 CanQualType QualTy = getFromTargetType(Ty);
7998 if (!QualTy && DestWidth == 128)
7999 return Signed ? Int128Ty : UnsignedInt128Ty;
8000 return QualTy;
8001}
8002
8003/// getRealTypeForBitwidth -
8004/// sets floating point QualTy according to specified bitwidth.
8005/// Returns empty type if there is no appropriate target types.
8006QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8007 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8008 switch (Ty) {
8009 case TargetInfo::Float:
8010 return FloatTy;
8011 case TargetInfo::Double:
8012 return DoubleTy;
8013 case TargetInfo::LongDouble:
8014 return LongDoubleTy;
8015 case TargetInfo::NoFloat:
8016 return QualType();
8017 }
8018
8019 llvm_unreachable("Unhandled TargetInfo::RealType value");
8020}
8021
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008022void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8023 if (Number > 1)
8024 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008025}
8026
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008027unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8028 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8029 MangleNumbers.find(ND);
8030 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008031}
8032
David Majnemer2206bf52014-03-05 08:57:59 +00008033void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8034 if (Number > 1)
8035 StaticLocalNumbers[VD] = Number;
8036}
8037
8038unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8039 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8040 StaticLocalNumbers.find(VD);
8041 return I != StaticLocalNumbers.end() ? I->second : 1;
8042}
8043
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008044MangleNumberingContext &
8045ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008046 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8047 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8048 if (!MCtx)
8049 MCtx = createMangleNumberingContext();
8050 return *MCtx;
8051}
8052
8053MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8054 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008055}
8056
Ted Kremenek540017e2011-10-06 05:00:56 +00008057void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8058 ParamIndices[D] = index;
8059}
8060
8061unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8062 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8063 assert(I != ParamIndices.end() &&
8064 "ParmIndices lacks entry set by ParmVarDecl");
8065 return I->second;
8066}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008067
Richard Smithe6c01442013-06-05 00:46:14 +00008068APValue *
8069ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8070 bool MayCreate) {
8071 assert(E && E->getStorageDuration() == SD_Static &&
8072 "don't need to cache the computed value for this temporary");
8073 if (MayCreate)
8074 return &MaterializedTemporaryValues[E];
8075
8076 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8077 MaterializedTemporaryValues.find(E);
8078 return I == MaterializedTemporaryValues.end() ? 0 : &I->second;
8079}
8080
Fariborz Jahanian615de762013-05-28 17:37:39 +00008081bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8082 const llvm::Triple &T = getTargetInfo().getTriple();
8083 if (!T.isOSDarwin())
8084 return false;
8085
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008086 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8087 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8088 return false;
8089
Fariborz Jahanian615de762013-05-28 17:37:39 +00008090 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8091 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8092 uint64_t Size = sizeChars.getQuantity();
8093 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8094 unsigned Align = alignChars.getQuantity();
8095 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8096 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8097}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008098
8099namespace {
8100
8101 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8102 /// parents as defined by the \c RecursiveASTVisitor.
8103 ///
8104 /// Note that the relationship described here is purely in terms of AST
8105 /// traversal - there are other relationships (for example declaration context)
8106 /// in the AST that are better modeled by special matchers.
8107 ///
8108 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8109 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8110
8111 public:
8112 /// \brief Builds and returns the translation unit's parent map.
8113 ///
8114 /// The caller takes ownership of the returned \c ParentMap.
8115 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8116 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8117 Visitor.TraverseDecl(&TU);
8118 return Visitor.Parents;
8119 }
8120
8121 private:
8122 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8123
8124 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8125 }
8126
8127 bool shouldVisitTemplateInstantiations() const {
8128 return true;
8129 }
8130 bool shouldVisitImplicitCode() const {
8131 return true;
8132 }
8133 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8134 // are not triggered during data recursion.
8135 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8136 return false;
8137 }
8138
8139 template <typename T>
8140 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
8141 if (Node == NULL)
8142 return true;
8143 if (ParentStack.size() > 0)
8144 // FIXME: Currently we add the same parent multiple times, for example
8145 // when we visit all subexpressions of template instantiations; this is
8146 // suboptimal, bug benign: the only way to visit those is with
8147 // hasAncestor / hasParent, and those do not create new matches.
8148 // The plan is to enable DynTypedNode to be storable in a map or hash
8149 // map. The main problem there is to implement hash functions /
8150 // comparison operators for all types that DynTypedNode supports that
8151 // do not have pointer identity.
8152 (*Parents)[Node].push_back(ParentStack.back());
8153 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8154 bool Result = (this ->* traverse) (Node);
8155 ParentStack.pop_back();
8156 return Result;
8157 }
8158
8159 bool TraverseDecl(Decl *DeclNode) {
8160 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8161 }
8162
8163 bool TraverseStmt(Stmt *StmtNode) {
8164 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8165 }
8166
8167 ASTContext::ParentMap *Parents;
8168 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8169
8170 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8171 };
8172
8173} // end namespace
8174
8175ASTContext::ParentVector
8176ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8177 assert(Node.getMemoizationData() &&
8178 "Invariant broken: only nodes that support memoization may be "
8179 "used in the parent map.");
8180 if (!AllParents) {
8181 // We always need to run over the whole translation unit, as
8182 // hasAncestor can escape any subtree.
8183 AllParents.reset(
8184 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8185 }
8186 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8187 if (I == AllParents->end()) {
8188 return ParentVector();
8189 }
8190 return I->second;
8191}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008192
8193bool
8194ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8195 const ObjCMethodDecl *MethodImpl) {
8196 // No point trying to match an unavailable/deprecated mothod.
8197 if (MethodDecl->hasAttr<UnavailableAttr>()
8198 || MethodDecl->hasAttr<DeprecatedAttr>())
8199 return false;
8200 if (MethodDecl->getObjCDeclQualifier() !=
8201 MethodImpl->getObjCDeclQualifier())
8202 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008203 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008204 return false;
8205
8206 if (MethodDecl->param_size() != MethodImpl->param_size())
8207 return false;
8208
8209 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8210 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8211 EF = MethodDecl->param_end();
8212 IM != EM && IF != EF; ++IM, ++IF) {
8213 const ParmVarDecl *DeclVar = (*IF);
8214 const ParmVarDecl *ImplVar = (*IM);
8215 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8216 return false;
8217 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8218 return false;
8219 }
8220 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8221
8222}