blob: 5aa4beeb292bbff75ee9b6bd63315129ed995047 [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();
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +000066
67#ifndef NDEBUG
68 ArrayRef<RawComment *> RawComments = Comments.getComments();
69 assert(std::is_sorted(RawComments.begin(), RawComments.end(),
70 BeforeThanCompare<RawComment>(SourceMgr)));
71#endif
72
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000073 CommentsLoaded = true;
74 }
75
76 assert(D);
77
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000078 // User can not attach documentation to implicit declarations.
79 if (D->isImplicit())
80 return NULL;
81
Dmitri Gribenkob2610882012-08-14 17:17:18 +000082 // User can not attach documentation to implicit instantiations.
83 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
84 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
85 return NULL;
86 }
87
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000088 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
89 if (VD->isStaticDataMember() &&
90 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
91 return NULL;
92 }
93
94 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
95 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
96 return NULL;
97 }
98
Dmitri Gribenko01b06512013-01-27 21:18:39 +000099 if (const ClassTemplateSpecializationDecl *CTSD =
100 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
101 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
102 if (TSK == TSK_ImplicitInstantiation ||
103 TSK == TSK_Undeclared)
104 return NULL;
105 }
106
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000107 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
108 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
109 return NULL;
110 }
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000111 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
112 // When tag declaration (but not definition!) is part of the
113 // decl-specifier-seq of some other declaration, it doesn't get comment
114 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
115 return NULL;
116 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000117 // TODO: handle comments for function parameters properly.
118 if (isa<ParmVarDecl>(D))
119 return NULL;
120
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000121 // TODO: we could look up template parameter documentation in the template
122 // documentation.
123 if (isa<TemplateTypeParmDecl>(D) ||
124 isa<NonTypeTemplateParmDecl>(D) ||
125 isa<TemplateTemplateParmDecl>(D))
126 return NULL;
127
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000128 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000129
130 // If there are no comments anywhere, we won't find anything.
131 if (RawComments.empty())
132 return NULL;
133
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000134 // Find declaration location.
135 // For Objective-C declarations we generally don't expect to have multiple
136 // declarators, thus use declaration starting location as the "declaration
137 // location".
138 // For all other declarations multiple declarators are used quite frequently,
139 // so we use the location of the identifier as the "declaration location".
140 SourceLocation DeclLoc;
141 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000142 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000143 isa<RedeclarableTemplateDecl>(D) ||
144 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000145 DeclLoc = D->getLocStart();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000146 else {
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000147 DeclLoc = D->getLocation();
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000148 if (DeclLoc.isMacroID()) {
149 if (isa<TypedefDecl>(D)) {
150 // If location of the typedef name is in a macro, it is because being
151 // declared via a macro. Try using declaration's starting location as
152 // the "declaration location".
153 DeclLoc = D->getLocStart();
154 } else if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
155 // If location of the tag decl is inside a macro, but the spelling of
156 // the tag name comes from a macro argument, it looks like a special
157 // macro like NS_ENUM is being used to define the tag decl. In that
158 // case, adjust the source location to the expansion loc so that we can
159 // attach the comment to the tag decl.
160 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
161 TD->isCompleteDefinition())
162 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
163 }
164 }
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000165 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000166
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000167 // If the declaration doesn't map directly to a location in a file, we
168 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000169 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
170 return NULL;
171
172 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000173 ArrayRef<RawComment *>::iterator Comment;
174 {
175 // When searching for comments during parsing, the comment we are looking
176 // for is usually among the last two comments we parsed -- check them
177 // first.
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000178 RawComment CommentAtDeclLoc(
179 SourceMgr, SourceRange(DeclLoc), false,
180 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000181 BeforeThanCompare<RawComment> Compare(SourceMgr);
182 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
183 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
184 if (!Found && RawComments.size() >= 2) {
185 MaybeBeforeDecl--;
186 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
187 }
188
189 if (Found) {
190 Comment = MaybeBeforeDecl + 1;
191 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
192 &CommentAtDeclLoc, Compare));
193 } else {
194 // Slow path.
195 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
196 &CommentAtDeclLoc, Compare);
197 }
198 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000199
200 // Decompose the location for the declaration and find the beginning of the
201 // file buffer.
202 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
203
204 // First check whether we have a trailing comment.
205 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000206 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Fariborz Jahanianfad28542013-08-06 23:29:00 +0000207 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian3ab62222013-08-07 16:40:29 +0000208 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000209 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000210 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000211 // Check that Doxygen trailing comment comes after the declaration, starts
212 // on the same line and in the same file as the declaration.
213 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
214 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
215 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
216 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000217 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000218 }
219 }
220
221 // The comment just after the declaration was not a trailing comment.
222 // Let's look at the previous comment.
223 if (Comment == RawComments.begin())
224 return NULL;
225 --Comment;
226
227 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000228 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000229 return NULL;
230
231 // Decompose the end of the comment.
232 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000233 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000234
235 // If the comment and the declaration aren't in the same file, then they
236 // aren't related.
237 if (DeclLocDecomp.first != CommentEndDecomp.first)
238 return NULL;
239
240 // Get the corresponding buffer.
241 bool Invalid = false;
242 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
243 &Invalid).data();
244 if (Invalid)
245 return NULL;
246
247 // Extract text between the comment and declaration.
248 StringRef Text(Buffer + CommentEndDecomp.second,
249 DeclLocDecomp.second - CommentEndDecomp.second);
250
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000251 // There should be no other declarations or preprocessor directives between
252 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000253 if (Text.find_first_of(";{}#@") != StringRef::npos)
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000254 return NULL;
255
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000256 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000257}
258
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000259namespace {
260/// If we have a 'templated' declaration for a template, adjust 'D' to
261/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000262/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000263const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000264 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000265 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000266 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000267 return FTD;
268
269 // Nothing to do if function is not an implicit instantiation.
270 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
271 return D;
272
273 // Function is an implicit instantiation of a function template?
274 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
275 return FTD;
276
277 // Function is instantiated from a member definition of a class template?
278 if (const FunctionDecl *MemberDecl =
279 FD->getInstantiatedFromMemberFunction())
280 return MemberDecl;
281
282 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000283 }
Dmitri Gribenko90631802012-08-22 17:44:32 +0000284 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
285 // Static data member is instantiated from a member definition of a class
286 // template?
287 if (VD->isStaticDataMember())
288 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
289 return MemberDecl;
290
291 return D;
292 }
293 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
294 // Is this class declaration part of a class template?
295 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
296 return CTD;
297
298 // Class is an implicit instantiation of a class template or partial
299 // specialization?
300 if (const ClassTemplateSpecializationDecl *CTSD =
301 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
302 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
303 return D;
304 llvm::PointerUnion<ClassTemplateDecl *,
305 ClassTemplatePartialSpecializationDecl *>
306 PU = CTSD->getSpecializedTemplateOrPartial();
307 return PU.is<ClassTemplateDecl*>() ?
308 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
309 static_cast<const Decl*>(
310 PU.get<ClassTemplatePartialSpecializationDecl *>());
311 }
312
313 // Class is instantiated from a member definition of a class template?
314 if (const MemberSpecializationInfo *Info =
315 CRD->getMemberSpecializationInfo())
316 return Info->getInstantiatedFrom();
317
318 return D;
319 }
320 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
321 // Enum is instantiated from a member definition of a class template?
322 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
323 return MemberDecl;
324
325 return D;
326 }
327 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000328 return D;
329}
330} // unnamed namespace
331
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000332const RawComment *ASTContext::getRawCommentForAnyRedecl(
333 const Decl *D,
334 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000335 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000336
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000337 // Check whether we have cached a comment for this declaration already.
338 {
339 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
340 RedeclComments.find(D);
341 if (Pos != RedeclComments.end()) {
342 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000343 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
344 if (OriginalDecl)
345 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000346 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000347 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000348 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000349 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000350
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000351 // Search for comments attached to declarations in the redeclaration chain.
352 const RawComment *RC = NULL;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000353 const Decl *OriginalDeclForRC = NULL;
Aaron Ballman86c93902014-03-06 23:45:36 +0000354 for (auto I : D->redecls()) {
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000355 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
Aaron Ballman86c93902014-03-06 23:45:36 +0000356 RedeclComments.find(I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000357 if (Pos != RedeclComments.end()) {
358 const RawCommentAndCacheFlags &Raw = Pos->second;
359 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
360 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000361 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000362 break;
363 }
364 } else {
Aaron Ballman86c93902014-03-06 23:45:36 +0000365 RC = getRawCommentForDeclNoCache(I);
366 OriginalDeclForRC = I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000367 RawCommentAndCacheFlags Raw;
368 if (RC) {
369 Raw.setRaw(RC);
370 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
371 } else
372 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000373 Raw.setOriginalDecl(I);
374 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000375 if (RC)
376 break;
377 }
378 }
379
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000380 // If we found a comment, it should be a documentation comment.
381 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000382
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000383 if (OriginalDecl)
384 *OriginalDecl = OriginalDeclForRC;
385
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000386 // Update cache for every declaration in the redeclaration chain.
387 RawCommentAndCacheFlags Raw;
388 Raw.setRaw(RC);
389 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000390 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000391
Aaron Ballman86c93902014-03-06 23:45:36 +0000392 for (auto I : D->redecls()) {
393 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000394 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
395 R = Raw;
396 }
397
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000398 return RC;
399}
400
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000401static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
402 SmallVectorImpl<const NamedDecl *> &Redeclared) {
403 const DeclContext *DC = ObjCMethod->getDeclContext();
404 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
405 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
406 if (!ID)
407 return;
408 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000409 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000410 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000411 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000412 ObjCMethod->isInstanceMethod()))
413 Redeclared.push_back(RedeclaredMethod);
414 }
415 }
416}
417
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000418comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
419 const Decl *D) const {
420 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
421 ThisDeclInfo->CommentDecl = D;
422 ThisDeclInfo->IsFilled = false;
423 ThisDeclInfo->fill();
424 ThisDeclInfo->CommentDecl = FC->getDecl();
425 comments::FullComment *CFC =
426 new (*this) comments::FullComment(FC->getBlocks(),
427 ThisDeclInfo);
428 return CFC;
429
430}
431
Richard Smithb39b9d52013-05-21 05:24:00 +0000432comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
433 const RawComment *RC = getRawCommentForDeclNoCache(D);
434 return RC ? RC->parse(*this, 0, D) : 0;
435}
436
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000437comments::FullComment *ASTContext::getCommentForDecl(
438 const Decl *D,
439 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000440 if (D->isInvalidDecl())
441 return NULL;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000442 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000443
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000444 const Decl *Canonical = D->getCanonicalDecl();
445 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
446 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000447
448 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000449 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000450 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000451 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000452 return CFC;
453 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000454 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000455 }
456
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000457 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000458
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000459 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000460 if (!RC) {
461 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000462 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000463 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000464 if (OMD && OMD->isPropertyAccessor())
465 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
466 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
467 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000468 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000469 addRedeclaredMethods(OMD, Overridden);
470 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000471 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
472 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
473 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000474 }
Fariborz Jahanian6384fbb2013-05-02 15:44:16 +0000475 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000476 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000477 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000478 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000479 if (const TagType *TT = QT->getAs<TagType>())
480 if (const Decl *TD = TT->getDecl())
481 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000482 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000483 }
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000484 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
485 while (IC->getSuperClass()) {
486 IC = IC->getSuperClass();
487 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
488 return cloneFullComment(FC, D);
489 }
490 }
491 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
492 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
493 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
494 return cloneFullComment(FC, D);
495 }
496 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
497 if (!(RD = RD->getDefinition()))
498 return NULL;
499 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000500 for (const auto &I : RD->bases()) {
501 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000502 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000503 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000504 if (Ty.isNull())
505 continue;
506 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
507 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
508 continue;
509
510 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
511 return cloneFullComment(FC, D);
512 }
513 }
514 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000515 for (const auto &I : RD->vbases()) {
516 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000517 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000518 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000519 if (Ty.isNull())
520 continue;
521 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
522 if (!(VirtualBase= VirtualBase->getDefinition()))
523 continue;
524 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
525 return cloneFullComment(FC, D);
526 }
527 }
528 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000529 return NULL;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000530 }
531
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000532 // If the RawComment was attached to other redeclaration of this Decl, we
533 // should parse the comment in context of that other Decl. This is important
534 // because comments can contain references to parameter names which can be
535 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000536 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000537 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000538
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000539 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000540 ParsedComments[Canonical] = FC;
541 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000542}
543
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000544void
545ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
546 TemplateTemplateParmDecl *Parm) {
547 ID.AddInteger(Parm->getDepth());
548 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000549 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000550
551 TemplateParameterList *Params = Parm->getTemplateParameters();
552 ID.AddInteger(Params->size());
553 for (TemplateParameterList::const_iterator P = Params->begin(),
554 PEnd = Params->end();
555 P != PEnd; ++P) {
556 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
557 ID.AddInteger(0);
558 ID.AddBoolean(TTP->isParameterPack());
559 continue;
560 }
561
562 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
563 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000564 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000565 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000566 if (NTTP->isExpandedParameterPack()) {
567 ID.AddBoolean(true);
568 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000569 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
570 QualType T = NTTP->getExpansionType(I);
571 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
572 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000573 } else
574 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000575 continue;
576 }
577
578 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
579 ID.AddInteger(2);
580 Profile(ID, TTP);
581 }
582}
583
584TemplateTemplateParmDecl *
585ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000586 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000587 // Check if we already have a canonical template template parameter.
588 llvm::FoldingSetNodeID ID;
589 CanonicalTemplateTemplateParm::Profile(ID, TTP);
590 void *InsertPos = 0;
591 CanonicalTemplateTemplateParm *Canonical
592 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
593 if (Canonical)
594 return Canonical->getParam();
595
596 // Build a canonical template parameter list.
597 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000598 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000599 CanonParams.reserve(Params->size());
600 for (TemplateParameterList::const_iterator P = Params->begin(),
601 PEnd = Params->end();
602 P != PEnd; ++P) {
603 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
604 CanonParams.push_back(
605 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000606 SourceLocation(),
607 SourceLocation(),
608 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000609 TTP->getIndex(), 0, false,
610 TTP->isParameterPack()));
611 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000612 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
613 QualType T = getCanonicalType(NTTP->getType());
614 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
615 NonTypeTemplateParmDecl *Param;
616 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000617 SmallVector<QualType, 2> ExpandedTypes;
618 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000619 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
620 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
621 ExpandedTInfos.push_back(
622 getTrivialTypeSourceInfo(ExpandedTypes.back()));
623 }
624
625 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000626 SourceLocation(),
627 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000628 NTTP->getDepth(),
629 NTTP->getPosition(), 0,
630 T,
631 TInfo,
632 ExpandedTypes.data(),
633 ExpandedTypes.size(),
634 ExpandedTInfos.data());
635 } else {
636 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000637 SourceLocation(),
638 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000639 NTTP->getDepth(),
640 NTTP->getPosition(), 0,
641 T,
642 NTTP->isParameterPack(),
643 TInfo);
644 }
645 CanonParams.push_back(Param);
646
647 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000648 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
649 cast<TemplateTemplateParmDecl>(*P)));
650 }
651
652 TemplateTemplateParmDecl *CanonTTP
653 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
654 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000655 TTP->getPosition(),
656 TTP->isParameterPack(),
657 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000658 TemplateParameterList::Create(*this, SourceLocation(),
659 SourceLocation(),
660 CanonParams.data(),
661 CanonParams.size(),
662 SourceLocation()));
663
664 // Get the new insert position for the node we care about.
665 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
666 assert(Canonical == 0 && "Shouldn't be in the map!");
667 (void)Canonical;
668
669 // Create the canonical template template parameter entry.
670 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
671 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
672 return CanonTTP;
673}
674
Charles Davis53c59df2010-08-16 03:33:14 +0000675CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000676 if (!LangOpts.CPlusPlus) return 0;
677
John McCall359b8852013-01-25 22:30:49 +0000678 switch (T.getCXXABI().getKind()) {
679 case TargetCXXABI::GenericARM:
680 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000681 case TargetCXXABI::iOS64:
John McCall86353412010-08-21 22:46:04 +0000682 return CreateARMCXXABI(*this);
Tim Northover9bb857a2013-01-31 12:13:10 +0000683 case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000684 case TargetCXXABI::GenericItanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000685 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000686 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000687 return CreateMicrosoftCXXABI(*this);
688 }
David Blaikie8a40f702012-01-17 06:56:22 +0000689 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000690}
691
Douglas Gregore8bbc122011-09-02 00:18:52 +0000692static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000693 const LangOptions &LOpts) {
694 if (LOpts.FakeAddressSpaceMap) {
695 // The fake address space map must have a distinct entry for each
696 // language-specific address space.
697 static const unsigned FakeAddrSpaceMap[] = {
698 1, // opencl_global
699 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000700 3, // opencl_constant
701 4, // cuda_device
702 5, // cuda_constant
703 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000704 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000705 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000706 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000707 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000708 }
709}
710
David Tweed31d09b02013-09-13 12:04:22 +0000711static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
712 const LangOptions &LangOpts) {
713 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000714 case LangOptions::ASMM_Target:
715 return TI.useAddressSpaceMapMangling();
716 case LangOptions::ASMM_On:
717 return true;
718 case LangOptions::ASMM_Off:
719 return false;
720 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000721 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000722}
723
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000724ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000725 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000726 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000727 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000728 unsigned size_reserve,
729 bool DelayInitialization)
730 : FunctionProtoTypes(this_()),
731 TemplateSpecializationTypes(this_()),
732 DependentTemplateSpecializationTypes(this_()),
733 SubstTemplateTemplateParmPacks(this_()),
734 GlobalNestedNameSpecifier(0),
Nico Webere1687c52013-06-20 21:44:55 +0000735 Int128Decl(0), UInt128Decl(0), Float128StubDecl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000736 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000737 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanianf2578572012-08-30 18:49:41 +0000738 BOOLDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000739 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000740 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000741 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
742 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
743 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000744 NullTypeSourceInfo(QualType()),
745 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000746 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000747 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000748 Idents(idents), Selectors(sels),
749 BuiltinInfo(builtins),
750 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000751 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000752 Comments(SM), CommentsLoaded(false),
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000753 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
Rafael Espindolace2168f2013-05-29 19:51:12 +0000754 LastSDM(0, 0)
Douglas Gregore8bbc122011-09-02 00:18:52 +0000755{
Mike Stump11289f42009-09-09 15:08:12 +0000756 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000757 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000758
759 if (!DelayInitialization) {
760 assert(t && "No target supplied for ASTContext initialization");
761 InitBuiltinTypes(*t);
762 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000763}
764
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000765ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000766 // Release the DenseMaps associated with DeclContext objects.
767 // FIXME: Is this the ideal solution?
768 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000769
Manuel Klimeka7328992013-06-03 13:51:33 +0000770 // Call all of the deallocation functions on all of their targets.
771 for (DeallocationMap::const_iterator I = Deallocations.begin(),
772 E = Deallocations.end(); I != E; ++I)
773 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
774 (I->first)((I->second)[J]);
775
Ted Kremenek076baeb2010-06-08 23:00:58 +0000776 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000777 // because they can contain DenseMaps.
778 for (llvm::DenseMap<const ObjCContainerDecl*,
779 const ASTRecordLayout*>::iterator
780 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
781 // Increment in loop to prevent using deallocated memory.
782 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
783 R->Destroy(*this);
784
Ted Kremenek076baeb2010-06-08 23:00:58 +0000785 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
786 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
787 // Increment in loop to prevent using deallocated memory.
788 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
789 R->Destroy(*this);
790 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000791
792 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
793 AEnd = DeclAttrs.end();
794 A != AEnd; ++A)
795 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000796
Reid Kleckner588c9372014-02-19 23:44:52 +0000797 llvm::DeleteContainerSeconds(MangleNumberingContexts);
Douglas Gregor561eceb2010-08-30 16:49:28 +0000798}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000799
Douglas Gregor1a809332010-05-23 18:26:36 +0000800void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimeka7328992013-06-03 13:51:33 +0000801 Deallocations[Callback].push_back(Data);
Douglas Gregor1a809332010-05-23 18:26:36 +0000802}
803
Mike Stump11289f42009-09-09 15:08:12 +0000804void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000805ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
806 ExternalSource = Source;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000807}
808
Chris Lattner4eb445d2007-01-26 01:27:23 +0000809void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000810 llvm::errs() << "\n*** AST Context Stats:\n";
811 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000812
Douglas Gregora30d0462009-05-26 14:40:08 +0000813 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000814#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000815#define ABSTRACT_TYPE(Name, Parent)
816#include "clang/AST/TypeNodes.def"
817 0 // Extra
818 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000819
Chris Lattner4eb445d2007-01-26 01:27:23 +0000820 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
821 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000822 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000823 }
824
Douglas Gregora30d0462009-05-26 14:40:08 +0000825 unsigned Idx = 0;
826 unsigned TotalBytes = 0;
827#define TYPE(Name, Parent) \
828 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000829 llvm::errs() << " " << counts[Idx] << " " << #Name \
830 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000831 TotalBytes += counts[Idx] * sizeof(Name##Type); \
832 ++Idx;
833#define ABSTRACT_TYPE(Name, Parent)
834#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000835
Chandler Carruth3c147a72011-07-04 05:32:14 +0000836 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
837
Douglas Gregor7454c562010-07-02 20:37:36 +0000838 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000839 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
840 << NumImplicitDefaultConstructors
841 << " implicit default constructors created\n";
842 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
843 << NumImplicitCopyConstructors
844 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000845 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000846 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
847 << NumImplicitMoveConstructors
848 << " implicit move constructors created\n";
849 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
850 << NumImplicitCopyAssignmentOperators
851 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000852 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000853 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
854 << NumImplicitMoveAssignmentOperators
855 << " implicit move assignment operators created\n";
856 llvm::errs() << NumImplicitDestructorsDeclared << "/"
857 << NumImplicitDestructors
858 << " implicit destructors created\n";
859
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000860 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000861 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000862 ExternalSource->PrintStats();
863 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000864
Douglas Gregor5b11d492010-07-25 17:53:33 +0000865 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000866}
867
Alp Toker2dea15b2013-12-17 01:22:38 +0000868RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
869 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000870 SourceLocation Loc;
871 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +0000872 if (getLangOpts().CPlusPlus)
873 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
874 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000875 else
Alp Toker2dea15b2013-12-17 01:22:38 +0000876 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
877 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000878 NewDecl->setImplicit();
879 return NewDecl;
880}
881
882TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
883 StringRef Name) const {
884 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
885 TypedefDecl *NewDecl = TypedefDecl::Create(
886 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
887 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
888 NewDecl->setImplicit();
889 return NewDecl;
890}
891
Douglas Gregor801c99d2011-08-12 06:49:56 +0000892TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000893 if (!Int128Decl)
894 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000895 return Int128Decl;
896}
897
898TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000899 if (!UInt128Decl)
900 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000901 return UInt128Decl;
902}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000903
Nico Webere1687c52013-06-20 21:44:55 +0000904TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber5b0b46f2013-06-21 01:29:36 +0000905 assert(LangOpts.CPlusPlus && "should only be called for c++");
Alp Toker56b5cc92013-12-15 10:36:26 +0000906 if (!Float128StubDecl)
Alp Toker2dea15b2013-12-17 01:22:38 +0000907 Float128StubDecl = buildImplicitRecord("__float128");
Alp Toker56b5cc92013-12-15 10:36:26 +0000908
Nico Webere1687c52013-06-20 21:44:55 +0000909 return Float128StubDecl;
910}
911
John McCall48f2d582009-10-23 23:03:21 +0000912void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000913 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000914 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000915 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000916}
917
Douglas Gregore8bbc122011-09-02 00:18:52 +0000918void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
919 assert((!this->Target || this->Target == &Target) &&
920 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000921 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000922
Douglas Gregore8bbc122011-09-02 00:18:52 +0000923 this->Target = &Target;
924
925 ABI.reset(createCXXABI(Target));
926 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +0000927 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000928
Chris Lattner970e54e2006-11-12 00:37:36 +0000929 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000930 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000931
Chris Lattner970e54e2006-11-12 00:37:36 +0000932 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000933 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000934 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000935 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000936 InitBuiltinType(CharTy, BuiltinType::Char_S);
937 else
938 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000939 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000940 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
941 InitBuiltinType(ShortTy, BuiltinType::Short);
942 InitBuiltinType(IntTy, BuiltinType::Int);
943 InitBuiltinType(LongTy, BuiltinType::Long);
944 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000945
Chris Lattner970e54e2006-11-12 00:37:36 +0000946 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000947 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
948 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
949 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
950 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
951 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000952
Chris Lattner970e54e2006-11-12 00:37:36 +0000953 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000954 InitBuiltinType(FloatTy, BuiltinType::Float);
955 InitBuiltinType(DoubleTy, BuiltinType::Double);
956 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000957
Chris Lattnerf122cef2009-04-30 02:43:43 +0000958 // GNU extension, 128-bit integers.
959 InitBuiltinType(Int128Ty, BuiltinType::Int128);
960 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
961
Hans Wennborg0d81e012013-05-10 10:08:40 +0000962 // C++ 3.9.1p5
963 if (TargetInfo::isTypeSigned(Target.getWCharType()))
964 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
965 else // -fshort-wchar makes wchar_t be unsigned.
966 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
967 if (LangOpts.CPlusPlus && LangOpts.WChar)
968 WideCharTy = WCharTy;
969 else {
970 // C99 (or C++ using -fno-wchar).
971 WideCharTy = getFromTargetType(Target.getWCharType());
972 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000973
James Molloy36365542012-05-04 10:55:22 +0000974 WIntTy = getFromTargetType(Target.getWIntType());
975
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000976 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
977 InitBuiltinType(Char16Ty, BuiltinType::Char16);
978 else // C99
979 Char16Ty = getFromTargetType(Target.getChar16Type());
980
981 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
982 InitBuiltinType(Char32Ty, BuiltinType::Char32);
983 else // C99
984 Char32Ty = getFromTargetType(Target.getChar32Type());
985
Douglas Gregor4619e432008-12-05 23:32:09 +0000986 // Placeholder type for type-dependent expressions whose type is
987 // completely unknown. No code should ever check a type against
988 // DependentTy and users should never see it; however, it is here to
989 // help diagnose failures to properly check for type-dependent
990 // expressions.
991 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000992
John McCall36e7fe32010-10-12 00:20:44 +0000993 // Placeholder type for functions.
994 InitBuiltinType(OverloadTy, BuiltinType::Overload);
995
John McCall0009fcc2011-04-26 20:42:42 +0000996 // Placeholder type for bound members.
997 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
998
John McCall526ab472011-10-25 17:37:35 +0000999 // Placeholder type for pseudo-objects.
1000 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1001
John McCall31996342011-04-07 08:22:57 +00001002 // "any" type; useful for debugger-like clients.
1003 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1004
John McCall8a6b59a2011-10-17 18:09:15 +00001005 // Placeholder type for unbridged ARC casts.
1006 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1007
Eli Friedman34866c72012-08-31 00:14:07 +00001008 // Placeholder type for builtin functions.
1009 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1010
Chris Lattner970e54e2006-11-12 00:37:36 +00001011 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001012 FloatComplexTy = getComplexType(FloatTy);
1013 DoubleComplexTy = getComplexType(DoubleTy);
1014 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001015
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001016 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001017 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1018 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001019 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001020
1021 if (LangOpts.OpenCL) {
1022 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1023 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1024 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1025 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1026 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
1027 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001028
Guy Benyei61054192013-02-07 10:55:47 +00001029 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001030 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001031 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001032
1033 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001034 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1035 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001036
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001037 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001038
1039 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001040
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001041 // void * type
1042 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001043
1044 // nullptr type (C++0x 2.14.7)
1045 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001046
1047 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1048 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001049
1050 // Builtin type used to help define __builtin_va_list.
1051 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +00001052}
1053
David Blaikie9c902b52011-09-25 23:23:43 +00001054DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001055 return SourceMgr.getDiagnostics();
1056}
1057
Douglas Gregor561eceb2010-08-30 16:49:28 +00001058AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1059 AttrVec *&Result = DeclAttrs[D];
1060 if (!Result) {
1061 void *Mem = Allocate(sizeof(AttrVec));
1062 Result = new (Mem) AttrVec;
1063 }
1064
1065 return *Result;
1066}
1067
1068/// \brief Erase the attributes corresponding to the given declaration.
1069void ASTContext::eraseDeclAttrs(const Decl *D) {
1070 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1071 if (Pos != DeclAttrs.end()) {
1072 Pos->second->~AttrVec();
1073 DeclAttrs.erase(Pos);
1074 }
1075}
1076
Larisse Voufo39a1e502013-08-06 01:03:05 +00001077// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001078MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001079ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001080 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001081 return getTemplateOrSpecializationInfo(Var)
1082 .dyn_cast<MemberSpecializationInfo *>();
1083}
1084
1085ASTContext::TemplateOrSpecializationInfo
1086ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1087 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1088 TemplateOrInstantiation.find(Var);
1089 if (Pos == TemplateOrInstantiation.end())
1090 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001091
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001092 return Pos->second;
1093}
1094
Mike Stump11289f42009-09-09 15:08:12 +00001095void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001096ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001097 TemplateSpecializationKind TSK,
1098 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001099 assert(Inst->isStaticDataMember() && "Not a static data member");
1100 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001101 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1102 Tmpl, TSK, PointOfInstantiation));
1103}
1104
1105void
1106ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1107 TemplateOrSpecializationInfo TSI) {
1108 assert(!TemplateOrInstantiation[Inst] &&
1109 "Already noted what the variable was instantiated from");
1110 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001111}
1112
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001113FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1114 const FunctionDecl *FD){
1115 assert(FD && "Specialization is 0");
1116 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001117 = ClassScopeSpecializationPattern.find(FD);
1118 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001119 return 0;
1120
1121 return Pos->second;
1122}
1123
1124void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1125 FunctionDecl *Pattern) {
1126 assert(FD && "Specialization is 0");
1127 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001128 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001129}
1130
John McCalle61f2ba2009-11-18 02:36:19 +00001131NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001132ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001133 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001134 = InstantiatedFromUsingDecl.find(UUD);
1135 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001136 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001137
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001138 return Pos->second;
1139}
1140
1141void
John McCallb96ec562009-12-04 22:46:56 +00001142ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1143 assert((isa<UsingDecl>(Pattern) ||
1144 isa<UnresolvedUsingValueDecl>(Pattern) ||
1145 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1146 "pattern decl is not a using decl");
1147 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1148 InstantiatedFromUsingDecl[Inst] = Pattern;
1149}
1150
1151UsingShadowDecl *
1152ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1153 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1154 = InstantiatedFromUsingShadowDecl.find(Inst);
1155 if (Pos == InstantiatedFromUsingShadowDecl.end())
1156 return 0;
1157
1158 return Pos->second;
1159}
1160
1161void
1162ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1163 UsingShadowDecl *Pattern) {
1164 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1165 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001166}
1167
Anders Carlsson5da84842009-09-01 04:26:58 +00001168FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1169 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1170 = InstantiatedFromUnnamedFieldDecl.find(Field);
1171 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1172 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001173
Anders Carlsson5da84842009-09-01 04:26:58 +00001174 return Pos->second;
1175}
1176
1177void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1178 FieldDecl *Tmpl) {
1179 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1180 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1181 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1182 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001183
Anders Carlsson5da84842009-09-01 04:26:58 +00001184 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1185}
1186
Douglas Gregor832940b2010-03-02 23:58:15 +00001187ASTContext::overridden_cxx_method_iterator
1188ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1189 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001190 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001191 if (Pos == OverriddenMethods.end())
1192 return 0;
1193
1194 return Pos->second.begin();
1195}
1196
1197ASTContext::overridden_cxx_method_iterator
1198ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1199 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001200 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001201 if (Pos == OverriddenMethods.end())
1202 return 0;
1203
1204 return Pos->second.end();
1205}
1206
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001207unsigned
1208ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1209 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001210 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001211 if (Pos == OverriddenMethods.end())
1212 return 0;
1213
1214 return Pos->second.size();
1215}
1216
Douglas Gregor832940b2010-03-02 23:58:15 +00001217void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1218 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001219 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001220 OverriddenMethods[Method].push_back(Overridden);
1221}
1222
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001223void ASTContext::getOverriddenMethods(
1224 const NamedDecl *D,
1225 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001226 assert(D);
1227
1228 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001229 Overridden.append(overridden_methods_begin(CXXMethod),
1230 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001231 return;
1232 }
1233
1234 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1235 if (!Method)
1236 return;
1237
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001238 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1239 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001240 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001241}
1242
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001243void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1244 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1245 assert(!Import->isFromASTFile() && "Non-local import declaration");
1246 if (!FirstLocalImport) {
1247 FirstLocalImport = Import;
1248 LastLocalImport = Import;
1249 return;
1250 }
1251
1252 LastLocalImport->NextLocalImport = Import;
1253 LastLocalImport = Import;
1254}
1255
Chris Lattner53cfe802007-07-18 17:52:12 +00001256//===----------------------------------------------------------------------===//
1257// Type Sizing and Analysis
1258//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001259
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001260/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1261/// scalar floating point type.
1262const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001263 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001264 assert(BT && "Not a floating point type!");
1265 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001266 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001267 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001268 case BuiltinType::Float: return Target->getFloatFormat();
1269 case BuiltinType::Double: return Target->getDoubleFormat();
1270 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001271 }
1272}
1273
Rafael Espindola71eccb32013-08-08 19:53:46 +00001274CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001275 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001276
John McCall94268702010-10-08 18:24:19 +00001277 bool UseAlignAttrOnly = false;
1278 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1279 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001280
John McCall94268702010-10-08 18:24:19 +00001281 // __attribute__((aligned)) can increase or decrease alignment
1282 // *except* on a struct or struct member, where it only increases
1283 // alignment unless 'packed' is also specified.
1284 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001285 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001286 // ignore that possibility; Sema should diagnose it.
1287 if (isa<FieldDecl>(D)) {
1288 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1289 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1290 } else {
1291 UseAlignAttrOnly = true;
1292 }
1293 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001294 else if (isa<FieldDecl>(D))
1295 UseAlignAttrOnly =
1296 D->hasAttr<PackedAttr>() ||
1297 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001298
John McCall4e819612011-01-20 07:57:12 +00001299 // If we're using the align attribute only, just ignore everything
1300 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001301 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001302 // do nothing
1303
John McCall94268702010-10-08 18:24:19 +00001304 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001305 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001306 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001307 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001308 T = RT->getPointeeType();
1309 else
1310 T = getPointerType(RT->getPointeeType());
1311 }
1312 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001313 // Adjust alignments of declarations with array type by the
1314 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001315 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001316 unsigned MinWidth = Target->getLargeArrayMinWidth();
1317 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001318 if (isa<VariableArrayType>(arrayType))
1319 Align = std::max(Align, Target->getLargeArrayAlign());
1320 else if (isa<ConstantArrayType>(arrayType) &&
1321 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1322 Align = std::max(Align, Target->getLargeArrayAlign());
1323 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001324
John McCall33ddac02011-01-19 10:06:00 +00001325 // Walk through any array types while we're at it.
1326 T = getBaseElementType(arrayType);
1327 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001328 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001329 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1330 if (VD->hasGlobalStorage())
1331 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1332 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001333 }
John McCall4e819612011-01-20 07:57:12 +00001334
1335 // Fields can be subject to extra alignment constraints, like if
1336 // the field is packed, the struct is packed, or the struct has a
1337 // a max-field-alignment constraint (#pragma pack). So calculate
1338 // the actual alignment of the field within the struct, and then
1339 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001340 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1341 const RecordDecl *Parent = Field->getParent();
1342 // We can only produce a sensible answer if the record is valid.
1343 if (!Parent->isInvalidDecl()) {
1344 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001345
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001346 // Start with the record's overall alignment.
1347 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001348
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001349 // Use the GCD of that and the offset within the record.
1350 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1351 if (Offset > 0) {
1352 // Alignment is always a power of 2, so the GCD will be a power of 2,
1353 // which means we get to do this crazy thing instead of Euclid's.
1354 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1355 if (LowBitOfOffset < FieldAlign)
1356 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1357 }
1358
1359 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001360 }
Charles Davis3fc51072010-02-23 04:52:00 +00001361 }
Chris Lattner68061312009-01-24 21:53:27 +00001362 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001363
Ken Dyckcc56c542011-01-15 18:38:59 +00001364 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001365}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001366
John McCallf1249922012-08-21 04:10:00 +00001367// getTypeInfoDataSizeInChars - Return the size of a type, in
1368// chars. If the type is a record, its data size is returned. This is
1369// the size of the memcpy that's performed when assigning this type
1370// using a trivial copy/move assignment operator.
1371std::pair<CharUnits, CharUnits>
1372ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1373 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1374
1375 // In C++, objects can sometimes be allocated into the tail padding
1376 // of a base-class subobject. We decide whether that's possible
1377 // during class layout, so here we can just trust the layout results.
1378 if (getLangOpts().CPlusPlus) {
1379 if (const RecordType *RT = T->getAs<RecordType>()) {
1380 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1381 sizeAndAlign.first = layout.getDataSize();
1382 }
1383 }
1384
1385 return sizeAndAlign;
1386}
1387
Richard Trieu04d2d942013-05-14 21:59:17 +00001388/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1389/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1390std::pair<CharUnits, CharUnits>
1391static getConstantArrayInfoInChars(const ASTContext &Context,
1392 const ConstantArrayType *CAT) {
1393 std::pair<CharUnits, CharUnits> EltInfo =
1394 Context.getTypeInfoInChars(CAT->getElementType());
1395 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001396 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1397 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001398 "Overflow in array type char size evaluation");
1399 uint64_t Width = EltInfo.first.getQuantity() * Size;
1400 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001401 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1402 Context.getTargetInfo().getPointerWidth(0) == 64)
1403 Width = llvm::RoundUpToAlignment(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001404 return std::make_pair(CharUnits::fromQuantity(Width),
1405 CharUnits::fromQuantity(Align));
1406}
1407
John McCall87fe5d52010-05-20 01:18:31 +00001408std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001409ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001410 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1411 return getConstantArrayInfoInChars(*this, CAT);
John McCall87fe5d52010-05-20 01:18:31 +00001412 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +00001413 return std::make_pair(toCharUnitsFromBits(Info.first),
1414 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +00001415}
1416
1417std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001418ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001419 return getTypeInfoInChars(T.getTypePtr());
1420}
1421
Daniel Dunbarc6475872012-03-09 04:12:54 +00001422std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1423 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1424 if (it != MemoizedTypeInfo.end())
1425 return it->second;
1426
1427 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1428 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1429 return Info;
1430}
1431
1432/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1433/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001434///
1435/// FIXME: Pointers into different addr spaces could have different sizes and
1436/// alignment requirements: getPointerInfo should take an AddrSpace, this
1437/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001438std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001439ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001440 uint64_t Width=0;
1441 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001442 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001443#define TYPE(Class, Base)
1444#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001445#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001446#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001447#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1448 case Type::Class: \
1449 assert(!T->isDependentType() && "should not see dependent types here"); \
1450 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001451#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001452 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001453
Chris Lattner355332d2007-07-13 22:27:08 +00001454 case Type::FunctionNoProto:
1455 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001456 // GCC extension: alignof(function) = 32 bits
1457 Width = 0;
1458 Align = 32;
1459 break;
1460
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001461 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001462 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001463 Width = 0;
1464 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1465 break;
1466
Steve Naroff5c131802007-08-30 01:06:46 +00001467 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001468 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001469
Chris Lattner37e05872008-03-05 18:54:05 +00001470 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001471 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001472 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1473 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001474 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001475 Align = EltInfo.second;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001476 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1477 getTargetInfo().getPointerWidth(0) == 64)
1478 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001479 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001480 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001481 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001482 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001483 const VectorType *VT = cast<VectorType>(T);
1484 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1485 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001486 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001487 // If the alignment is not a power of 2, round up to the next power of 2.
1488 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001489 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001490 Align = llvm::NextPowerOf2(Align);
1491 Width = llvm::RoundUpToAlignment(Width, Align);
1492 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001493 // Adjust the alignment based on the target max.
1494 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1495 if (TargetVectorAlign && TargetVectorAlign < Align)
1496 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001497 break;
1498 }
Chris Lattner647fb222007-07-18 18:26:58 +00001499
Chris Lattner7570e9c2008-03-08 08:52:55 +00001500 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001501 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001502 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001503 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001504 // GCC extension: alignof(void) = 8 bits.
1505 Width = 0;
1506 Align = 8;
1507 break;
1508
Chris Lattner6a4f7452007-12-19 19:23:28 +00001509 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001510 Width = Target->getBoolWidth();
1511 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001512 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001513 case BuiltinType::Char_S:
1514 case BuiltinType::Char_U:
1515 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001516 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001517 Width = Target->getCharWidth();
1518 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001519 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001520 case BuiltinType::WChar_S:
1521 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001522 Width = Target->getWCharWidth();
1523 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001524 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001525 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001526 Width = Target->getChar16Width();
1527 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001528 break;
1529 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001530 Width = Target->getChar32Width();
1531 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001532 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001533 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001534 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001535 Width = Target->getShortWidth();
1536 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001537 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001538 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001539 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001540 Width = Target->getIntWidth();
1541 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001542 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001543 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001544 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001545 Width = Target->getLongWidth();
1546 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001547 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001548 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001549 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001550 Width = Target->getLongLongWidth();
1551 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001552 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001553 case BuiltinType::Int128:
1554 case BuiltinType::UInt128:
1555 Width = 128;
1556 Align = 128; // int128_t is 128-bit aligned on all targets.
1557 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001558 case BuiltinType::Half:
1559 Width = Target->getHalfWidth();
1560 Align = Target->getHalfAlign();
1561 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001562 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001563 Width = Target->getFloatWidth();
1564 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001565 break;
1566 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001567 Width = Target->getDoubleWidth();
1568 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001569 break;
1570 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001571 Width = Target->getLongDoubleWidth();
1572 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001573 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001574 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001575 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1576 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001577 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001578 case BuiltinType::ObjCId:
1579 case BuiltinType::ObjCClass:
1580 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001581 Width = Target->getPointerWidth(0);
1582 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001583 break;
Guy Benyei61054192013-02-07 10:55:47 +00001584 case BuiltinType::OCLSampler:
1585 // Samplers are modeled as integers.
1586 Width = Target->getIntWidth();
1587 Align = Target->getIntAlign();
1588 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001589 case BuiltinType::OCLEvent:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001590 case BuiltinType::OCLImage1d:
1591 case BuiltinType::OCLImage1dArray:
1592 case BuiltinType::OCLImage1dBuffer:
1593 case BuiltinType::OCLImage2d:
1594 case BuiltinType::OCLImage2dArray:
1595 case BuiltinType::OCLImage3d:
1596 // Currently these types are pointers to opaque types.
1597 Width = Target->getPointerWidth(0);
1598 Align = Target->getPointerAlign(0);
1599 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001600 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001601 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001602 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001603 Width = Target->getPointerWidth(0);
1604 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001605 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001606 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001607 unsigned AS = getTargetAddressSpace(
1608 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001609 Width = Target->getPointerWidth(AS);
1610 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001611 break;
1612 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001613 case Type::LValueReference:
1614 case Type::RValueReference: {
1615 // alignof and sizeof should never enter this code path here, so we go
1616 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001617 unsigned AS = getTargetAddressSpace(
1618 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001619 Width = Target->getPointerWidth(AS);
1620 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001621 break;
1622 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001623 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001624 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001625 Width = Target->getPointerWidth(AS);
1626 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001627 break;
1628 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001629 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001630 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001631 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001632 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001633 }
Chris Lattner647fb222007-07-18 18:26:58 +00001634 case Type::Complex: {
1635 // Complex types have the same alignment as their elements, but twice the
1636 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001637 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001638 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001639 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001640 Align = EltInfo.second;
1641 break;
1642 }
John McCall8b07ec22010-05-15 11:32:37 +00001643 case Type::ObjCObject:
1644 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001645 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001646 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001647 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001648 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001649 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001650 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001651 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001652 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001653 break;
1654 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001655 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001656 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001657 const TagType *TT = cast<TagType>(T);
1658
1659 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001660 Width = 8;
1661 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001662 break;
1663 }
Mike Stump11289f42009-09-09 15:08:12 +00001664
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001665 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001666 return getTypeInfo(ET->getDecl()->getIntegerType());
1667
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001668 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001669 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001670 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001671 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001672 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001673 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001674
Chris Lattner63d2b362009-10-22 05:17:15 +00001675 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001676 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1677 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001678
Richard Smith30482bc2011-02-20 03:19:35 +00001679 case Type::Auto: {
1680 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001681 assert(!A->getDeducedType().isNull() &&
1682 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001683 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001684 }
1685
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001686 case Type::Paren:
1687 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1688
Douglas Gregoref462e62009-04-30 17:32:17 +00001689 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001690 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001691 std::pair<uint64_t, unsigned> Info
1692 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001693 // If the typedef has an aligned attribute on it, it overrides any computed
1694 // alignment we have. This violates the GCC documentation (which says that
1695 // attribute(aligned) can only round up) but matches its implementation.
1696 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1697 Align = AttrAlign;
1698 else
1699 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001700 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001701 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001702 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001703
Abramo Bagnara6150c882010-05-11 21:36:43 +00001704 case Type::Elaborated:
1705 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001706
John McCall81904512011-01-06 01:58:22 +00001707 case Type::Attributed:
1708 return getTypeInfo(
1709 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1710
Eli Friedman0dfb8892011-10-06 23:00:33 +00001711 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001712 // Start with the base type information.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001713 std::pair<uint64_t, unsigned> Info
1714 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1715 Width = Info.first;
1716 Align = Info.second;
John McCalla8ec7eb2013-03-07 21:37:17 +00001717
1718 // If the size of the type doesn't exceed the platform's max
1719 // atomic promotion width, make the size and alignment more
1720 // favorable to atomic operations:
1721 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1722 // Round the size up to a power of 2.
1723 if (!llvm::isPowerOf2_64(Width))
1724 Width = llvm::NextPowerOf2(Width);
1725
1726 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001727 Align = static_cast<unsigned>(Width);
1728 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001729 }
1730
Douglas Gregoref462e62009-04-30 17:32:17 +00001731 }
Mike Stump11289f42009-09-09 15:08:12 +00001732
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001733 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001734 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001735}
1736
Ken Dyckcc56c542011-01-15 18:38:59 +00001737/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1738CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1739 return CharUnits::fromQuantity(BitSize / getCharWidth());
1740}
1741
Ken Dyckb0fcc592011-02-11 01:54:29 +00001742/// toBits - Convert a size in characters to a size in characters.
1743int64_t ASTContext::toBits(CharUnits CharSize) const {
1744 return CharSize.getQuantity() * getCharWidth();
1745}
1746
Ken Dyck8c89d592009-12-22 14:23:30 +00001747/// getTypeSizeInChars - Return the size of the specified type, in characters.
1748/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001749CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001750 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001751}
Jay Foad39c79802011-01-12 09:06:06 +00001752CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001753 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001754}
1755
Ken Dycka6046ab2010-01-26 17:25:18 +00001756/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001757/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001758CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001759 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001760}
Jay Foad39c79802011-01-12 09:06:06 +00001761CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001762 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001763}
1764
Chris Lattnera3402cd2009-01-27 18:08:34 +00001765/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1766/// type for the current target in bits. This can be different than the ABI
1767/// alignment in cases where it is beneficial for performance to overalign
1768/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001769unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001770 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001771
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001772 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1773 return ABIAlign; // Never overalign on XCore.
1774
David Majnemer8b6bd572014-02-24 23:34:17 +00001775 const TypedefType *TT = T->getAs<TypedefType>();
1776
Eli Friedman7ab09572009-05-25 21:27:19 +00001777 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00001778 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001779 T = CT->getElementType().getTypePtr();
1780 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001781 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1782 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00001783 // Don't increase the alignment if an alignment attribute was specified on a
1784 // typedef declaration.
1785 if (!TT || !TT->getDecl()->getMaxAlignment())
1786 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00001787
Chris Lattnera3402cd2009-01-27 18:08:34 +00001788 return ABIAlign;
1789}
1790
Ulrich Weigandfa806422013-05-06 16:23:57 +00001791/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1792/// to a global variable of the specified type.
1793unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1794 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1795}
1796
1797/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1798/// should be given to a global variable of the specified type.
1799CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1800 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1801}
1802
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001803/// DeepCollectObjCIvars -
1804/// This routine first collects all declared, but not synthesized, ivars in
1805/// super class and then collects all ivars, including those synthesized for
1806/// current class. This routine is used for implementation of current class
1807/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001808///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001809void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1810 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001811 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001812 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1813 DeepCollectObjCIvars(SuperClass, false, Ivars);
1814 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00001815 for (const auto *I : OI->ivars())
1816 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001817 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001818 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001819 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001820 Iv= Iv->getNextIvar())
1821 Ivars.push_back(Iv);
1822 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001823}
1824
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001825/// CollectInheritedProtocols - Collect all protocols in current class and
1826/// those inherited by it.
1827void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001828 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001829 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001830 // We can use protocol_iterator here instead of
1831 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001832 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001833 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001834 for (auto *P : Proto->protocols()) {
1835 Protocols.insert(P->getCanonicalDecl());
1836 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001837 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001838 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001839
1840 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00001841 for (const auto *Cat : OI->visible_categories())
1842 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001843
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001844 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1845 while (SD) {
1846 CollectInheritedProtocols(SD, Protocols);
1847 SD = SD->getSuperClass();
1848 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001849 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00001850 for (auto *Proto : OC->protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001851 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001852 for (const auto *P : Proto->protocols())
1853 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001854 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001855 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001856 for (auto *Proto : OP->protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001857 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001858 for (const auto *P : Proto->protocols())
1859 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001860 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001861 }
1862}
1863
Jay Foad39c79802011-01-12 09:06:06 +00001864unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001865 unsigned count = 0;
1866 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00001867 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001868 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001869
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001870 // Count ivar defined in this class's implementation. This
1871 // includes synthesized ivars.
1872 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001873 count += ImplDecl->ivar_size();
1874
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001875 return count;
1876}
1877
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001878bool ASTContext::isSentinelNullExpr(const Expr *E) {
1879 if (!E)
1880 return false;
1881
1882 // nullptr_t is always treated as null.
1883 if (E->getType()->isNullPtrType()) return true;
1884
1885 if (E->getType()->isAnyPointerType() &&
1886 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1887 Expr::NPC_ValueDependentIsNull))
1888 return true;
1889
1890 // Unfortunately, __null has type 'int'.
1891 if (isa<GNUNullExpr>(E)) return true;
1892
1893 return false;
1894}
1895
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001896/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1897ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1898 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1899 I = ObjCImpls.find(D);
1900 if (I != ObjCImpls.end())
1901 return cast<ObjCImplementationDecl>(I->second);
1902 return 0;
1903}
1904/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1905ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1906 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1907 I = ObjCImpls.find(D);
1908 if (I != ObjCImpls.end())
1909 return cast<ObjCCategoryImplDecl>(I->second);
1910 return 0;
1911}
1912
1913/// \brief Set the implementation of ObjCInterfaceDecl.
1914void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1915 ObjCImplementationDecl *ImplD) {
1916 assert(IFaceD && ImplD && "Passed null params");
1917 ObjCImpls[IFaceD] = ImplD;
1918}
1919/// \brief Set the implementation of ObjCCategoryDecl.
1920void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1921 ObjCCategoryImplDecl *ImplD) {
1922 assert(CatD && ImplD && "Passed null params");
1923 ObjCImpls[CatD] = ImplD;
1924}
1925
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001926const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1927 const NamedDecl *ND) const {
1928 if (const ObjCInterfaceDecl *ID =
1929 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001930 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001931 if (const ObjCCategoryDecl *CD =
1932 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001933 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001934 if (const ObjCImplDecl *IMD =
1935 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001936 return IMD->getClassInterface();
1937
1938 return 0;
1939}
1940
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001941/// \brief Get the copy initialization expression of VarDecl,or NULL if
1942/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001943Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001944 assert(VD && "Passed null params");
1945 assert(VD->hasAttr<BlocksAttr>() &&
1946 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001947 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001948 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001949 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1950}
1951
1952/// \brief Set the copy inialization expression of a block var decl.
1953void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1954 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001955 assert(VD->hasAttr<BlocksAttr>() &&
1956 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001957 BlockVarCopyInits[VD] = Init;
1958}
1959
John McCallbcd03502009-12-07 02:54:59 +00001960TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001961 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001962 if (!DataSize)
1963 DataSize = TypeLoc::getFullDataSizeForType(T);
1964 else
1965 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001966 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001967
John McCallbcd03502009-12-07 02:54:59 +00001968 TypeSourceInfo *TInfo =
1969 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1970 new (TInfo) TypeSourceInfo(T);
1971 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001972}
1973
John McCallbcd03502009-12-07 02:54:59 +00001974TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001975 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001976 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001977 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001978 return DI;
1979}
1980
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001981const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001982ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001983 return getObjCLayout(D, 0);
1984}
1985
1986const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001987ASTContext::getASTObjCImplementationLayout(
1988 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001989 return getObjCLayout(D->getClassInterface(), D);
1990}
1991
Chris Lattner983a8bb2007-07-13 22:13:22 +00001992//===----------------------------------------------------------------------===//
1993// Type creation/memoization methods
1994//===----------------------------------------------------------------------===//
1995
Jay Foad39c79802011-01-12 09:06:06 +00001996QualType
John McCall33ddac02011-01-19 10:06:00 +00001997ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1998 unsigned fastQuals = quals.getFastQualifiers();
1999 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002000
2001 // Check if we've already instantiated this type.
2002 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002003 ExtQuals::Profile(ID, baseType, quals);
2004 void *insertPos = 0;
2005 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2006 assert(eq->getQualifiers() == quals);
2007 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002008 }
2009
John McCall33ddac02011-01-19 10:06:00 +00002010 // If the base type is not canonical, make the appropriate canonical type.
2011 QualType canon;
2012 if (!baseType->isCanonicalUnqualified()) {
2013 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002014 canonSplit.Quals.addConsistentQualifiers(quals);
2015 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002016
2017 // Re-find the insert position.
2018 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2019 }
2020
2021 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2022 ExtQualNodes.InsertNode(eq, insertPos);
2023 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002024}
2025
Jay Foad39c79802011-01-12 09:06:06 +00002026QualType
2027ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002028 QualType CanT = getCanonicalType(T);
2029 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002030 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002031
John McCall8ccfcb52009-09-24 19:53:00 +00002032 // If we are composing extended qualifiers together, merge together
2033 // into one ExtQuals node.
2034 QualifierCollector Quals;
2035 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002036
John McCall8ccfcb52009-09-24 19:53:00 +00002037 // If this type already has an address space specified, it cannot get
2038 // another one.
2039 assert(!Quals.hasAddressSpace() &&
2040 "Type cannot be in multiple addr spaces!");
2041 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002042
John McCall8ccfcb52009-09-24 19:53:00 +00002043 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002044}
2045
Chris Lattnerd60183d2009-02-18 22:53:11 +00002046QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002047 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002048 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002049 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002050 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002051
John McCall53fa7142010-12-24 02:08:15 +00002052 if (const PointerType *ptr = T->getAs<PointerType>()) {
2053 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002054 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002055 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2056 return getPointerType(ResultType);
2057 }
2058 }
Mike Stump11289f42009-09-09 15:08:12 +00002059
John McCall8ccfcb52009-09-24 19:53:00 +00002060 // If we are composing extended qualifiers together, merge together
2061 // into one ExtQuals node.
2062 QualifierCollector Quals;
2063 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002064
John McCall8ccfcb52009-09-24 19:53:00 +00002065 // If this type already has an ObjCGC specified, it cannot get
2066 // another one.
2067 assert(!Quals.hasObjCGCAttr() &&
2068 "Type cannot have multiple ObjCGCs!");
2069 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002070
John McCall8ccfcb52009-09-24 19:53:00 +00002071 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002072}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002073
John McCall4f5019e2010-12-19 02:44:49 +00002074const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2075 FunctionType::ExtInfo Info) {
2076 if (T->getExtInfo() == Info)
2077 return T;
2078
2079 QualType Result;
2080 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002081 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002082 } else {
2083 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2084 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2085 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002086 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002087 }
2088
2089 return cast<FunctionType>(Result.getTypePtr());
2090}
2091
Richard Smith2a7d4812013-05-04 07:00:32 +00002092void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2093 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002094 FD = FD->getMostRecentDecl();
2095 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002096 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2097 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002098 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002099 if (FunctionDecl *Next = FD->getPreviousDecl())
2100 FD = Next;
2101 else
2102 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002103 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002104 if (ASTMutationListener *L = getASTMutationListener())
2105 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002106}
2107
Chris Lattnerc6395932007-06-22 20:56:16 +00002108/// getComplexType - Return the uniqued reference to the type for a complex
2109/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002110QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002111 // Unique pointers, to guarantee there is only one pointer of a particular
2112 // structure.
2113 llvm::FoldingSetNodeID ID;
2114 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002115
Chris Lattnerc6395932007-06-22 20:56:16 +00002116 void *InsertPos = 0;
2117 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2118 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002119
Chris Lattnerc6395932007-06-22 20:56:16 +00002120 // If the pointee type isn't canonical, this won't be a canonical type either,
2121 // so fill in the canonical type field.
2122 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002123 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002124 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002125
Chris Lattnerc6395932007-06-22 20:56:16 +00002126 // Get the new insert position for the node we care about.
2127 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002128 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002129 }
John McCall90d1c2d2009-09-24 23:30:46 +00002130 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002131 Types.push_back(New);
2132 ComplexTypes.InsertNode(New, InsertPos);
2133 return QualType(New, 0);
2134}
2135
Chris Lattner970e54e2006-11-12 00:37:36 +00002136/// getPointerType - Return the uniqued reference to the type for a pointer to
2137/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002138QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002139 // Unique pointers, to guarantee there is only one pointer of a particular
2140 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002141 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002142 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002143
Chris Lattner67521df2007-01-27 01:29:36 +00002144 void *InsertPos = 0;
2145 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002146 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002147
Chris Lattner7ccecb92006-11-12 08:50:50 +00002148 // If the pointee type isn't canonical, this won't be a canonical type either,
2149 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002150 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002151 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002152 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002153
Bob Wilsonc8541f22013-03-15 17:12:43 +00002154 // Get the new insert position for the node we care about.
2155 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2156 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2157 }
John McCall90d1c2d2009-09-24 23:30:46 +00002158 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002159 Types.push_back(New);
2160 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002161 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002162}
2163
Reid Kleckner0503a872013-12-05 01:23:43 +00002164QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2165 llvm::FoldingSetNodeID ID;
2166 AdjustedType::Profile(ID, Orig, New);
2167 void *InsertPos = 0;
2168 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2169 if (AT)
2170 return QualType(AT, 0);
2171
2172 QualType Canonical = getCanonicalType(New);
2173
2174 // Get the new insert position for the node we care about.
2175 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2176 assert(AT == 0 && "Shouldn't be in the map!");
2177
2178 AT = new (*this, TypeAlignment)
2179 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2180 Types.push_back(AT);
2181 AdjustedTypes.InsertNode(AT, InsertPos);
2182 return QualType(AT, 0);
2183}
2184
Reid Kleckner8a365022013-06-24 17:51:48 +00002185QualType ASTContext::getDecayedType(QualType T) const {
2186 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2187
Reid Kleckner8a365022013-06-24 17:51:48 +00002188 QualType Decayed;
2189
2190 // C99 6.7.5.3p7:
2191 // A declaration of a parameter as "array of type" shall be
2192 // adjusted to "qualified pointer to type", where the type
2193 // qualifiers (if any) are those specified within the [ and ] of
2194 // the array type derivation.
2195 if (T->isArrayType())
2196 Decayed = getArrayDecayedType(T);
2197
2198 // C99 6.7.5.3p8:
2199 // A declaration of a parameter as "function returning type"
2200 // shall be adjusted to "pointer to function returning type", as
2201 // in 6.3.2.1.
2202 if (T->isFunctionType())
2203 Decayed = getPointerType(T);
2204
Reid Kleckner0503a872013-12-05 01:23:43 +00002205 llvm::FoldingSetNodeID ID;
2206 AdjustedType::Profile(ID, T, Decayed);
2207 void *InsertPos = 0;
2208 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2209 if (AT)
2210 return QualType(AT, 0);
2211
Reid Kleckner8a365022013-06-24 17:51:48 +00002212 QualType Canonical = getCanonicalType(Decayed);
2213
2214 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002215 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2216 assert(AT == 0 && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002217
Reid Kleckner0503a872013-12-05 01:23:43 +00002218 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2219 Types.push_back(AT);
2220 AdjustedTypes.InsertNode(AT, InsertPos);
2221 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002222}
2223
Mike Stump11289f42009-09-09 15:08:12 +00002224/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002225/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002226QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002227 assert(T->isFunctionType() && "block of function types only");
2228 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002229 // structure.
2230 llvm::FoldingSetNodeID ID;
2231 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002232
Steve Naroffec33ed92008-08-27 16:04:49 +00002233 void *InsertPos = 0;
2234 if (BlockPointerType *PT =
2235 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2236 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002237
2238 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002239 // type either so fill in the canonical type field.
2240 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002241 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002242 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002243
Steve Naroffec33ed92008-08-27 16:04:49 +00002244 // Get the new insert position for the node we care about.
2245 BlockPointerType *NewIP =
2246 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002247 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002248 }
John McCall90d1c2d2009-09-24 23:30:46 +00002249 BlockPointerType *New
2250 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002251 Types.push_back(New);
2252 BlockPointerTypes.InsertNode(New, InsertPos);
2253 return QualType(New, 0);
2254}
2255
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002256/// getLValueReferenceType - Return the uniqued reference to the type for an
2257/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002258QualType
2259ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002260 assert(getCanonicalType(T) != OverloadTy &&
2261 "Unresolved overloaded function type");
2262
Bill Wendling3708c182007-05-27 10:15:43 +00002263 // Unique pointers, to guarantee there is only one pointer of a particular
2264 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002265 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002266 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002267
2268 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002269 if (LValueReferenceType *RT =
2270 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002271 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002272
John McCallfc93cf92009-10-22 22:37:11 +00002273 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2274
Bill Wendling3708c182007-05-27 10:15:43 +00002275 // If the referencee type isn't canonical, this won't be a canonical type
2276 // either, so fill in the canonical type field.
2277 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002278 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2279 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2280 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002281
Bill Wendling3708c182007-05-27 10:15:43 +00002282 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002283 LValueReferenceType *NewIP =
2284 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002285 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002286 }
2287
John McCall90d1c2d2009-09-24 23:30:46 +00002288 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002289 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2290 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002291 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002292 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002293
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002294 return QualType(New, 0);
2295}
2296
2297/// getRValueReferenceType - Return the uniqued reference to the type for an
2298/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002299QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002300 // Unique pointers, to guarantee there is only one pointer of a particular
2301 // structure.
2302 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002303 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002304
2305 void *InsertPos = 0;
2306 if (RValueReferenceType *RT =
2307 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2308 return QualType(RT, 0);
2309
John McCallfc93cf92009-10-22 22:37:11 +00002310 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2311
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002312 // If the referencee type isn't canonical, this won't be a canonical type
2313 // either, so fill in the canonical type field.
2314 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002315 if (InnerRef || !T.isCanonical()) {
2316 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2317 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002318
2319 // Get the new insert position for the node we care about.
2320 RValueReferenceType *NewIP =
2321 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002322 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002323 }
2324
John McCall90d1c2d2009-09-24 23:30:46 +00002325 RValueReferenceType *New
2326 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002327 Types.push_back(New);
2328 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002329 return QualType(New, 0);
2330}
2331
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002332/// getMemberPointerType - Return the uniqued reference to the type for a
2333/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002334QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002335 // Unique pointers, to guarantee there is only one pointer of a particular
2336 // structure.
2337 llvm::FoldingSetNodeID ID;
2338 MemberPointerType::Profile(ID, T, Cls);
2339
2340 void *InsertPos = 0;
2341 if (MemberPointerType *PT =
2342 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2343 return QualType(PT, 0);
2344
2345 // If the pointee or class type isn't canonical, this won't be a canonical
2346 // type either, so fill in the canonical type field.
2347 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002348 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002349 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2350
2351 // Get the new insert position for the node we care about.
2352 MemberPointerType *NewIP =
2353 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002354 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002355 }
John McCall90d1c2d2009-09-24 23:30:46 +00002356 MemberPointerType *New
2357 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002358 Types.push_back(New);
2359 MemberPointerTypes.InsertNode(New, InsertPos);
2360 return QualType(New, 0);
2361}
2362
Mike Stump11289f42009-09-09 15:08:12 +00002363/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002364/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002365QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002366 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002367 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002368 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002369 assert((EltTy->isDependentType() ||
2370 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002371 "Constant array of VLAs is illegal!");
2372
Chris Lattnere2df3f92009-05-13 04:12:56 +00002373 // Convert the array size into a canonical width matching the pointer size for
2374 // the target.
2375 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002376 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002377 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002378
Chris Lattner23b7eb62007-06-15 23:05:46 +00002379 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002380 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002381
Chris Lattner36f8e652007-01-27 08:31:04 +00002382 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002383 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002384 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002385 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002386
John McCall33ddac02011-01-19 10:06:00 +00002387 // If the element type isn't canonical or has qualifiers, this won't
2388 // be a canonical type either, so fill in the canonical type field.
2389 QualType Canon;
2390 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2391 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002392 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002393 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002394 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002395
Chris Lattner36f8e652007-01-27 08:31:04 +00002396 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002397 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002398 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002399 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002400 }
Mike Stump11289f42009-09-09 15:08:12 +00002401
John McCall90d1c2d2009-09-24 23:30:46 +00002402 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002403 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002404 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002405 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002406 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002407}
2408
John McCall06549462011-01-18 08:40:38 +00002409/// getVariableArrayDecayedType - Turns the given type, which may be
2410/// variably-modified, into the corresponding type with all the known
2411/// sizes replaced with [*].
2412QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2413 // Vastly most common case.
2414 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002415
John McCall06549462011-01-18 08:40:38 +00002416 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002417
John McCall06549462011-01-18 08:40:38 +00002418 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002419 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002420 switch (ty->getTypeClass()) {
2421#define TYPE(Class, Base)
2422#define ABSTRACT_TYPE(Class, Base)
2423#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2424#include "clang/AST/TypeNodes.def"
2425 llvm_unreachable("didn't desugar past all non-canonical types?");
2426
2427 // These types should never be variably-modified.
2428 case Type::Builtin:
2429 case Type::Complex:
2430 case Type::Vector:
2431 case Type::ExtVector:
2432 case Type::DependentSizedExtVector:
2433 case Type::ObjCObject:
2434 case Type::ObjCInterface:
2435 case Type::ObjCObjectPointer:
2436 case Type::Record:
2437 case Type::Enum:
2438 case Type::UnresolvedUsing:
2439 case Type::TypeOfExpr:
2440 case Type::TypeOf:
2441 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002442 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002443 case Type::DependentName:
2444 case Type::InjectedClassName:
2445 case Type::TemplateSpecialization:
2446 case Type::DependentTemplateSpecialization:
2447 case Type::TemplateTypeParm:
2448 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002449 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002450 case Type::PackExpansion:
2451 llvm_unreachable("type should never be variably-modified");
2452
2453 // These types can be variably-modified but should never need to
2454 // further decay.
2455 case Type::FunctionNoProto:
2456 case Type::FunctionProto:
2457 case Type::BlockPointer:
2458 case Type::MemberPointer:
2459 return type;
2460
2461 // These types can be variably-modified. All these modifications
2462 // preserve structure except as noted by comments.
2463 // TODO: if we ever care about optimizing VLAs, there are no-op
2464 // optimizations available here.
2465 case Type::Pointer:
2466 result = getPointerType(getVariableArrayDecayedType(
2467 cast<PointerType>(ty)->getPointeeType()));
2468 break;
2469
2470 case Type::LValueReference: {
2471 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2472 result = getLValueReferenceType(
2473 getVariableArrayDecayedType(lv->getPointeeType()),
2474 lv->isSpelledAsLValue());
2475 break;
2476 }
2477
2478 case Type::RValueReference: {
2479 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2480 result = getRValueReferenceType(
2481 getVariableArrayDecayedType(lv->getPointeeType()));
2482 break;
2483 }
2484
Eli Friedman0dfb8892011-10-06 23:00:33 +00002485 case Type::Atomic: {
2486 const AtomicType *at = cast<AtomicType>(ty);
2487 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2488 break;
2489 }
2490
John McCall06549462011-01-18 08:40:38 +00002491 case Type::ConstantArray: {
2492 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2493 result = getConstantArrayType(
2494 getVariableArrayDecayedType(cat->getElementType()),
2495 cat->getSize(),
2496 cat->getSizeModifier(),
2497 cat->getIndexTypeCVRQualifiers());
2498 break;
2499 }
2500
2501 case Type::DependentSizedArray: {
2502 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2503 result = getDependentSizedArrayType(
2504 getVariableArrayDecayedType(dat->getElementType()),
2505 dat->getSizeExpr(),
2506 dat->getSizeModifier(),
2507 dat->getIndexTypeCVRQualifiers(),
2508 dat->getBracketsRange());
2509 break;
2510 }
2511
2512 // Turn incomplete types into [*] types.
2513 case Type::IncompleteArray: {
2514 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2515 result = getVariableArrayType(
2516 getVariableArrayDecayedType(iat->getElementType()),
2517 /*size*/ 0,
2518 ArrayType::Normal,
2519 iat->getIndexTypeCVRQualifiers(),
2520 SourceRange());
2521 break;
2522 }
2523
2524 // Turn VLA types into [*] types.
2525 case Type::VariableArray: {
2526 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2527 result = getVariableArrayType(
2528 getVariableArrayDecayedType(vat->getElementType()),
2529 /*size*/ 0,
2530 ArrayType::Star,
2531 vat->getIndexTypeCVRQualifiers(),
2532 vat->getBracketsRange());
2533 break;
2534 }
2535 }
2536
2537 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002538 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002539}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002540
Steve Naroffcadebd02007-08-30 18:14:25 +00002541/// getVariableArrayType - Returns a non-unique reference to the type for a
2542/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002543QualType ASTContext::getVariableArrayType(QualType EltTy,
2544 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002545 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002546 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002547 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002548 // Since we don't unique expressions, it isn't possible to unique VLA's
2549 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002550 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002551
John McCall33ddac02011-01-19 10:06:00 +00002552 // Be sure to pull qualifiers off the element type.
2553 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2554 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002555 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002556 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002557 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002558 }
2559
John McCall90d1c2d2009-09-24 23:30:46 +00002560 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002561 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002562
2563 VariableArrayTypes.push_back(New);
2564 Types.push_back(New);
2565 return QualType(New, 0);
2566}
2567
Douglas Gregor4619e432008-12-05 23:32:09 +00002568/// getDependentSizedArrayType - Returns a non-unique reference to
2569/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002570/// type.
John McCall33ddac02011-01-19 10:06:00 +00002571QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2572 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002573 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002574 unsigned elementTypeQuals,
2575 SourceRange brackets) const {
2576 assert((!numElements || numElements->isTypeDependent() ||
2577 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002578 "Size must be type- or value-dependent!");
2579
John McCall33ddac02011-01-19 10:06:00 +00002580 // Dependently-sized array types that do not have a specified number
2581 // of elements will have their sizes deduced from a dependent
2582 // initializer. We do no canonicalization here at all, which is okay
2583 // because they can't be used in most locations.
2584 if (!numElements) {
2585 DependentSizedArrayType *newType
2586 = new (*this, TypeAlignment)
2587 DependentSizedArrayType(*this, elementType, QualType(),
2588 numElements, ASM, elementTypeQuals,
2589 brackets);
2590 Types.push_back(newType);
2591 return QualType(newType, 0);
2592 }
2593
2594 // Otherwise, we actually build a new type every time, but we
2595 // also build a canonical type.
2596
2597 SplitQualType canonElementType = getCanonicalType(elementType).split();
2598
2599 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002600 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002601 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002602 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002603 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002604
John McCall33ddac02011-01-19 10:06:00 +00002605 // Look for an existing type with these properties.
2606 DependentSizedArrayType *canonTy =
2607 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002608
John McCall33ddac02011-01-19 10:06:00 +00002609 // If we don't have one, build one.
2610 if (!canonTy) {
2611 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002612 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002613 QualType(), numElements, ASM, elementTypeQuals,
2614 brackets);
2615 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2616 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002617 }
2618
John McCall33ddac02011-01-19 10:06:00 +00002619 // Apply qualifiers from the element type to the array.
2620 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002621 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002622
John McCall33ddac02011-01-19 10:06:00 +00002623 // If we didn't need extra canonicalization for the element type,
2624 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002625 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002626 return canon;
2627
2628 // Otherwise, we need to build a type which follows the spelling
2629 // of the element type.
2630 DependentSizedArrayType *sugaredType
2631 = new (*this, TypeAlignment)
2632 DependentSizedArrayType(*this, elementType, canon, numElements,
2633 ASM, elementTypeQuals, brackets);
2634 Types.push_back(sugaredType);
2635 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002636}
2637
John McCall33ddac02011-01-19 10:06:00 +00002638QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002639 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002640 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002641 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002642 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002643
John McCall33ddac02011-01-19 10:06:00 +00002644 void *insertPos = 0;
2645 if (IncompleteArrayType *iat =
2646 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2647 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002648
2649 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002650 // either, so fill in the canonical type field. We also have to pull
2651 // qualifiers off the element type.
2652 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002653
John McCall33ddac02011-01-19 10:06:00 +00002654 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2655 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002656 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002657 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002658 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002659
2660 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002661 IncompleteArrayType *existing =
2662 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2663 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002664 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002665
John McCall33ddac02011-01-19 10:06:00 +00002666 IncompleteArrayType *newType = new (*this, TypeAlignment)
2667 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002668
John McCall33ddac02011-01-19 10:06:00 +00002669 IncompleteArrayTypes.InsertNode(newType, insertPos);
2670 Types.push_back(newType);
2671 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002672}
2673
Steve Naroff91fcddb2007-07-18 18:00:27 +00002674/// getVectorType - Return the unique reference to a vector type of
2675/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002676QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002677 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002678 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002679
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002680 // Check if we've already instantiated a vector of this type.
2681 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002682 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002683
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002684 void *InsertPos = 0;
2685 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2686 return QualType(VTP, 0);
2687
2688 // If the element type isn't canonical, this won't be a canonical type either,
2689 // so fill in the canonical type field.
2690 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002691 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002692 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002693
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002694 // Get the new insert position for the node we care about.
2695 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002696 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002697 }
John McCall90d1c2d2009-09-24 23:30:46 +00002698 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002699 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002700 VectorTypes.InsertNode(New, InsertPos);
2701 Types.push_back(New);
2702 return QualType(New, 0);
2703}
2704
Nate Begemance4d7fc2008-04-18 23:10:10 +00002705/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002706/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002707QualType
2708ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002709 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002710
Steve Naroff91fcddb2007-07-18 18:00:27 +00002711 // Check if we've already instantiated a vector of this type.
2712 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002713 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002714 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002715 void *InsertPos = 0;
2716 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2717 return QualType(VTP, 0);
2718
2719 // If the element type isn't canonical, this won't be a canonical type either,
2720 // so fill in the canonical type field.
2721 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002722 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002723 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002724
Steve Naroff91fcddb2007-07-18 18:00:27 +00002725 // Get the new insert position for the node we care about.
2726 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002727 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002728 }
John McCall90d1c2d2009-09-24 23:30:46 +00002729 ExtVectorType *New = new (*this, TypeAlignment)
2730 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002731 VectorTypes.InsertNode(New, InsertPos);
2732 Types.push_back(New);
2733 return QualType(New, 0);
2734}
2735
Jay Foad39c79802011-01-12 09:06:06 +00002736QualType
2737ASTContext::getDependentSizedExtVectorType(QualType vecType,
2738 Expr *SizeExpr,
2739 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002740 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002741 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002742 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002743
Douglas Gregor352169a2009-07-31 03:54:25 +00002744 void *InsertPos = 0;
2745 DependentSizedExtVectorType *Canon
2746 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2747 DependentSizedExtVectorType *New;
2748 if (Canon) {
2749 // We already have a canonical version of this array type; use it as
2750 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002751 New = new (*this, TypeAlignment)
2752 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2753 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002754 } else {
2755 QualType CanonVecTy = getCanonicalType(vecType);
2756 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002757 New = new (*this, TypeAlignment)
2758 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2759 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002760
2761 DependentSizedExtVectorType *CanonCheck
2762 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2763 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2764 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002765 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2766 } else {
2767 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2768 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002769 New = new (*this, TypeAlignment)
2770 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002771 }
2772 }
Mike Stump11289f42009-09-09 15:08:12 +00002773
Douglas Gregor758a8692009-06-17 21:51:59 +00002774 Types.push_back(New);
2775 return QualType(New, 0);
2776}
2777
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002778/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002779///
Jay Foad39c79802011-01-12 09:06:06 +00002780QualType
2781ASTContext::getFunctionNoProtoType(QualType ResultTy,
2782 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002783 const CallingConv CallConv = Info.getCC();
2784
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002785 // Unique functions, to guarantee there is only one function of a particular
2786 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002787 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002788 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002789
Chris Lattner47955de2007-01-27 08:37:20 +00002790 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002791 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002792 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002793 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002794
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002795 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002796 if (!ResultTy.isCanonical()) {
2797 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002798
Chris Lattner47955de2007-01-27 08:37:20 +00002799 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002800 FunctionNoProtoType *NewIP =
2801 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002802 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002803 }
Mike Stump11289f42009-09-09 15:08:12 +00002804
Roman Divacky65b88cd2011-03-01 17:40:53 +00002805 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002806 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002807 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002808 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002809 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002810 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002811}
2812
Douglas Gregorcd780372013-01-17 23:36:45 +00002813/// \brief Determine whether \p T is canonical as the result type of a function.
2814static bool isCanonicalResultType(QualType T) {
2815 return T.isCanonical() &&
2816 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2817 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2818}
2819
Jay Foad39c79802011-01-12 09:06:06 +00002820QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002821ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002822 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002823 size_t NumArgs = ArgArray.size();
2824
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002825 // Unique functions, to guarantee there is only one function of a particular
2826 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002827 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002828 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2829 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002830
2831 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002832 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002833 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002834 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002835
2836 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002837 bool isCanonical =
Douglas Gregorcd780372013-01-17 23:36:45 +00002838 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002839 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002840 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002841 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002842 isCanonical = false;
2843
2844 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002845 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002846 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002847 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002848 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002849 CanonicalArgs.reserve(NumArgs);
2850 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002851 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002852
John McCalldb40c7f2010-12-14 08:05:40 +00002853 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002854 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002855 CanonicalEPI.ExceptionSpecType = EST_None;
2856 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002857
Douglas Gregorcd780372013-01-17 23:36:45 +00002858 // Result types do not have ARC lifetime qualifiers.
2859 QualType CanResultTy = getCanonicalType(ResultTy);
2860 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2861 Qualifiers Qs = CanResultTy.getQualifiers();
2862 Qs.removeObjCLifetime();
2863 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2864 }
2865
Jordan Rose5c382722013-03-08 21:51:21 +00002866 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002867
Chris Lattnerfd4de792007-01-27 01:15:32 +00002868 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002869 FunctionProtoType *NewIP =
2870 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002871 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002872 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002873
John McCall31168b02011-06-15 23:02:42 +00002874 // FunctionProtoType objects are allocated with extra bytes after
2875 // them for three variable size arrays at the end:
2876 // - parameter types
2877 // - exception types
2878 // - consumed-arguments flags
2879 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002880 // expression, or information used to resolve the exception
2881 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002882 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002883 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002884 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002885 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002886 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002887 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002888 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002889 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002890 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2891 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002892 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002893 if (EPI.ConsumedParameters)
John McCall31168b02011-06-15 23:02:42 +00002894 Size += NumArgs * sizeof(bool);
2895
John McCalldb40c7f2010-12-14 08:05:40 +00002896 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002897 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00002898 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002899 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002900 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002901 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002902}
Chris Lattneref51c202006-11-10 07:17:23 +00002903
John McCalle78aac42010-03-10 03:28:59 +00002904#ifndef NDEBUG
2905static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2906 if (!isa<CXXRecordDecl>(D)) return false;
2907 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2908 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2909 return true;
2910 if (RD->getDescribedClassTemplate() &&
2911 !isa<ClassTemplateSpecializationDecl>(RD))
2912 return true;
2913 return false;
2914}
2915#endif
2916
2917/// getInjectedClassNameType - Return the unique reference to the
2918/// injected class name type for the specified templated declaration.
2919QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002920 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002921 assert(NeedsInjectedClassNameType(Decl));
2922 if (Decl->TypeForDecl) {
2923 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002924 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002925 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2926 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2927 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2928 } else {
John McCall424cec92011-01-19 06:33:43 +00002929 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002930 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002931 Decl->TypeForDecl = newType;
2932 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002933 }
2934 return QualType(Decl->TypeForDecl, 0);
2935}
2936
Douglas Gregor83a586e2008-04-13 21:07:44 +00002937/// getTypeDeclType - Return the unique reference to the type for the
2938/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002939QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002940 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002941 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002942
Richard Smithdda56e42011-04-15 14:24:37 +00002943 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002944 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002945
John McCall96f0b5f2010-03-10 06:48:02 +00002946 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2947 "Template type parameter types are always available.");
2948
John McCall81e38502010-02-16 03:57:14 +00002949 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00002950 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00002951 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002952 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002953 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00002954 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002955 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002956 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002957 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002958 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2959 Decl->TypeForDecl = newType;
2960 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002961 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002962 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002963
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002964 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002965}
2966
Chris Lattner32d920b2007-01-26 02:01:53 +00002967/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002968/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002969QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002970ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2971 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002972 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002973
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002974 if (Canonical.isNull())
2975 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002976 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002977 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002978 Decl->TypeForDecl = newType;
2979 Types.push_back(newType);
2980 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002981}
2982
Jay Foad39c79802011-01-12 09:06:06 +00002983QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002984 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2985
Douglas Gregorec9fd132012-01-14 16:38:05 +00002986 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002987 if (PrevDecl->TypeForDecl)
2988 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2989
John McCall424cec92011-01-19 06:33:43 +00002990 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2991 Decl->TypeForDecl = newType;
2992 Types.push_back(newType);
2993 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002994}
2995
Jay Foad39c79802011-01-12 09:06:06 +00002996QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002997 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2998
Douglas Gregorec9fd132012-01-14 16:38:05 +00002999 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003000 if (PrevDecl->TypeForDecl)
3001 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3002
John McCall424cec92011-01-19 06:33:43 +00003003 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3004 Decl->TypeForDecl = newType;
3005 Types.push_back(newType);
3006 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003007}
3008
John McCall81904512011-01-06 01:58:22 +00003009QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3010 QualType modifiedType,
3011 QualType equivalentType) {
3012 llvm::FoldingSetNodeID id;
3013 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3014
3015 void *insertPos = 0;
3016 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3017 if (type) return QualType(type, 0);
3018
3019 QualType canon = getCanonicalType(equivalentType);
3020 type = new (*this, TypeAlignment)
3021 AttributedType(canon, attrKind, modifiedType, equivalentType);
3022
3023 Types.push_back(type);
3024 AttributedTypes.InsertNode(type, insertPos);
3025
3026 return QualType(type, 0);
3027}
3028
3029
John McCallcebee162009-10-18 09:09:24 +00003030/// \brief Retrieve a substitution-result type.
3031QualType
3032ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003033 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003034 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003035 && "replacement types must always be canonical");
3036
3037 llvm::FoldingSetNodeID ID;
3038 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3039 void *InsertPos = 0;
3040 SubstTemplateTypeParmType *SubstParm
3041 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3042
3043 if (!SubstParm) {
3044 SubstParm = new (*this, TypeAlignment)
3045 SubstTemplateTypeParmType(Parm, Replacement);
3046 Types.push_back(SubstParm);
3047 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3048 }
3049
3050 return QualType(SubstParm, 0);
3051}
3052
Douglas Gregorada4b792011-01-14 02:55:32 +00003053/// \brief Retrieve a
3054QualType ASTContext::getSubstTemplateTypeParmPackType(
3055 const TemplateTypeParmType *Parm,
3056 const TemplateArgument &ArgPack) {
3057#ifndef NDEBUG
3058 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
3059 PEnd = ArgPack.pack_end();
3060 P != PEnd; ++P) {
3061 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3062 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
3063 }
3064#endif
3065
3066 llvm::FoldingSetNodeID ID;
3067 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3068 void *InsertPos = 0;
3069 if (SubstTemplateTypeParmPackType *SubstParm
3070 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3071 return QualType(SubstParm, 0);
3072
3073 QualType Canon;
3074 if (!Parm->isCanonicalUnqualified()) {
3075 Canon = getCanonicalType(QualType(Parm, 0));
3076 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3077 ArgPack);
3078 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3079 }
3080
3081 SubstTemplateTypeParmPackType *SubstParm
3082 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3083 ArgPack);
3084 Types.push_back(SubstParm);
3085 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3086 return QualType(SubstParm, 0);
3087}
3088
Douglas Gregoreff93e02009-02-05 23:33:38 +00003089/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003090/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003091/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003092QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003093 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003094 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003095 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003096 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003097 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003098 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003099 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3100
3101 if (TypeParm)
3102 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003103
Chandler Carruth08836322011-05-01 00:51:33 +00003104 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003105 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003106 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003107
3108 TemplateTypeParmType *TypeCheck
3109 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3110 assert(!TypeCheck && "Template type parameter canonical type broken");
3111 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003112 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003113 TypeParm = new (*this, TypeAlignment)
3114 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003115
3116 Types.push_back(TypeParm);
3117 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3118
3119 return QualType(TypeParm, 0);
3120}
3121
John McCalle78aac42010-03-10 03:28:59 +00003122TypeSourceInfo *
3123ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3124 SourceLocation NameLoc,
3125 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003126 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003127 assert(!Name.getAsDependentTemplateName() &&
3128 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003129 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003130
3131 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003132 TemplateSpecializationTypeLoc TL =
3133 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003134 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003135 TL.setTemplateNameLoc(NameLoc);
3136 TL.setLAngleLoc(Args.getLAngleLoc());
3137 TL.setRAngleLoc(Args.getRAngleLoc());
3138 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3139 TL.setArgLocInfo(i, Args[i].getLocInfo());
3140 return DI;
3141}
3142
Mike Stump11289f42009-09-09 15:08:12 +00003143QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003144ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003145 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003146 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003147 assert(!Template.getAsDependentTemplateName() &&
3148 "No dependent template names here!");
3149
John McCall6b51f282009-11-23 01:53:49 +00003150 unsigned NumArgs = Args.size();
3151
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003152 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003153 ArgVec.reserve(NumArgs);
3154 for (unsigned i = 0; i != NumArgs; ++i)
3155 ArgVec.push_back(Args[i].getArgument());
3156
John McCall2408e322010-04-27 00:57:59 +00003157 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003158 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003159}
3160
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003161#ifndef NDEBUG
3162static bool hasAnyPackExpansions(const TemplateArgument *Args,
3163 unsigned NumArgs) {
3164 for (unsigned I = 0; I != NumArgs; ++I)
3165 if (Args[I].isPackExpansion())
3166 return true;
3167
3168 return true;
3169}
3170#endif
3171
John McCall0ad16662009-10-29 08:12:44 +00003172QualType
3173ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003174 const TemplateArgument *Args,
3175 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003176 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003177 assert(!Template.getAsDependentTemplateName() &&
3178 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003179 // Look through qualified template names.
3180 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3181 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003182
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003183 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003184 Template.getAsTemplateDecl() &&
3185 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003186 QualType CanonType;
3187 if (!Underlying.isNull())
3188 CanonType = getCanonicalType(Underlying);
3189 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003190 // We can get here with an alias template when the specialization contains
3191 // a pack expansion that does not match up with a parameter pack.
3192 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3193 "Caller must compute aliased type");
3194 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003195 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3196 NumArgs);
3197 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003198
Douglas Gregora8e02e72009-07-28 23:00:59 +00003199 // Allocate the (non-canonical) template specialization type, but don't
3200 // try to unique it: these types typically have location information that
3201 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003202 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3203 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003204 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003205 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003206 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003207 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3208 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003209
Douglas Gregor8bf42052009-02-09 18:46:07 +00003210 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003211 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003212}
3213
Mike Stump11289f42009-09-09 15:08:12 +00003214QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003215ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3216 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003217 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003218 assert(!Template.getAsDependentTemplateName() &&
3219 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003220
Douglas Gregore29139c2011-03-03 17:04:51 +00003221 // Look through qualified template names.
3222 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3223 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003224
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003225 // Build the canonical template specialization type.
3226 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003227 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003228 CanonArgs.reserve(NumArgs);
3229 for (unsigned I = 0; I != NumArgs; ++I)
3230 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3231
3232 // Determine whether this canonical template specialization type already
3233 // exists.
3234 llvm::FoldingSetNodeID ID;
3235 TemplateSpecializationType::Profile(ID, CanonTemplate,
3236 CanonArgs.data(), NumArgs, *this);
3237
3238 void *InsertPos = 0;
3239 TemplateSpecializationType *Spec
3240 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3241
3242 if (!Spec) {
3243 // Allocate a new canonical template specialization type.
3244 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3245 sizeof(TemplateArgument) * NumArgs),
3246 TypeAlignment);
3247 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3248 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003249 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003250 Types.push_back(Spec);
3251 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3252 }
3253
3254 assert(Spec->isDependentType() &&
3255 "Non-dependent template-id type must have a canonical type");
3256 return QualType(Spec, 0);
3257}
3258
3259QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003260ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3261 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003262 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003263 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003264 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003265
3266 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003267 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003268 if (T)
3269 return QualType(T, 0);
3270
Douglas Gregorc42075a2010-02-04 18:10:26 +00003271 QualType Canon = NamedType;
3272 if (!Canon.isCanonical()) {
3273 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003274 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3275 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003276 (void)CheckT;
3277 }
3278
Abramo Bagnara6150c882010-05-11 21:36:43 +00003279 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003280 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003281 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003282 return QualType(T, 0);
3283}
3284
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003285QualType
Jay Foad39c79802011-01-12 09:06:06 +00003286ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003287 llvm::FoldingSetNodeID ID;
3288 ParenType::Profile(ID, InnerType);
3289
3290 void *InsertPos = 0;
3291 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3292 if (T)
3293 return QualType(T, 0);
3294
3295 QualType Canon = InnerType;
3296 if (!Canon.isCanonical()) {
3297 Canon = getCanonicalType(InnerType);
3298 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3299 assert(!CheckT && "Paren canonical type broken");
3300 (void)CheckT;
3301 }
3302
3303 T = new (*this) ParenType(InnerType, Canon);
3304 Types.push_back(T);
3305 ParenTypes.InsertNode(T, InsertPos);
3306 return QualType(T, 0);
3307}
3308
Douglas Gregor02085352010-03-31 20:19:30 +00003309QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3310 NestedNameSpecifier *NNS,
3311 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003312 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003313 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3314
3315 if (Canon.isNull()) {
3316 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003317 ElaboratedTypeKeyword CanonKeyword = Keyword;
3318 if (Keyword == ETK_None)
3319 CanonKeyword = ETK_Typename;
3320
3321 if (CanonNNS != NNS || CanonKeyword != Keyword)
3322 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003323 }
3324
3325 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003326 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003327
3328 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003329 DependentNameType *T
3330 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003331 if (T)
3332 return QualType(T, 0);
3333
Douglas Gregor02085352010-03-31 20:19:30 +00003334 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003335 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003336 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003337 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003338}
3339
Mike Stump11289f42009-09-09 15:08:12 +00003340QualType
John McCallc392f372010-06-11 00:33:02 +00003341ASTContext::getDependentTemplateSpecializationType(
3342 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003343 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003344 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003345 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003346 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003347 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003348 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3349 ArgCopy.push_back(Args[I].getArgument());
3350 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3351 ArgCopy.size(),
3352 ArgCopy.data());
3353}
3354
3355QualType
3356ASTContext::getDependentTemplateSpecializationType(
3357 ElaboratedTypeKeyword Keyword,
3358 NestedNameSpecifier *NNS,
3359 const IdentifierInfo *Name,
3360 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003361 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003362 assert((!NNS || NNS->isDependent()) &&
3363 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003364
Douglas Gregorc42075a2010-02-04 18:10:26 +00003365 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003366 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3367 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003368
3369 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00003370 DependentTemplateSpecializationType *T
3371 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003372 if (T)
3373 return QualType(T, 0);
3374
John McCallc392f372010-06-11 00:33:02 +00003375 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003376
John McCallc392f372010-06-11 00:33:02 +00003377 ElaboratedTypeKeyword CanonKeyword = Keyword;
3378 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3379
3380 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003381 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003382 for (unsigned I = 0; I != NumArgs; ++I) {
3383 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3384 if (!CanonArgs[I].structurallyEquals(Args[I]))
3385 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003386 }
3387
John McCallc392f372010-06-11 00:33:02 +00003388 QualType Canon;
3389 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3390 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3391 Name, NumArgs,
3392 CanonArgs.data());
3393
3394 // Find the insert position again.
3395 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3396 }
3397
3398 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3399 sizeof(TemplateArgument) * NumArgs),
3400 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003401 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003402 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003403 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003404 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003405 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003406}
3407
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003408QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003409 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003410 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003411 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003412
3413 assert(Pattern->containsUnexpandedParameterPack() &&
3414 "Pack expansions must expand one or more parameter packs");
3415 void *InsertPos = 0;
3416 PackExpansionType *T
3417 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3418 if (T)
3419 return QualType(T, 0);
3420
3421 QualType Canon;
3422 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003423 Canon = getCanonicalType(Pattern);
3424 // The canonical type might not contain an unexpanded parameter pack, if it
3425 // contains an alias template specialization which ignores one of its
3426 // parameters.
3427 if (Canon->containsUnexpandedParameterPack()) {
3428 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003429
Richard Smith68eea502012-07-16 00:20:35 +00003430 // Find the insert position again, in case we inserted an element into
3431 // PackExpansionTypes and invalidated our insert position.
3432 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3433 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003434 }
3435
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003436 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003437 Types.push_back(T);
3438 PackExpansionTypes.InsertNode(T, InsertPos);
3439 return QualType(T, 0);
3440}
3441
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003442/// CmpProtocolNames - Comparison predicate for sorting protocols
3443/// alphabetically.
3444static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3445 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003446 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003447}
3448
John McCall8b07ec22010-05-15 11:32:37 +00003449static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003450 unsigned NumProtocols) {
3451 if (NumProtocols == 0) return true;
3452
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003453 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3454 return false;
3455
John McCallfc93cf92009-10-22 22:37:11 +00003456 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003457 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3458 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003459 return false;
3460 return true;
3461}
3462
3463static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003464 unsigned &NumProtocols) {
3465 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003466
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003467 // Sort protocols, keyed by name.
3468 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3469
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003470 // Canonicalize.
3471 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3472 Protocols[I] = Protocols[I]->getCanonicalDecl();
3473
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003474 // Remove duplicates.
3475 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3476 NumProtocols = ProtocolsEnd-Protocols;
3477}
3478
John McCall8b07ec22010-05-15 11:32:37 +00003479QualType ASTContext::getObjCObjectType(QualType BaseType,
3480 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003481 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003482 // If the base type is an interface and there aren't any protocols
3483 // to add, then the interface type will do just fine.
3484 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3485 return BaseType;
3486
3487 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003488 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003489 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003490 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003491 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3492 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003493
John McCall8b07ec22010-05-15 11:32:37 +00003494 // Build the canonical type, which has the canonical base type and
3495 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003496 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003497 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3498 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3499 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003500 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003501 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003502 unsigned UniqueCount = NumProtocols;
3503
John McCallfc93cf92009-10-22 22:37:11 +00003504 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003505 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3506 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003507 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003508 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3509 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003510 }
3511
3512 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003513 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3514 }
3515
3516 unsigned Size = sizeof(ObjCObjectTypeImpl);
3517 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3518 void *Mem = Allocate(Size, TypeAlignment);
3519 ObjCObjectTypeImpl *T =
3520 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3521
3522 Types.push_back(T);
3523 ObjCObjectTypes.InsertNode(T, InsertPos);
3524 return QualType(T, 0);
3525}
3526
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003527/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3528/// protocol list adopt all protocols in QT's qualified-id protocol
3529/// list.
3530bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3531 ObjCInterfaceDecl *IC) {
3532 if (!QT->isObjCQualifiedIdType())
3533 return false;
3534
3535 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3536 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00003537 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003538 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
Aaron Ballman83731462014-03-17 16:14:00 +00003563 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003564 // If both the right and left sides have qualifiers.
3565 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00003566 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003567 // return 'true' if '*PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00003568 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003569 break;
3570 }
3571 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003572 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003573 }
3574 return true;
3575}
3576
John McCall8b07ec22010-05-15 11:32:37 +00003577/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3578/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003579QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003580 llvm::FoldingSetNodeID ID;
3581 ObjCObjectPointerType::Profile(ID, ObjectT);
3582
3583 void *InsertPos = 0;
3584 if (ObjCObjectPointerType *QT =
3585 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3586 return QualType(QT, 0);
3587
3588 // Find the canonical object type.
3589 QualType Canonical;
3590 if (!ObjectT.isCanonical()) {
3591 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3592
3593 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003594 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3595 }
3596
Douglas Gregorf85bee62010-02-08 22:59:26 +00003597 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003598 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3599 ObjCObjectPointerType *QType =
3600 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003601
Steve Narofffb4330f2009-06-17 22:40:22 +00003602 Types.push_back(QType);
3603 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003604 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003605}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003606
Douglas Gregor1c283312010-08-11 12:19:30 +00003607/// getObjCInterfaceType - Return the unique reference to the type for the
3608/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003609QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3610 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003611 if (Decl->TypeForDecl)
3612 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003613
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003614 if (PrevDecl) {
3615 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3616 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3617 return QualType(PrevDecl->TypeForDecl, 0);
3618 }
3619
Douglas Gregor7671e532011-12-16 16:34:57 +00003620 // Prefer the definition, if there is one.
3621 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3622 Decl = Def;
3623
Douglas Gregor1c283312010-08-11 12:19:30 +00003624 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3625 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3626 Decl->TypeForDecl = T;
3627 Types.push_back(T);
3628 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003629}
3630
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003631/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3632/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003633/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003634/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003635/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003636QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003637 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003638 if (tofExpr->isTypeDependent()) {
3639 llvm::FoldingSetNodeID ID;
3640 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003641
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003642 void *InsertPos = 0;
3643 DependentTypeOfExprType *Canon
3644 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3645 if (Canon) {
3646 // We already have a "canonical" version of an identical, dependent
3647 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003648 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003649 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003650 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003651 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003652 Canon
3653 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003654 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3655 toe = Canon;
3656 }
3657 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003658 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003659 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003660 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003661 Types.push_back(toe);
3662 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003663}
3664
Steve Naroffa773cd52007-08-01 18:02:17 +00003665/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3666/// TypeOfType AST's. The only motivation to unique these nodes would be
3667/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003668/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003669/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003670QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003671 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003672 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003673 Types.push_back(tot);
3674 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003675}
3676
Anders Carlssonad6bd352009-06-24 21:24:56 +00003677
Anders Carlsson81df7b82009-06-24 19:06:50 +00003678/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3679/// DecltypeType AST's. The only motivation to unique these nodes would be
3680/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003681/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003682/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003683QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003684 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003685
3686 // C++0x [temp.type]p2:
3687 // If an expression e involves a template parameter, decltype(e) denotes a
3688 // unique dependent type. Two such decltype-specifiers refer to the same
3689 // type only if their expressions are equivalent (14.5.6.1).
3690 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003691 llvm::FoldingSetNodeID ID;
3692 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003693
Douglas Gregora21f6c32009-07-30 23:36:40 +00003694 void *InsertPos = 0;
3695 DependentDecltypeType *Canon
3696 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3697 if (Canon) {
3698 // We already have a "canonical" version of an equivalent, dependent
3699 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003700 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003701 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003702 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003703 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003704 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003705 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3706 dt = Canon;
3707 }
3708 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003709 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3710 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003711 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003712 Types.push_back(dt);
3713 return QualType(dt, 0);
3714}
3715
Alexis Hunte852b102011-05-24 22:41:36 +00003716/// getUnaryTransformationType - We don't unique these, since the memory
3717/// savings are minimal and these are rare.
3718QualType ASTContext::getUnaryTransformType(QualType BaseType,
3719 QualType UnderlyingType,
3720 UnaryTransformType::UTTKind Kind)
3721 const {
3722 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003723 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3724 Kind,
3725 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003726 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003727 Types.push_back(Ty);
3728 return QualType(Ty, 0);
3729}
3730
Richard Smith2a7d4812013-05-04 07:00:32 +00003731/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3732/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3733/// canonical deduced-but-dependent 'auto' type.
3734QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003735 bool IsDependent) const {
3736 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003737 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003738
Richard Smith2a7d4812013-05-04 07:00:32 +00003739 // Look in the folding set for an existing type.
Richard Smithb2bc2e62011-02-21 20:05:19 +00003740 void *InsertPos = 0;
Richard Smith2a7d4812013-05-04 07:00:32 +00003741 llvm::FoldingSetNodeID ID;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003742 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003743 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3744 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003745
Richard Smith74aeef52013-04-26 16:15:35 +00003746 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003747 IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003748 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003749 Types.push_back(AT);
3750 if (InsertPos)
3751 AutoTypes.InsertNode(AT, InsertPos);
3752 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003753}
3754
Eli Friedman0dfb8892011-10-06 23:00:33 +00003755/// getAtomicType - Return the uniqued reference to the atomic type for
3756/// the given value type.
3757QualType ASTContext::getAtomicType(QualType T) const {
3758 // Unique pointers, to guarantee there is only one pointer of a particular
3759 // structure.
3760 llvm::FoldingSetNodeID ID;
3761 AtomicType::Profile(ID, T);
3762
3763 void *InsertPos = 0;
3764 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3765 return QualType(AT, 0);
3766
3767 // If the atomic value type isn't canonical, this won't be a canonical type
3768 // either, so fill in the canonical type field.
3769 QualType Canonical;
3770 if (!T.isCanonical()) {
3771 Canonical = getAtomicType(getCanonicalType(T));
3772
3773 // Get the new insert position for the node we care about.
3774 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3775 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3776 }
3777 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3778 Types.push_back(New);
3779 AtomicTypes.InsertNode(New, InsertPos);
3780 return QualType(New, 0);
3781}
3782
Richard Smith02e85f32011-04-14 22:09:26 +00003783/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3784QualType ASTContext::getAutoDeductType() const {
3785 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00003786 AutoDeductTy = QualType(
3787 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003788 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00003789 0);
Richard Smith02e85f32011-04-14 22:09:26 +00003790 return AutoDeductTy;
3791}
3792
3793/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3794QualType ASTContext::getAutoRRefDeductType() const {
3795 if (AutoRRefDeductTy.isNull())
3796 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3797 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3798 return AutoRRefDeductTy;
3799}
3800
Chris Lattnerfb072462007-01-23 05:45:31 +00003801/// getTagDeclType - Return the unique reference to the type for the
3802/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003803QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003804 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003805 // FIXME: What is the design on getTagDeclType when it requires casting
3806 // away const? mutable?
3807 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003808}
3809
Mike Stump11289f42009-09-09 15:08:12 +00003810/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3811/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3812/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003813CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003814 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003815}
Chris Lattnerfb072462007-01-23 05:45:31 +00003816
Hans Wennborg27541db2011-10-27 08:29:09 +00003817/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3818CanQualType ASTContext::getIntMaxType() const {
3819 return getFromTargetType(Target->getIntMaxType());
3820}
3821
3822/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3823CanQualType ASTContext::getUIntMaxType() const {
3824 return getFromTargetType(Target->getUIntMaxType());
3825}
3826
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003827/// getSignedWCharType - Return the type of "signed wchar_t".
3828/// Used when in C++, as a GCC extension.
3829QualType ASTContext::getSignedWCharType() const {
3830 // FIXME: derive from "Target" ?
3831 return WCharTy;
3832}
3833
3834/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3835/// Used when in C++, as a GCC extension.
3836QualType ASTContext::getUnsignedWCharType() const {
3837 // FIXME: derive from "Target" ?
3838 return UnsignedIntTy;
3839}
3840
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00003841QualType ASTContext::getIntPtrType() const {
3842 return getFromTargetType(Target->getIntPtrType());
3843}
3844
3845QualType ASTContext::getUIntPtrType() const {
3846 return getCorrespondingUnsignedType(getIntPtrType());
3847}
3848
Hans Wennborg27541db2011-10-27 08:29:09 +00003849/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003850/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3851QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003852 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003853}
3854
Eli Friedman4e91899e2012-11-27 02:58:24 +00003855/// \brief Return the unique type for "pid_t" defined in
3856/// <sys/types.h>. We need this to compute the correct type for vfork().
3857QualType ASTContext::getProcessIDType() const {
3858 return getFromTargetType(Target->getProcessIDType());
3859}
3860
Chris Lattnera21ad802008-04-02 05:18:44 +00003861//===----------------------------------------------------------------------===//
3862// Type Operators
3863//===----------------------------------------------------------------------===//
3864
Jay Foad39c79802011-01-12 09:06:06 +00003865CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003866 // Push qualifiers into arrays, and then discard any remaining
3867 // qualifiers.
3868 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003869 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003870 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003871 QualType Result;
3872 if (isa<ArrayType>(Ty)) {
3873 Result = getArrayDecayedType(QualType(Ty,0));
3874 } else if (isa<FunctionType>(Ty)) {
3875 Result = getPointerType(QualType(Ty, 0));
3876 } else {
3877 Result = QualType(Ty, 0);
3878 }
3879
3880 return CanQualType::CreateUnsafe(Result);
3881}
3882
John McCall6c9dd522011-01-18 07:41:22 +00003883QualType ASTContext::getUnqualifiedArrayType(QualType type,
3884 Qualifiers &quals) {
3885 SplitQualType splitType = type.getSplitUnqualifiedType();
3886
3887 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3888 // the unqualified desugared type and then drops it on the floor.
3889 // We then have to strip that sugar back off with
3890 // getUnqualifiedDesugaredType(), which is silly.
3891 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003892 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003893
3894 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003895 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003896 quals = splitType.Quals;
3897 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003898 }
3899
John McCall6c9dd522011-01-18 07:41:22 +00003900 // Otherwise, recurse on the array's element type.
3901 QualType elementType = AT->getElementType();
3902 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3903
3904 // If that didn't change the element type, AT has no qualifiers, so we
3905 // can just use the results in splitType.
3906 if (elementType == unqualElementType) {
3907 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003908 quals = splitType.Quals;
3909 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003910 }
3911
3912 // Otherwise, add in the qualifiers from the outermost type, then
3913 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003914 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003915
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003916 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003917 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003918 CAT->getSizeModifier(), 0);
3919 }
3920
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003921 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003922 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003923 }
3924
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003925 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003926 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003927 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003928 VAT->getSizeModifier(),
3929 VAT->getIndexTypeCVRQualifiers(),
3930 VAT->getBracketsRange());
3931 }
3932
3933 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003934 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003935 DSAT->getSizeModifier(), 0,
3936 SourceRange());
3937}
3938
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003939/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3940/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3941/// they point to and return true. If T1 and T2 aren't pointer types
3942/// or pointer-to-member types, or if they are not similar at this
3943/// level, returns false and leaves T1 and T2 unchanged. Top-level
3944/// qualifiers on T1 and T2 are ignored. This function will typically
3945/// be called in a loop that successively "unwraps" pointer and
3946/// pointer-to-member types to compare them at each level.
3947bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3948 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3949 *T2PtrType = T2->getAs<PointerType>();
3950 if (T1PtrType && T2PtrType) {
3951 T1 = T1PtrType->getPointeeType();
3952 T2 = T2PtrType->getPointeeType();
3953 return true;
3954 }
3955
3956 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3957 *T2MPType = T2->getAs<MemberPointerType>();
3958 if (T1MPType && T2MPType &&
3959 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3960 QualType(T2MPType->getClass(), 0))) {
3961 T1 = T1MPType->getPointeeType();
3962 T2 = T2MPType->getPointeeType();
3963 return true;
3964 }
3965
David Blaikiebbafb8a2012-03-11 07:00:24 +00003966 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003967 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3968 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3969 if (T1OPType && T2OPType) {
3970 T1 = T1OPType->getPointeeType();
3971 T2 = T2OPType->getPointeeType();
3972 return true;
3973 }
3974 }
3975
3976 // FIXME: Block pointers, too?
3977
3978 return false;
3979}
3980
Jay Foad39c79802011-01-12 09:06:06 +00003981DeclarationNameInfo
3982ASTContext::getNameForTemplate(TemplateName Name,
3983 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003984 switch (Name.getKind()) {
3985 case TemplateName::QualifiedTemplate:
3986 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003987 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003988 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3989 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003990
John McCalld9dfe3a2011-06-30 08:33:18 +00003991 case TemplateName::OverloadedTemplate: {
3992 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3993 // DNInfo work in progress: CHECKME: what about DNLoc?
3994 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3995 }
3996
3997 case TemplateName::DependentTemplate: {
3998 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003999 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004000 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004001 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4002 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004003 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004004 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4005 // DNInfo work in progress: FIXME: source locations?
4006 DeclarationNameLoc DNLoc;
4007 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4008 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4009 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004010 }
4011 }
4012
John McCalld9dfe3a2011-06-30 08:33:18 +00004013 case TemplateName::SubstTemplateTemplateParm: {
4014 SubstTemplateTemplateParmStorage *subst
4015 = Name.getAsSubstTemplateTemplateParm();
4016 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4017 NameLoc);
4018 }
4019
4020 case TemplateName::SubstTemplateTemplateParmPack: {
4021 SubstTemplateTemplateParmPackStorage *subst
4022 = Name.getAsSubstTemplateTemplateParmPack();
4023 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4024 NameLoc);
4025 }
4026 }
4027
4028 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004029}
4030
Jay Foad39c79802011-01-12 09:06:06 +00004031TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004032 switch (Name.getKind()) {
4033 case TemplateName::QualifiedTemplate:
4034 case TemplateName::Template: {
4035 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004036 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004037 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004038 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4039
4040 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004041 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004042 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004043
John McCalld9dfe3a2011-06-30 08:33:18 +00004044 case TemplateName::OverloadedTemplate:
4045 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004046
John McCalld9dfe3a2011-06-30 08:33:18 +00004047 case TemplateName::DependentTemplate: {
4048 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4049 assert(DTN && "Non-dependent template names must refer to template decls.");
4050 return DTN->CanonicalTemplateName;
4051 }
4052
4053 case TemplateName::SubstTemplateTemplateParm: {
4054 SubstTemplateTemplateParmStorage *subst
4055 = Name.getAsSubstTemplateTemplateParm();
4056 return getCanonicalTemplateName(subst->getReplacement());
4057 }
4058
4059 case TemplateName::SubstTemplateTemplateParmPack: {
4060 SubstTemplateTemplateParmPackStorage *subst
4061 = Name.getAsSubstTemplateTemplateParmPack();
4062 TemplateTemplateParmDecl *canonParameter
4063 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4064 TemplateArgument canonArgPack
4065 = getCanonicalTemplateArgument(subst->getArgumentPack());
4066 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4067 }
4068 }
4069
4070 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004071}
4072
Douglas Gregoradee3e32009-11-11 23:06:43 +00004073bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4074 X = getCanonicalTemplateName(X);
4075 Y = getCanonicalTemplateName(Y);
4076 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4077}
4078
Mike Stump11289f42009-09-09 15:08:12 +00004079TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004080ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004081 switch (Arg.getKind()) {
4082 case TemplateArgument::Null:
4083 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004084
Douglas Gregora8e02e72009-07-28 23:00:59 +00004085 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004086 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004087
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004088 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004089 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4090 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004091 }
Mike Stump11289f42009-09-09 15:08:12 +00004092
Eli Friedmanb826a002012-09-26 02:36:12 +00004093 case TemplateArgument::NullPtr:
4094 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4095 /*isNullPtr*/true);
4096
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004097 case TemplateArgument::Template:
4098 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004099
4100 case TemplateArgument::TemplateExpansion:
4101 return TemplateArgument(getCanonicalTemplateName(
4102 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004103 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004104
Douglas Gregora8e02e72009-07-28 23:00:59 +00004105 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004106 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004107
Douglas Gregora8e02e72009-07-28 23:00:59 +00004108 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004109 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004110
Douglas Gregora8e02e72009-07-28 23:00:59 +00004111 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004112 if (Arg.pack_size() == 0)
4113 return Arg;
4114
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004115 TemplateArgument *CanonArgs
4116 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004117 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004118 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004119 AEnd = Arg.pack_end();
4120 A != AEnd; (void)++A, ++Idx)
4121 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004122
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004123 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00004124 }
4125 }
4126
4127 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004128 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004129}
4130
Douglas Gregor333489b2009-03-27 23:10:48 +00004131NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004132ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004133 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00004134 return 0;
4135
4136 switch (NNS->getKind()) {
4137 case NestedNameSpecifier::Identifier:
4138 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004139 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004140 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4141 NNS->getAsIdentifier());
4142
4143 case NestedNameSpecifier::Namespace:
4144 // A namespace is canonical; build a nested-name-specifier with
4145 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004146 return NestedNameSpecifier::Create(*this, 0,
4147 NNS->getAsNamespace()->getOriginalNamespace());
4148
4149 case NestedNameSpecifier::NamespaceAlias:
4150 // A namespace is canonical; build a nested-name-specifier with
4151 // this namespace and no prefix.
4152 return NestedNameSpecifier::Create(*this, 0,
4153 NNS->getAsNamespaceAlias()->getNamespace()
4154 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004155
4156 case NestedNameSpecifier::TypeSpec:
4157 case NestedNameSpecifier::TypeSpecWithTemplate: {
4158 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004159
4160 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4161 // break it apart into its prefix and identifier, then reconsititute those
4162 // as the canonical nested-name-specifier. This is required to canonicalize
4163 // a dependent nested-name-specifier involving typedefs of dependent-name
4164 // types, e.g.,
4165 // typedef typename T::type T1;
4166 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004167 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4168 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004169 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004170
Eli Friedman5358a0a2012-03-03 04:09:56 +00004171 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4172 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4173 // first place?
John McCall33ddac02011-01-19 10:06:00 +00004174 return NestedNameSpecifier::Create(*this, 0, false,
4175 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004176 }
4177
4178 case NestedNameSpecifier::Global:
4179 // The global specifier is canonical and unique.
4180 return NNS;
4181 }
4182
David Blaikie8a40f702012-01-17 06:56:22 +00004183 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004184}
4185
Chris Lattner7adf0762008-08-04 07:31:14 +00004186
Jay Foad39c79802011-01-12 09:06:06 +00004187const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004188 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004189 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004190 // Handle the common positive case fast.
4191 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4192 return AT;
4193 }
Mike Stump11289f42009-09-09 15:08:12 +00004194
John McCall8ccfcb52009-09-24 19:53:00 +00004195 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004196 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00004197 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004198
John McCall8ccfcb52009-09-24 19:53:00 +00004199 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004200 // implements C99 6.7.3p8: "If the specification of an array type includes
4201 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004202
Chris Lattner7adf0762008-08-04 07:31:14 +00004203 // If we get here, we either have type qualifiers on the type, or we have
4204 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004205 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004206
John McCall33ddac02011-01-19 10:06:00 +00004207 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004208 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004209
Chris Lattner7adf0762008-08-04 07:31:14 +00004210 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004211 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00004212 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004213 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004214
Chris Lattner7adf0762008-08-04 07:31:14 +00004215 // Otherwise, we have an array and we have qualifiers on it. Push the
4216 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004217 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004218
Chris Lattner7adf0762008-08-04 07:31:14 +00004219 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4220 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4221 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004222 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004223 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4224 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4225 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004226 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004227
Mike Stump11289f42009-09-09 15:08:12 +00004228 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004229 = dyn_cast<DependentSizedArrayType>(ATy))
4230 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004231 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004232 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004233 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004234 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004235 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004236
Chris Lattner7adf0762008-08-04 07:31:14 +00004237 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004238 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004239 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004240 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004241 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004242 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004243}
4244
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004245QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004246 if (T->isArrayType() || T->isFunctionType())
4247 return getDecayedType(T);
4248 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004249}
4250
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004251QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004252 T = getVariableArrayDecayedType(T);
4253 T = getAdjustedParameterType(T);
4254 return T.getUnqualifiedType();
4255}
4256
Chris Lattnera21ad802008-04-02 05:18:44 +00004257/// getArrayDecayedType - Return the properly qualified result of decaying the
4258/// specified array type to a pointer. This operation is non-trivial when
4259/// handling typedefs etc. The canonical type of "T" must be an array type,
4260/// this returns a pointer to a properly qualified element of the array.
4261///
4262/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004263QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004264 // Get the element type with 'getAsArrayType' so that we don't lose any
4265 // typedefs in the element type of the array. This also handles propagation
4266 // of type qualifiers from the array type into the element type if present
4267 // (C99 6.7.3p8).
4268 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4269 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004270
Chris Lattner7adf0762008-08-04 07:31:14 +00004271 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004272
4273 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004274 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004275}
4276
John McCall33ddac02011-01-19 10:06:00 +00004277QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4278 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004279}
4280
John McCall33ddac02011-01-19 10:06:00 +00004281QualType ASTContext::getBaseElementType(QualType type) const {
4282 Qualifiers qs;
4283 while (true) {
4284 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004285 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004286 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004287
John McCall33ddac02011-01-19 10:06:00 +00004288 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004289 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004290 }
Mike Stump11289f42009-09-09 15:08:12 +00004291
John McCall33ddac02011-01-19 10:06:00 +00004292 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004293}
4294
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004295/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004296uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004297ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4298 uint64_t ElementCount = 1;
4299 do {
4300 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004301 CA = dyn_cast_or_null<ConstantArrayType>(
4302 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004303 } while (CA);
4304 return ElementCount;
4305}
4306
Steve Naroff0af91202007-04-27 21:51:21 +00004307/// getFloatingRank - Return a relative rank for floating point types.
4308/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004309static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004310 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004311 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004312
John McCall9dd450b2009-09-21 23:43:11 +00004313 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4314 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004315 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004316 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004317 case BuiltinType::Float: return FloatRank;
4318 case BuiltinType::Double: return DoubleRank;
4319 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004320 }
4321}
4322
Mike Stump11289f42009-09-09 15:08:12 +00004323/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4324/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004325/// 'typeDomain' is a real floating point or complex type.
4326/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004327QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4328 QualType Domain) const {
4329 FloatingRank EltRank = getFloatingRank(Size);
4330 if (Domain->isComplexType()) {
4331 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004332 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004333 case FloatRank: return FloatComplexTy;
4334 case DoubleRank: return DoubleComplexTy;
4335 case LongDoubleRank: return LongDoubleComplexTy;
4336 }
Steve Naroff0af91202007-04-27 21:51:21 +00004337 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004338
4339 assert(Domain->isRealFloatingType() && "Unknown domain!");
4340 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004341 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004342 case FloatRank: return FloatTy;
4343 case DoubleRank: return DoubleTy;
4344 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004345 }
David Blaikief47fa302012-01-17 02:30:50 +00004346 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004347}
4348
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004349/// getFloatingTypeOrder - Compare the rank of the two specified floating
4350/// point types, ignoring the domain of the type (i.e. 'double' ==
4351/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004352/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004353int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004354 FloatingRank LHSR = getFloatingRank(LHS);
4355 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004356
Chris Lattnerb90739d2008-04-06 23:38:49 +00004357 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004358 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004359 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004360 return 1;
4361 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004362}
4363
Chris Lattner76a00cf2008-04-06 22:59:24 +00004364/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4365/// routine will assert if passed a built-in type that isn't an integer or enum,
4366/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004367unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004368 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004369
Chris Lattner76a00cf2008-04-06 22:59:24 +00004370 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004371 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004372 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004373 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004374 case BuiltinType::Char_S:
4375 case BuiltinType::Char_U:
4376 case BuiltinType::SChar:
4377 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004378 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004379 case BuiltinType::Short:
4380 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004381 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004382 case BuiltinType::Int:
4383 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004384 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004385 case BuiltinType::Long:
4386 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004387 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004388 case BuiltinType::LongLong:
4389 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004390 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004391 case BuiltinType::Int128:
4392 case BuiltinType::UInt128:
4393 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004394 }
4395}
4396
Eli Friedman629ffb92009-08-20 04:21:42 +00004397/// \brief Whether this is a promotable bitfield reference according
4398/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4399///
4400/// \returns the type this bit-field will promote to, or NULL if no
4401/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004402QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004403 if (E->isTypeDependent() || E->isValueDependent())
4404 return QualType();
4405
John McCalld25db7e2013-05-06 21:39:12 +00004406 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004407 if (!Field)
4408 return QualType();
4409
4410 QualType FT = Field->getType();
4411
Richard Smithcaf33902011-10-10 18:28:20 +00004412 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004413 uint64_t IntSize = getTypeSize(IntTy);
4414 // GCC extension compatibility: if the bit-field size is less than or equal
4415 // to the size of int, it gets promoted no matter what its type is.
4416 // For instance, unsigned long bf : 4 gets promoted to signed int.
4417 if (BitWidth < IntSize)
4418 return IntTy;
4419
4420 if (BitWidth == IntSize)
4421 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4422
4423 // Types bigger than int are not subject to promotions, and therefore act
4424 // like the base type.
4425 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4426 // is ridiculous.
4427 return QualType();
4428}
4429
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004430/// getPromotedIntegerType - Returns the type that Promotable will
4431/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4432/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004433QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004434 assert(!Promotable.isNull());
4435 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004436 if (const EnumType *ET = Promotable->getAs<EnumType>())
4437 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004438
4439 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4440 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4441 // (3.9.1) can be converted to a prvalue of the first of the following
4442 // types that can represent all the values of its underlying type:
4443 // int, unsigned int, long int, unsigned long int, long long int, or
4444 // unsigned long long int [...]
4445 // FIXME: Is there some better way to compute this?
4446 if (BT->getKind() == BuiltinType::WChar_S ||
4447 BT->getKind() == BuiltinType::WChar_U ||
4448 BT->getKind() == BuiltinType::Char16 ||
4449 BT->getKind() == BuiltinType::Char32) {
4450 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4451 uint64_t FromSize = getTypeSize(BT);
4452 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4453 LongLongTy, UnsignedLongLongTy };
4454 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4455 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4456 if (FromSize < ToSize ||
4457 (FromSize == ToSize &&
4458 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4459 return PromoteTypes[Idx];
4460 }
4461 llvm_unreachable("char type should fit into long long");
4462 }
4463 }
4464
4465 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004466 if (Promotable->isSignedIntegerType())
4467 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004468 uint64_t PromotableSize = getIntWidth(Promotable);
4469 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004470 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4471 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4472}
4473
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004474/// \brief Recurses in pointer/array types until it finds an objc retainable
4475/// type and returns its ownership.
4476Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4477 while (!T.isNull()) {
4478 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4479 return T.getObjCLifetime();
4480 if (T->isArrayType())
4481 T = getBaseElementType(T);
4482 else if (const PointerType *PT = T->getAs<PointerType>())
4483 T = PT->getPointeeType();
4484 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004485 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004486 else
4487 break;
4488 }
4489
4490 return Qualifiers::OCL_None;
4491}
4492
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004493static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4494 // Incomplete enum types are not treated as integer types.
4495 // FIXME: In C++, enum types are never integer types.
4496 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4497 return ET->getDecl()->getIntegerType().getTypePtr();
4498 return NULL;
4499}
4500
Mike Stump11289f42009-09-09 15:08:12 +00004501/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004502/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004503/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004504int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004505 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4506 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004507
4508 // Unwrap enums to their underlying type.
4509 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4510 LHSC = getIntegerTypeForEnum(ET);
4511 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4512 RHSC = getIntegerTypeForEnum(ET);
4513
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004514 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004515
Chris Lattner76a00cf2008-04-06 22:59:24 +00004516 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4517 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004518
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004519 unsigned LHSRank = getIntegerRank(LHSC);
4520 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004521
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004522 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4523 if (LHSRank == RHSRank) return 0;
4524 return LHSRank > RHSRank ? 1 : -1;
4525 }
Mike Stump11289f42009-09-09 15:08:12 +00004526
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004527 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4528 if (LHSUnsigned) {
4529 // If the unsigned [LHS] type is larger, return it.
4530 if (LHSRank >= RHSRank)
4531 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004532
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004533 // If the signed type can represent all values of the unsigned type, it
4534 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004535 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004536 return -1;
4537 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004538
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004539 // If the unsigned [RHS] type is larger, return it.
4540 if (RHSRank >= LHSRank)
4541 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004542
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004543 // If the signed type can represent all values of the unsigned type, it
4544 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004545 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004546 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004547}
Anders Carlsson98f07902007-08-17 05:31:46 +00004548
Mike Stump11289f42009-09-09 15:08:12 +00004549// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004550QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004551 if (!CFConstantStringTypeDecl) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004552 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
John McCallae580fe2010-02-05 01:33:36 +00004553 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004554
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004555 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004556
Anders Carlsson98f07902007-08-17 05:31:46 +00004557 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004558 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004559 // int flags;
4560 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004561 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004562 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004563 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004564 FieldTypes[3] = LongTy;
4565
Anders Carlsson98f07902007-08-17 05:31:46 +00004566 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004567 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004568 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004569 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004570 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004571 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004572 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004573 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004574 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004575 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004576 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004577 }
4578
Douglas Gregord5058122010-02-11 01:19:42 +00004579 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004580 }
Mike Stump11289f42009-09-09 15:08:12 +00004581
Anders Carlsson98f07902007-08-17 05:31:46 +00004582 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004583}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004584
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004585QualType ASTContext::getObjCSuperType() const {
4586 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004587 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004588 TUDecl->addDecl(ObjCSuperTypeDecl);
4589 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4590 }
4591 return ObjCSuperType;
4592}
4593
Douglas Gregor512b0772009-04-23 22:29:11 +00004594void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004595 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004596 assert(Rec && "Invalid CFConstantStringType");
4597 CFConstantStringTypeDecl = Rec->getDecl();
4598}
4599
Jay Foad39c79802011-01-12 09:06:06 +00004600QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004601 if (BlockDescriptorType)
4602 return getTagDeclType(BlockDescriptorType);
4603
Alp Toker2dea15b2013-12-17 01:22:38 +00004604 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004605 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004606 RD = buildImplicitRecord("__block_descriptor");
4607 RD->startDefinition();
4608
Mike Stumpd0153282009-10-20 02:12:22 +00004609 QualType FieldTypes[] = {
4610 UnsignedLongTy,
4611 UnsignedLongTy,
4612 };
4613
Craig Topperd6d31ac2013-07-15 08:24:27 +00004614 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004615 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004616 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004617 };
4618
4619 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004620 FieldDecl *Field = FieldDecl::Create(
4621 *this, RD, SourceLocation(), SourceLocation(),
4622 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/0,
4623 /*BitWidth=*/0, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004624 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004625 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004626 }
4627
Alp Toker2dea15b2013-12-17 01:22:38 +00004628 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004629
Alp Toker2dea15b2013-12-17 01:22:38 +00004630 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004631
4632 return getTagDeclType(BlockDescriptorType);
4633}
4634
Jay Foad39c79802011-01-12 09:06:06 +00004635QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004636 if (BlockDescriptorExtendedType)
4637 return getTagDeclType(BlockDescriptorExtendedType);
4638
Alp Toker2dea15b2013-12-17 01:22:38 +00004639 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004640 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004641 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4642 RD->startDefinition();
4643
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004644 QualType FieldTypes[] = {
4645 UnsignedLongTy,
4646 UnsignedLongTy,
4647 getPointerType(VoidPtrTy),
4648 getPointerType(VoidPtrTy)
4649 };
4650
Craig Topperd6d31ac2013-07-15 08:24:27 +00004651 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004652 "reserved",
4653 "Size",
4654 "CopyFuncPtr",
4655 "DestroyFuncPtr"
4656 };
4657
4658 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004659 FieldDecl *Field = FieldDecl::Create(
4660 *this, RD, SourceLocation(), SourceLocation(),
4661 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/0,
4662 /*BitWidth=*/0,
4663 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004664 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004665 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004666 }
4667
Alp Toker2dea15b2013-12-17 01:22:38 +00004668 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004669
Alp Toker2dea15b2013-12-17 01:22:38 +00004670 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004671 return getTagDeclType(BlockDescriptorExtendedType);
4672}
4673
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004674/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4675/// requires copy/dispose. Note that this must match the logic
4676/// in buildByrefHelpers.
4677bool ASTContext::BlockRequiresCopying(QualType Ty,
4678 const VarDecl *D) {
4679 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4680 const Expr *copyExpr = getBlockVarCopyInits(D);
4681 if (!copyExpr && record->hasTrivialDestructor()) return false;
4682
Mike Stump94967902009-10-21 18:16:27 +00004683 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004684 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004685
4686 if (!Ty->isObjCRetainableType()) return false;
4687
4688 Qualifiers qs = Ty.getQualifiers();
4689
4690 // If we have lifetime, that dominates.
4691 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4692 assert(getLangOpts().ObjCAutoRefCount);
4693
4694 switch (lifetime) {
4695 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4696
4697 // These are just bits as far as the runtime is concerned.
4698 case Qualifiers::OCL_ExplicitNone:
4699 case Qualifiers::OCL_Autoreleasing:
4700 return false;
4701
4702 // Tell the runtime that this is ARC __weak, called by the
4703 // byref routines.
4704 case Qualifiers::OCL_Weak:
4705 // ARC __strong __block variables need to be retained.
4706 case Qualifiers::OCL_Strong:
4707 return true;
4708 }
4709 llvm_unreachable("fell out of lifetime switch!");
4710 }
4711 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4712 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004713}
4714
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004715bool ASTContext::getByrefLifetime(QualType Ty,
4716 Qualifiers::ObjCLifetime &LifeTime,
4717 bool &HasByrefExtendedLayout) const {
4718
4719 if (!getLangOpts().ObjC1 ||
4720 getLangOpts().getGC() != LangOptions::NonGC)
4721 return false;
4722
4723 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004724 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004725 HasByrefExtendedLayout = true;
4726 LifeTime = Qualifiers::OCL_None;
4727 }
4728 else if (getLangOpts().ObjCAutoRefCount)
4729 LifeTime = Ty.getObjCLifetime();
4730 // MRR.
4731 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4732 LifeTime = Qualifiers::OCL_ExplicitNone;
4733 else
4734 LifeTime = Qualifiers::OCL_None;
4735 return true;
4736}
4737
Douglas Gregorbab8a962011-09-08 01:46:34 +00004738TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4739 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00004740 ObjCInstanceTypeDecl =
4741 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00004742 return ObjCInstanceTypeDecl;
4743}
4744
Anders Carlsson18acd442007-10-29 06:33:42 +00004745// This returns true if a type has been typedefed to BOOL:
4746// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004747static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004748 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004749 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4750 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004751
Anders Carlssond8499822007-10-29 05:01:08 +00004752 return false;
4753}
4754
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004755/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004756/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004757CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004758 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4759 return CharUnits::Zero();
4760
Ken Dyck40775002010-01-11 17:06:35 +00004761 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004762
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004763 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004764 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004765 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004766 // Treat arrays as pointers, since that's how they're passed in.
4767 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004768 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004769 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004770}
4771
4772static inline
4773std::string charUnitsToString(const CharUnits &CU) {
4774 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004775}
4776
John McCall351762c2011-02-07 10:33:21 +00004777/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004778/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004779std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4780 std::string S;
4781
David Chisnall950a9512009-11-17 19:33:30 +00004782 const BlockDecl *Decl = Expr->getBlockDecl();
4783 QualType BlockTy =
4784 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4785 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004786 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00004787 getObjCEncodingForMethodParameter(
4788 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
4789 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004790 else
Alp Toker314cc812014-01-25 16:55:45 +00004791 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004792 // Compute size of all parameters.
4793 // Start with computing size of a pointer in number of bytes.
4794 // FIXME: There might(should) be a better way of doing this computation!
4795 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004796 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4797 CharUnits ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00004798 for (auto PI : Decl->params()) {
4799 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004800 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004801 if (sz.isZero())
4802 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004803 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004804 ParmOffset += sz;
4805 }
4806 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004807 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004808 // Block pointer and offset.
4809 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004810
4811 // Argument types.
4812 ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00004813 for (auto PVDecl : Decl->params()) {
David Chisnall950a9512009-11-17 19:33:30 +00004814 QualType PType = PVDecl->getOriginalType();
4815 if (const ArrayType *AT =
4816 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4817 // Use array's original type only if it has known number of
4818 // elements.
4819 if (!isa<ConstantArrayType>(AT))
4820 PType = PVDecl->getType();
4821 } else if (PType->isFunctionType())
4822 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004823 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004824 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4825 S, true /*Extended*/);
4826 else
4827 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004828 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004829 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004830 }
John McCall351762c2011-02-07 10:33:21 +00004831
4832 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004833}
4834
Douglas Gregora9d84932011-05-27 01:19:52 +00004835bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004836 std::string& S) {
4837 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00004838 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00004839 CharUnits ParmOffset;
4840 // Compute size of all parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00004841 for (auto PI : Decl->params()) {
4842 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00004843 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004844 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004845 continue;
4846
David Chisnall50e4eba2010-12-30 14:05:53 +00004847 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004848 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004849 ParmOffset += sz;
4850 }
4851 S += charUnitsToString(ParmOffset);
4852 ParmOffset = CharUnits::Zero();
4853
4854 // Argument types.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00004855 for (auto PVDecl : Decl->params()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00004856 QualType PType = PVDecl->getOriginalType();
4857 if (const ArrayType *AT =
4858 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4859 // Use array's original type only if it has known number of
4860 // elements.
4861 if (!isa<ConstantArrayType>(AT))
4862 PType = PVDecl->getType();
4863 } else if (PType->isFunctionType())
4864 PType = PVDecl->getType();
4865 getObjCEncodingForType(PType, S);
4866 S += charUnitsToString(ParmOffset);
4867 ParmOffset += getObjCEncodingTypeSize(PType);
4868 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004869
4870 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004871}
4872
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004873/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4874/// method parameter or return type. If Extended, include class names and
4875/// block object types.
4876void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4877 QualType T, std::string& S,
4878 bool Extended) const {
4879 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4880 getObjCEncodingForTypeQualifier(QT, S);
4881 // Encode parameter type.
4882 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4883 true /*OutermostType*/,
4884 false /*EncodingProperty*/,
4885 false /*StructField*/,
4886 Extended /*EncodeBlockParameters*/,
4887 Extended /*EncodeClassNames*/);
4888}
4889
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004890/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004891/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004892bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004893 std::string& S,
4894 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004895 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004896 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00004897 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4898 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004899 // Compute size of all parameters.
4900 // Start with computing size of a pointer in number of bytes.
4901 // FIXME: There might(should) be a better way of doing this computation!
4902 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004903 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004904 // The first two arguments (self and _cmd) are pointers; account for
4905 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004906 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004907 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004908 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004909 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004910 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004911 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004912 continue;
4913
Ken Dyck40775002010-01-11 17:06:35 +00004914 assert (sz.isPositive() &&
4915 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004916 ParmOffset += sz;
4917 }
Ken Dyck40775002010-01-11 17:06:35 +00004918 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004919 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004920 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004921
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004922 // Argument types.
4923 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004924 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004925 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004926 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004927 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004928 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004929 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4930 // Use array's original type only if it has known number of
4931 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004932 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004933 PType = PVDecl->getType();
4934 } else if (PType->isFunctionType())
4935 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004936 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4937 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004938 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004939 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004940 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004941
4942 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004943}
4944
Fariborz Jahaniandad96302014-01-22 19:02:20 +00004945ObjCPropertyImplDecl *
4946ASTContext::getObjCPropertyImplDeclForPropertyDecl(
4947 const ObjCPropertyDecl *PD,
4948 const Decl *Container) const {
4949 if (!Container)
4950 return 0;
4951 if (const ObjCCategoryImplDecl *CID =
4952 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00004953 for (auto *PID : CID->property_impls())
4954 if (PID->getPropertyDecl() == PD)
4955 return PID;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00004956 } else {
4957 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Aaron Ballmand85eff42014-03-14 15:02:45 +00004958 for (auto *PID : OID->property_impls())
Fariborz Jahaniandad96302014-01-22 19:02:20 +00004959 if (PID->getPropertyDecl() == PD)
4960 return PID;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00004961 }
4962 return 0;
4963}
4964
Daniel Dunbar4932b362008-08-28 04:38:10 +00004965/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004966/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004967/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4968/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004969/// Property attributes are stored as a comma-delimited C string. The simple
4970/// attributes readonly and bycopy are encoded as single characters. The
4971/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4972/// encoded as single characters, followed by an identifier. Property types
4973/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004974/// these attributes are defined by the following enumeration:
4975/// @code
4976/// enum PropertyAttributes {
4977/// kPropertyReadOnly = 'R', // property is read-only.
4978/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4979/// kPropertyByref = '&', // property is a reference to the value last assigned
4980/// kPropertyDynamic = 'D', // property is dynamic
4981/// kPropertyGetter = 'G', // followed by getter selector name
4982/// kPropertySetter = 'S', // followed by setter selector name
4983/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004984/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004985/// kPropertyWeak = 'W' // 'weak' property
4986/// kPropertyStrong = 'P' // property GC'able
4987/// kPropertyNonAtomic = 'N' // property non-atomic
4988/// };
4989/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004990void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004991 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004992 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004993 // Collect information from the property implementation decl(s).
4994 bool Dynamic = false;
4995 ObjCPropertyImplDecl *SynthesizePID = 0;
4996
Fariborz Jahaniandad96302014-01-22 19:02:20 +00004997 if (ObjCPropertyImplDecl *PropertyImpDecl =
4998 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
4999 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5000 Dynamic = true;
5001 else
5002 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005003 }
5004
5005 // FIXME: This is not very efficient.
5006 S = "T";
5007
5008 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005009 // GCC has some special rules regarding encoding of properties which
5010 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00005011 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005012 true /* outermost type */,
5013 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005014
5015 if (PD->isReadOnly()) {
5016 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005017 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5018 S += ",C";
5019 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5020 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005021 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5022 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005023 } else {
5024 switch (PD->getSetterKind()) {
5025 case ObjCPropertyDecl::Assign: break;
5026 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005027 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005028 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005029 }
5030 }
5031
5032 // It really isn't clear at all what this means, since properties
5033 // are "dynamic by default".
5034 if (Dynamic)
5035 S += ",D";
5036
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005037 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5038 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005039
Daniel Dunbar4932b362008-08-28 04:38:10 +00005040 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5041 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005042 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005043 }
5044
5045 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5046 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005047 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005048 }
5049
5050 if (SynthesizePID) {
5051 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5052 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005053 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005054 }
5055
5056 // FIXME: OBJCGC: weak & strong
5057}
5058
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005059/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005060/// Another legacy compatibility encoding: 32-bit longs are encoded as
5061/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005062/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5063///
5064void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005065 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005066 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005067 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005068 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005069 else
Jay Foad39c79802011-01-12 09:06:06 +00005070 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005071 PointeeTy = IntTy;
5072 }
5073 }
5074}
5075
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005076void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00005077 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005078 // We follow the behavior of gcc, expanding structures which are
5079 // directly pointed to, and expanding embedded structures. Note that
5080 // these rules are sufficient to prevent recursive encoding of the
5081 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005082 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00005083 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005084}
5085
John McCall393a78d2012-12-20 02:45:14 +00005086static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5087 BuiltinType::Kind kind) {
5088 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005089 case BuiltinType::Void: return 'v';
5090 case BuiltinType::Bool: return 'B';
5091 case BuiltinType::Char_U:
5092 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005093 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005094 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005095 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005096 case BuiltinType::UInt: return 'I';
5097 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005098 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005099 case BuiltinType::UInt128: return 'T';
5100 case BuiltinType::ULongLong: return 'Q';
5101 case BuiltinType::Char_S:
5102 case BuiltinType::SChar: return 'c';
5103 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005104 case BuiltinType::WChar_S:
5105 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005106 case BuiltinType::Int: return 'i';
5107 case BuiltinType::Long:
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::LongLong: return 'q';
5110 case BuiltinType::Int128: return 't';
5111 case BuiltinType::Float: return 'f';
5112 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005113 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005114 case BuiltinType::NullPtr: return '*'; // like char*
5115
5116 case BuiltinType::Half:
5117 // FIXME: potentially need @encodes for these!
5118 return ' ';
5119
5120 case BuiltinType::ObjCId:
5121 case BuiltinType::ObjCClass:
5122 case BuiltinType::ObjCSel:
5123 llvm_unreachable("@encoding ObjC primitive type");
5124
5125 // OpenCL and placeholder types don't need @encodings.
5126 case BuiltinType::OCLImage1d:
5127 case BuiltinType::OCLImage1dArray:
5128 case BuiltinType::OCLImage1dBuffer:
5129 case BuiltinType::OCLImage2d:
5130 case BuiltinType::OCLImage2dArray:
5131 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005132 case BuiltinType::OCLEvent:
Guy Benyei61054192013-02-07 10:55:47 +00005133 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005134 case BuiltinType::Dependent:
5135#define BUILTIN_TYPE(KIND, ID)
5136#define PLACEHOLDER_TYPE(KIND, ID) \
5137 case BuiltinType::KIND:
5138#include "clang/AST/BuiltinTypes.def"
5139 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005140 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005141 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005142}
5143
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005144static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5145 EnumDecl *Enum = ET->getDecl();
5146
5147 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5148 if (!Enum->isFixed())
5149 return 'i';
5150
5151 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005152 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5153 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005154}
5155
Jay Foad39c79802011-01-12 09:06:06 +00005156static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005157 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005158 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005159 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005160 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5161 // The GNU runtime requires more information; bitfields are encoded as b,
5162 // then the offset (in bits) of the first element, then the type of the
5163 // bitfield, then the size in bits. For example, in this structure:
5164 //
5165 // struct
5166 // {
5167 // int integer;
5168 // int flags:2;
5169 // };
5170 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5171 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5172 // information is not especially sensible, but we're stuck with it for
5173 // compatibility with GCC, although providing it breaks anything that
5174 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005175 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005176 const RecordDecl *RD = FD->getParent();
5177 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005178 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005179 if (const EnumType *ET = T->getAs<EnumType>())
5180 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005181 else {
5182 const BuiltinType *BT = T->castAs<BuiltinType>();
5183 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5184 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005185 }
Richard Smithcaf33902011-10-10 18:28:20 +00005186 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005187}
5188
Daniel Dunbar07d07852009-10-18 21:17:35 +00005189// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005190void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5191 bool ExpandPointedToStructures,
5192 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005193 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005194 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005195 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005196 bool StructField,
5197 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005198 bool EncodeClassNames,
5199 bool EncodePointerToObjCTypedef) const {
John McCall393a78d2012-12-20 02:45:14 +00005200 CanQualType CT = getCanonicalType(T);
5201 switch (CT->getTypeClass()) {
5202 case Type::Builtin:
5203 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005204 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005205 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005206 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5207 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5208 else
5209 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005210 return;
Mike Stump11289f42009-09-09 15:08:12 +00005211
John McCall393a78d2012-12-20 02:45:14 +00005212 case Type::Complex: {
5213 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005214 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00005215 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00005216 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005217 return;
5218 }
John McCall393a78d2012-12-20 02:45:14 +00005219
5220 case Type::Atomic: {
5221 const AtomicType *AT = T->castAs<AtomicType>();
5222 S += 'A';
5223 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5224 false, false);
5225 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005226 }
John McCall393a78d2012-12-20 02:45:14 +00005227
5228 // encoding for pointer or reference types.
5229 case Type::Pointer:
5230 case Type::LValueReference:
5231 case Type::RValueReference: {
5232 QualType PointeeTy;
5233 if (isa<PointerType>(CT)) {
5234 const PointerType *PT = T->castAs<PointerType>();
5235 if (PT->isObjCSelType()) {
5236 S += ':';
5237 return;
5238 }
5239 PointeeTy = PT->getPointeeType();
5240 } else {
5241 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5242 }
5243
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005244 bool isReadOnly = false;
5245 // For historical/compatibility reasons, the read-only qualifier of the
5246 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5247 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005248 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005249 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005250 if (OutermostType && T.isConstQualified()) {
5251 isReadOnly = true;
5252 S += 'r';
5253 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005254 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005255 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005256 while (P->getAs<PointerType>())
5257 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005258 if (P.isConstQualified()) {
5259 isReadOnly = true;
5260 S += 'r';
5261 }
5262 }
5263 if (isReadOnly) {
5264 // Another legacy compatibility encoding. Some ObjC qualifier and type
5265 // combinations need to be rearranged.
5266 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005267 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005268 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005269 }
Mike Stump11289f42009-09-09 15:08:12 +00005270
Anders Carlssond8499822007-10-29 05:01:08 +00005271 if (PointeeTy->isCharType()) {
5272 // char pointer types should be encoded as '*' unless it is a
5273 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005274 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005275 S += '*';
5276 return;
5277 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005278 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005279 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5280 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5281 S += '#';
5282 return;
5283 }
5284 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5285 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5286 S += '@';
5287 return;
5288 }
5289 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005290 }
Anders Carlssond8499822007-10-29 05:01:08 +00005291 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005292 getLegacyIntegralTypeEncoding(PointeeTy);
5293
Mike Stump11289f42009-09-09 15:08:12 +00005294 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005295 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005296 return;
5297 }
John McCall393a78d2012-12-20 02:45:14 +00005298
5299 case Type::ConstantArray:
5300 case Type::IncompleteArray:
5301 case Type::VariableArray: {
5302 const ArrayType *AT = cast<ArrayType>(CT);
5303
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005304 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005305 // Incomplete arrays are encoded as a pointer to the array element.
5306 S += '^';
5307
Mike Stump11289f42009-09-09 15:08:12 +00005308 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005309 false, ExpandStructures, FD);
5310 } else {
5311 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005312
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005313 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5314 S += llvm::utostr(CAT->getSize().getZExtValue());
5315 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005316 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005317 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5318 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005319 S += '0';
5320 }
Mike Stump11289f42009-09-09 15:08:12 +00005321
5322 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005323 false, ExpandStructures, FD);
5324 S += ']';
5325 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005326 return;
5327 }
Mike Stump11289f42009-09-09 15:08:12 +00005328
John McCall393a78d2012-12-20 02:45:14 +00005329 case Type::FunctionNoProto:
5330 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005331 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005332 return;
Mike Stump11289f42009-09-09 15:08:12 +00005333
John McCall393a78d2012-12-20 02:45:14 +00005334 case Type::Record: {
5335 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005336 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005337 // Anonymous structures print as '?'
5338 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5339 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005340 if (ClassTemplateSpecializationDecl *Spec
5341 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5342 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005343 llvm::raw_string_ostream OS(S);
5344 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005345 TemplateArgs.data(),
5346 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005347 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005348 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005349 } else {
5350 S += '?';
5351 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005352 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005353 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005354 if (!RDecl->isUnion()) {
5355 getObjCEncodingForStructureImpl(RDecl, S, FD);
5356 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005357 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005358 if (FD) {
5359 S += '"';
5360 S += Field->getNameAsString();
5361 S += '"';
5362 }
Mike Stump11289f42009-09-09 15:08:12 +00005363
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005364 // Special case bit-fields.
5365 if (Field->isBitField()) {
5366 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005367 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005368 } else {
5369 QualType qt = Field->getType();
5370 getLegacyIntegralTypeEncoding(qt);
5371 getObjCEncodingForTypeImpl(qt, S, false, true,
5372 FD, /*OutermostType*/false,
5373 /*EncodingProperty*/false,
5374 /*StructField*/true);
5375 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005376 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005377 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005378 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005379 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005380 return;
5381 }
Mike Stump11289f42009-09-09 15:08:12 +00005382
John McCall393a78d2012-12-20 02:45:14 +00005383 case Type::BlockPointer: {
5384 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005385 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005386 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005387 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005388
5389 S += '<';
5390 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005391 getObjCEncodingForTypeImpl(
5392 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5393 FD, false /* OutermostType */, EncodingProperty,
5394 false /* StructField */, EncodeBlockParameters, EncodeClassNames);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005395 // Block self
5396 S += "@?";
5397 // Block parameters
5398 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005399 for (const auto &I : FPT->param_types())
5400 getObjCEncodingForTypeImpl(
5401 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5402 false /* OutermostType */, EncodingProperty,
5403 false /* StructField */, EncodeBlockParameters, EncodeClassNames);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005404 }
5405 S += '>';
5406 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005407 return;
5408 }
Mike Stump11289f42009-09-09 15:08:12 +00005409
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005410 case Type::ObjCObject: {
5411 // hack to match legacy encoding of *id and *Class
5412 QualType Ty = getObjCObjectPointerType(CT);
5413 if (Ty->isObjCIdType()) {
5414 S += "{objc_object=}";
5415 return;
5416 }
5417 else if (Ty->isObjCClassType()) {
5418 S += "{objc_class=}";
5419 return;
5420 }
5421 }
5422
John McCall393a78d2012-12-20 02:45:14 +00005423 case Type::ObjCInterface: {
5424 // Ignore protocol qualifiers when mangling at this level.
5425 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005426
John McCall393a78d2012-12-20 02:45:14 +00005427 // The assumption seems to be that this assert will succeed
5428 // because nested levels will have filtered out 'id' and 'Class'.
5429 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005430 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005431 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005432 S += '{';
5433 const IdentifierInfo *II = OI->getIdentifier();
5434 S += II->getName();
5435 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005436 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005437 DeepCollectObjCIvars(OI, true, Ivars);
5438 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005439 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005440 if (Field->isBitField())
5441 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005442 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005443 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5444 false, false, false, false, false,
5445 EncodePointerToObjCTypedef);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005446 }
5447 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005448 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005449 }
Mike Stump11289f42009-09-09 15:08:12 +00005450
John McCall393a78d2012-12-20 02:45:14 +00005451 case Type::ObjCObjectPointer: {
5452 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005453 if (OPT->isObjCIdType()) {
5454 S += '@';
5455 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005456 }
Mike Stump11289f42009-09-09 15:08:12 +00005457
Steve Narofff0c86112009-10-28 22:03:49 +00005458 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5459 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5460 // Since this is a binary compatibility issue, need to consult with runtime
5461 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005462 S += '#';
5463 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005464 }
Mike Stump11289f42009-09-09 15:08:12 +00005465
Chris Lattnere7cabb92009-07-13 00:10:46 +00005466 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005467 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005468 ExpandPointedToStructures,
5469 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005470 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005471 // Note that we do extended encoding of protocol qualifer list
5472 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005473 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00005474 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005475 S += '<';
Aaron Ballman83731462014-03-17 16:14:00 +00005476 S += I->getNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005477 S += '>';
5478 }
5479 S += '"';
5480 }
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 QualType PointeeTy = OPT->getPointeeType();
5485 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005486 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5487 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005488 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005489 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005490 // {...};
5491 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005492 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005493 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005494 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5495 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5496 DeepCollectObjCIvars(OI, true, Ivars);
5497 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5498 if (cast<FieldDecl>(Ivars[i]) == FD) {
5499 S += '{';
5500 S += OI->getIdentifier()->getName();
5501 S += '}';
5502 return;
5503 }
5504 }
5505 }
Mike Stump11289f42009-09-09 15:08:12 +00005506 getObjCEncodingForTypeImpl(PointeeTy, S,
5507 false, ExpandPointedToStructures,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005508 NULL,
5509 false, false, false, false, false,
5510 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005511 return;
5512 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005513
5514 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005515 if (OPT->getInterfaceDecl() &&
5516 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005517 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005518 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Aaron Ballman83731462014-03-17 16:14:00 +00005519 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005520 S += '<';
Aaron Ballman83731462014-03-17 16:14:00 +00005521 S += I->getNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00005522 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005523 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005524 S += '"';
5525 }
5526 return;
5527 }
Mike Stump11289f42009-09-09 15:08:12 +00005528
John McCalla9e6e8d2010-05-17 23:56:34 +00005529 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005530 // FIXME: we shoul do better than that. 'M' is available.
5531 case Type::MemberPointer:
John McCalla9e6e8d2010-05-17 23:56:34 +00005532 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005533
John McCall393a78d2012-12-20 02:45:14 +00005534 case Type::Vector:
5535 case Type::ExtVector:
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005536 // This matches gcc's encoding, even though technically it is
5537 // insufficient.
5538 // FIXME. We should do a better job than gcc.
5539 return;
John McCall393a78d2012-12-20 02:45:14 +00005540
Richard Smith27d807c2013-04-30 13:56:41 +00005541 case Type::Auto:
5542 // We could see an undeduced auto type here during error recovery.
5543 // Just ignore it.
5544 return;
5545
John McCall393a78d2012-12-20 02:45:14 +00005546#define ABSTRACT_TYPE(KIND, BASE)
5547#define TYPE(KIND, BASE)
5548#define DEPENDENT_TYPE(KIND, BASE) \
5549 case Type::KIND:
5550#define NON_CANONICAL_TYPE(KIND, BASE) \
5551 case Type::KIND:
5552#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5553 case Type::KIND:
5554#include "clang/AST/TypeNodes.def"
5555 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005556 }
John McCall393a78d2012-12-20 02:45:14 +00005557 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005558}
5559
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005560void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5561 std::string &S,
5562 const FieldDecl *FD,
5563 bool includeVBases) const {
5564 assert(RDecl && "Expected non-null RecordDecl");
5565 assert(!RDecl->isUnion() && "Should not be called for unions");
5566 if (!RDecl->getDefinition())
5567 return;
5568
5569 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5570 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5571 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5572
5573 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00005574 for (const auto &BI : CXXRec->bases()) {
5575 if (!BI.isVirtual()) {
5576 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005577 if (base->isEmpty())
5578 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005579 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005580 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5581 std::make_pair(offs, base));
5582 }
5583 }
5584 }
5585
5586 unsigned i = 0;
5587 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5588 FieldEnd = RDecl->field_end();
5589 Field != FieldEnd; ++Field, ++i) {
5590 uint64_t offs = layout.getFieldOffset(i);
5591 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005592 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005593 }
5594
5595 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005596 for (const auto &BI : CXXRec->vbases()) {
5597 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005598 if (base->isEmpty())
5599 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005600 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005601 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5602 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005603 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5604 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005605 }
5606 }
5607
5608 CharUnits size;
5609 if (CXXRec) {
5610 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5611 } else {
5612 size = layout.getSize();
5613 }
5614
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005615#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005616 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005617#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005618 std::multimap<uint64_t, NamedDecl *>::iterator
5619 CurLayObj = FieldOrBaseOffsets.begin();
5620
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005621 if (CXXRec && CXXRec->isDynamicClass() &&
5622 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005623 if (FD) {
5624 S += "\"_vptr$";
5625 std::string recname = CXXRec->getNameAsString();
5626 if (recname.empty()) recname = "?";
5627 S += recname;
5628 S += '"';
5629 }
5630 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005631#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005632 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005633#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005634 }
5635
5636 if (!RDecl->hasFlexibleArrayMember()) {
5637 // Mark the end of the structure.
5638 uint64_t offs = toBits(size);
5639 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5640 std::make_pair(offs, (NamedDecl*)0));
5641 }
5642
5643 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005644#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005645 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005646 if (CurOffs < CurLayObj->first) {
5647 uint64_t padding = CurLayObj->first - CurOffs;
5648 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5649 // packing/alignment of members is different that normal, in which case
5650 // the encoding will be out-of-sync with the real layout.
5651 // If the runtime switches to just consider the size of types without
5652 // taking into account alignment, we could make padding explicit in the
5653 // encoding (e.g. using arrays of chars). The encoding strings would be
5654 // longer then though.
5655 CurOffs += padding;
5656 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005657#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005658
5659 NamedDecl *dcl = CurLayObj->second;
5660 if (dcl == 0)
5661 break; // reached end of structure.
5662
5663 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5664 // We expand the bases without their virtual bases since those are going
5665 // in the initial structure. Note that this differs from gcc which
5666 // expands virtual bases each time one is encountered in the hierarchy,
5667 // making the encoding type bigger than it really is.
5668 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005669 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005670#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005671 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005672#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005673 } else {
5674 FieldDecl *field = cast<FieldDecl>(dcl);
5675 if (FD) {
5676 S += '"';
5677 S += field->getNameAsString();
5678 S += '"';
5679 }
5680
5681 if (field->isBitField()) {
5682 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005683#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00005684 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005685#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005686 } else {
5687 QualType qt = field->getType();
5688 getLegacyIntegralTypeEncoding(qt);
5689 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5690 /*OutermostType*/false,
5691 /*EncodingProperty*/false,
5692 /*StructField*/true);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005693#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005694 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005695#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005696 }
5697 }
5698 }
5699}
5700
Mike Stump11289f42009-09-09 15:08:12 +00005701void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005702 std::string& S) const {
5703 if (QT & Decl::OBJC_TQ_In)
5704 S += 'n';
5705 if (QT & Decl::OBJC_TQ_Inout)
5706 S += 'N';
5707 if (QT & Decl::OBJC_TQ_Out)
5708 S += 'o';
5709 if (QT & Decl::OBJC_TQ_Bycopy)
5710 S += 'O';
5711 if (QT & Decl::OBJC_TQ_Byref)
5712 S += 'R';
5713 if (QT & Decl::OBJC_TQ_Oneway)
5714 S += 'V';
5715}
5716
Douglas Gregor3ea72692011-08-12 05:46:01 +00005717TypedefDecl *ASTContext::getObjCIdDecl() const {
5718 if (!ObjCIdDecl) {
5719 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5720 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005721 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00005722 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00005723 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005724}
5725
Douglas Gregor52e02802011-08-12 06:17:30 +00005726TypedefDecl *ASTContext::getObjCSelDecl() const {
5727 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005728 QualType T = getPointerType(ObjCBuiltinSelTy);
5729 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00005730 }
5731 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005732}
5733
Douglas Gregor0a586182011-08-12 05:59:41 +00005734TypedefDecl *ASTContext::getObjCClassDecl() const {
5735 if (!ObjCClassDecl) {
5736 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5737 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005738 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00005739 }
Douglas Gregor0a586182011-08-12 05:59:41 +00005740 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005741}
5742
Douglas Gregord53ae832012-01-17 18:09:05 +00005743ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5744 if (!ObjCProtocolClassDecl) {
5745 ObjCProtocolClassDecl
5746 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5747 SourceLocation(),
5748 &Idents.get("Protocol"),
5749 /*PrevDecl=*/0,
5750 SourceLocation(), true);
5751 }
5752
5753 return ObjCProtocolClassDecl;
5754}
5755
Meador Inge5d3fb222012-06-16 03:34:49 +00005756//===----------------------------------------------------------------------===//
5757// __builtin_va_list Construction Functions
5758//===----------------------------------------------------------------------===//
5759
5760static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5761 // typedef char* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005762 QualType T = Context->getPointerType(Context->CharTy);
5763 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005764}
5765
5766static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5767 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005768 QualType T = Context->getPointerType(Context->VoidTy);
5769 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005770}
5771
Tim Northover9bb857a2013-01-31 12:13:10 +00005772static TypedefDecl *
5773CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005774 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00005775 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005776 if (Context->getLangOpts().CPlusPlus) {
5777 // namespace std { struct __va_list {
5778 NamespaceDecl *NS;
5779 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5780 Context->getTranslationUnitDecl(),
5781 /*Inline*/false, SourceLocation(),
5782 SourceLocation(), &Context->Idents.get("std"),
5783 /*PrevDecl*/0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005784 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00005785 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00005786 }
5787
5788 VaListTagDecl->startDefinition();
5789
5790 const size_t NumFields = 5;
5791 QualType FieldTypes[NumFields];
5792 const char *FieldNames[NumFields];
5793
5794 // void *__stack;
5795 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5796 FieldNames[0] = "__stack";
5797
5798 // void *__gr_top;
5799 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5800 FieldNames[1] = "__gr_top";
5801
5802 // void *__vr_top;
5803 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5804 FieldNames[2] = "__vr_top";
5805
5806 // int __gr_offs;
5807 FieldTypes[3] = Context->IntTy;
5808 FieldNames[3] = "__gr_offs";
5809
5810 // int __vr_offs;
5811 FieldTypes[4] = Context->IntTy;
5812 FieldNames[4] = "__vr_offs";
5813
5814 // Create fields
5815 for (unsigned i = 0; i < NumFields; ++i) {
5816 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5817 VaListTagDecl,
5818 SourceLocation(),
5819 SourceLocation(),
5820 &Context->Idents.get(FieldNames[i]),
5821 FieldTypes[i], /*TInfo=*/0,
5822 /*BitWidth=*/0,
5823 /*Mutable=*/false,
5824 ICIS_NoInit);
5825 Field->setAccess(AS_public);
5826 VaListTagDecl->addDecl(Field);
5827 }
5828 VaListTagDecl->completeDefinition();
5829 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5830 Context->VaListTagTy = VaListTagType;
5831
5832 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005833 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005834}
5835
Meador Inge5d3fb222012-06-16 03:34:49 +00005836static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5837 // typedef struct __va_list_tag {
5838 RecordDecl *VaListTagDecl;
5839
Alp Toker2dea15b2013-12-17 01:22:38 +00005840 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005841 VaListTagDecl->startDefinition();
5842
5843 const size_t NumFields = 5;
5844 QualType FieldTypes[NumFields];
5845 const char *FieldNames[NumFields];
5846
5847 // unsigned char gpr;
5848 FieldTypes[0] = Context->UnsignedCharTy;
5849 FieldNames[0] = "gpr";
5850
5851 // unsigned char fpr;
5852 FieldTypes[1] = Context->UnsignedCharTy;
5853 FieldNames[1] = "fpr";
5854
5855 // unsigned short reserved;
5856 FieldTypes[2] = Context->UnsignedShortTy;
5857 FieldNames[2] = "reserved";
5858
5859 // void* overflow_arg_area;
5860 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5861 FieldNames[3] = "overflow_arg_area";
5862
5863 // void* reg_save_area;
5864 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5865 FieldNames[4] = "reg_save_area";
5866
5867 // Create fields
5868 for (unsigned i = 0; i < NumFields; ++i) {
5869 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5870 SourceLocation(),
5871 SourceLocation(),
5872 &Context->Idents.get(FieldNames[i]),
5873 FieldTypes[i], /*TInfo=*/0,
5874 /*BitWidth=*/0,
5875 /*Mutable=*/false,
5876 ICIS_NoInit);
5877 Field->setAccess(AS_public);
5878 VaListTagDecl->addDecl(Field);
5879 }
5880 VaListTagDecl->completeDefinition();
5881 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005882 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005883
5884 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00005885 TypedefDecl *VaListTagTypedefDecl =
5886 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
5887
Meador Inge5d3fb222012-06-16 03:34:49 +00005888 QualType VaListTagTypedefType =
5889 Context->getTypedefType(VaListTagTypedefDecl);
5890
5891 // typedef __va_list_tag __builtin_va_list[1];
5892 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5893 QualType VaListTagArrayType
5894 = Context->getConstantArrayType(VaListTagTypedefType,
5895 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005896 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005897}
5898
5899static TypedefDecl *
5900CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5901 // typedef struct __va_list_tag {
5902 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00005903 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005904 VaListTagDecl->startDefinition();
5905
5906 const size_t NumFields = 4;
5907 QualType FieldTypes[NumFields];
5908 const char *FieldNames[NumFields];
5909
5910 // unsigned gp_offset;
5911 FieldTypes[0] = Context->UnsignedIntTy;
5912 FieldNames[0] = "gp_offset";
5913
5914 // unsigned fp_offset;
5915 FieldTypes[1] = Context->UnsignedIntTy;
5916 FieldNames[1] = "fp_offset";
5917
5918 // void* overflow_arg_area;
5919 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5920 FieldNames[2] = "overflow_arg_area";
5921
5922 // void* reg_save_area;
5923 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5924 FieldNames[3] = "reg_save_area";
5925
5926 // Create fields
5927 for (unsigned i = 0; i < NumFields; ++i) {
5928 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5929 VaListTagDecl,
5930 SourceLocation(),
5931 SourceLocation(),
5932 &Context->Idents.get(FieldNames[i]),
5933 FieldTypes[i], /*TInfo=*/0,
5934 /*BitWidth=*/0,
5935 /*Mutable=*/false,
5936 ICIS_NoInit);
5937 Field->setAccess(AS_public);
5938 VaListTagDecl->addDecl(Field);
5939 }
5940 VaListTagDecl->completeDefinition();
5941 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005942 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005943
5944 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00005945 TypedefDecl *VaListTagTypedefDecl =
5946 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
5947
Meador Inge5d3fb222012-06-16 03:34:49 +00005948 QualType VaListTagTypedefType =
5949 Context->getTypedefType(VaListTagTypedefDecl);
5950
5951 // typedef __va_list_tag __builtin_va_list[1];
5952 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5953 QualType VaListTagArrayType
5954 = Context->getConstantArrayType(VaListTagTypedefType,
5955 Size, ArrayType::Normal,0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005956 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005957}
5958
5959static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5960 // typedef int __builtin_va_list[4];
5961 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5962 QualType IntArrayType
5963 = Context->getConstantArrayType(Context->IntTy,
5964 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005965 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005966}
5967
Logan Chien57086ce2012-10-10 06:56:20 +00005968static TypedefDecl *
5969CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005970 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00005971 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00005972 if (Context->getLangOpts().CPlusPlus) {
5973 // namespace std { struct __va_list {
5974 NamespaceDecl *NS;
5975 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5976 Context->getTranslationUnitDecl(),
5977 /*Inline*/false, SourceLocation(),
5978 SourceLocation(), &Context->Idents.get("std"),
5979 /*PrevDecl*/0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005980 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00005981 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00005982 }
5983
5984 VaListDecl->startDefinition();
5985
5986 // void * __ap;
5987 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5988 VaListDecl,
5989 SourceLocation(),
5990 SourceLocation(),
5991 &Context->Idents.get("__ap"),
5992 Context->getPointerType(Context->VoidTy),
5993 /*TInfo=*/0,
5994 /*BitWidth=*/0,
5995 /*Mutable=*/false,
5996 ICIS_NoInit);
5997 Field->setAccess(AS_public);
5998 VaListDecl->addDecl(Field);
5999
6000 // };
6001 VaListDecl->completeDefinition();
6002
6003 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006004 QualType T = Context->getRecordType(VaListDecl);
6005 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006006}
6007
Ulrich Weigand47445072013-05-06 16:26:41 +00006008static TypedefDecl *
6009CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6010 // typedef struct __va_list_tag {
6011 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006012 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006013 VaListTagDecl->startDefinition();
6014
6015 const size_t NumFields = 4;
6016 QualType FieldTypes[NumFields];
6017 const char *FieldNames[NumFields];
6018
6019 // long __gpr;
6020 FieldTypes[0] = Context->LongTy;
6021 FieldNames[0] = "__gpr";
6022
6023 // long __fpr;
6024 FieldTypes[1] = Context->LongTy;
6025 FieldNames[1] = "__fpr";
6026
6027 // void *__overflow_arg_area;
6028 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6029 FieldNames[2] = "__overflow_arg_area";
6030
6031 // void *__reg_save_area;
6032 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6033 FieldNames[3] = "__reg_save_area";
6034
6035 // Create fields
6036 for (unsigned i = 0; i < NumFields; ++i) {
6037 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6038 VaListTagDecl,
6039 SourceLocation(),
6040 SourceLocation(),
6041 &Context->Idents.get(FieldNames[i]),
6042 FieldTypes[i], /*TInfo=*/0,
6043 /*BitWidth=*/0,
6044 /*Mutable=*/false,
6045 ICIS_NoInit);
6046 Field->setAccess(AS_public);
6047 VaListTagDecl->addDecl(Field);
6048 }
6049 VaListTagDecl->completeDefinition();
6050 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6051 Context->VaListTagTy = VaListTagType;
6052
6053 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006054 TypedefDecl *VaListTagTypedefDecl =
6055 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006056 QualType VaListTagTypedefType =
6057 Context->getTypedefType(VaListTagTypedefDecl);
6058
6059 // typedef __va_list_tag __builtin_va_list[1];
6060 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6061 QualType VaListTagArrayType
6062 = Context->getConstantArrayType(VaListTagTypedefType,
6063 Size, ArrayType::Normal,0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006064
Alp Toker56b5cc92013-12-15 10:36:26 +00006065 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006066}
6067
Meador Inge5d3fb222012-06-16 03:34:49 +00006068static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6069 TargetInfo::BuiltinVaListKind Kind) {
6070 switch (Kind) {
6071 case TargetInfo::CharPtrBuiltinVaList:
6072 return CreateCharPtrBuiltinVaListDecl(Context);
6073 case TargetInfo::VoidPtrBuiltinVaList:
6074 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006075 case TargetInfo::AArch64ABIBuiltinVaList:
6076 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006077 case TargetInfo::PowerABIBuiltinVaList:
6078 return CreatePowerABIBuiltinVaListDecl(Context);
6079 case TargetInfo::X86_64ABIBuiltinVaList:
6080 return CreateX86_64ABIBuiltinVaListDecl(Context);
6081 case TargetInfo::PNaClABIBuiltinVaList:
6082 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006083 case TargetInfo::AAPCSABIBuiltinVaList:
6084 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006085 case TargetInfo::SystemZBuiltinVaList:
6086 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006087 }
6088
6089 llvm_unreachable("Unhandled __builtin_va_list type kind");
6090}
6091
6092TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006093 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006094 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006095 assert(BuiltinVaListDecl->isImplicit());
6096 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006097
6098 return BuiltinVaListDecl;
6099}
6100
Meador Ingecfb60902012-07-01 15:57:25 +00006101QualType ASTContext::getVaListTagType() const {
6102 // Force the creation of VaListTagTy by building the __builtin_va_list
6103 // declaration.
6104 if (VaListTagTy.isNull())
6105 (void) getBuiltinVaListDecl();
6106
6107 return VaListTagTy;
6108}
6109
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006110void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006111 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006112 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006113
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006114 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006115}
6116
John McCalld28ae272009-12-02 08:04:21 +00006117/// \brief Retrieve the template name that corresponds to a non-empty
6118/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006119TemplateName
6120ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6121 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006122 unsigned size = End - Begin;
6123 assert(size > 1 && "set is not overloaded!");
6124
6125 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6126 size * sizeof(FunctionTemplateDecl*));
6127 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6128
6129 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006130 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006131 NamedDecl *D = *I;
6132 assert(isa<FunctionTemplateDecl>(D) ||
6133 (isa<UsingShadowDecl>(D) &&
6134 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6135 *Storage++ = D;
6136 }
6137
6138 return TemplateName(OT);
6139}
6140
Douglas Gregordc572a32009-03-30 22:58:21 +00006141/// \brief Retrieve the template name that represents a qualified
6142/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006143TemplateName
6144ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6145 bool TemplateKeyword,
6146 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006147 assert(NNS && "Missing nested-name-specifier in qualified template name");
6148
Douglas Gregorc42075a2010-02-04 18:10:26 +00006149 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006150 llvm::FoldingSetNodeID ID;
6151 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6152
6153 void *InsertPos = 0;
6154 QualifiedTemplateName *QTN =
6155 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6156 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006157 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6158 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006159 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6160 }
6161
6162 return TemplateName(QTN);
6163}
6164
6165/// \brief Retrieve the template name that represents a dependent
6166/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006167TemplateName
6168ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6169 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006170 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006171 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006172
6173 llvm::FoldingSetNodeID ID;
6174 DependentTemplateName::Profile(ID, NNS, Name);
6175
6176 void *InsertPos = 0;
6177 DependentTemplateName *QTN =
6178 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6179
6180 if (QTN)
6181 return TemplateName(QTN);
6182
6183 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6184 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006185 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6186 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006187 } else {
6188 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006189 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6190 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006191 DependentTemplateName *CheckQTN =
6192 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6193 assert(!CheckQTN && "Dependent type name canonicalization broken");
6194 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006195 }
6196
6197 DependentTemplateNames.InsertNode(QTN, InsertPos);
6198 return TemplateName(QTN);
6199}
6200
Douglas Gregor71395fa2009-11-04 00:56:37 +00006201/// \brief Retrieve the template name that represents a dependent
6202/// template name such as \c MetaFun::template operator+.
6203TemplateName
6204ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006205 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006206 assert((!NNS || NNS->isDependent()) &&
6207 "Nested name specifier must be dependent");
6208
6209 llvm::FoldingSetNodeID ID;
6210 DependentTemplateName::Profile(ID, NNS, Operator);
6211
6212 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006213 DependentTemplateName *QTN
6214 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006215
6216 if (QTN)
6217 return TemplateName(QTN);
6218
6219 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6220 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006221 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6222 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006223 } else {
6224 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006225 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6226 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006227
6228 DependentTemplateName *CheckQTN
6229 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6230 assert(!CheckQTN && "Dependent template name canonicalization broken");
6231 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006232 }
6233
6234 DependentTemplateNames.InsertNode(QTN, InsertPos);
6235 return TemplateName(QTN);
6236}
6237
Douglas Gregor5590be02011-01-15 06:45:20 +00006238TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006239ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6240 TemplateName replacement) const {
6241 llvm::FoldingSetNodeID ID;
6242 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6243
6244 void *insertPos = 0;
6245 SubstTemplateTemplateParmStorage *subst
6246 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6247
6248 if (!subst) {
6249 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6250 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6251 }
6252
6253 return TemplateName(subst);
6254}
6255
6256TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006257ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6258 const TemplateArgument &ArgPack) const {
6259 ASTContext &Self = const_cast<ASTContext &>(*this);
6260 llvm::FoldingSetNodeID ID;
6261 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6262
6263 void *InsertPos = 0;
6264 SubstTemplateTemplateParmPackStorage *Subst
6265 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6266
6267 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006268 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006269 ArgPack.pack_size(),
6270 ArgPack.pack_begin());
6271 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6272 }
6273
6274 return TemplateName(Subst);
6275}
6276
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006277/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006278/// TargetInfo, produce the corresponding type. The unsigned @p Type
6279/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006280CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006281 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006282 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006283 case TargetInfo::SignedChar: return SignedCharTy;
6284 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006285 case TargetInfo::SignedShort: return ShortTy;
6286 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6287 case TargetInfo::SignedInt: return IntTy;
6288 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6289 case TargetInfo::SignedLong: return LongTy;
6290 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6291 case TargetInfo::SignedLongLong: return LongLongTy;
6292 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6293 }
6294
David Blaikie83d382b2011-09-23 05:06:16 +00006295 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006296}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006297
6298//===----------------------------------------------------------------------===//
6299// Type Predicates.
6300//===----------------------------------------------------------------------===//
6301
Fariborz Jahanian96207692009-02-18 21:49:28 +00006302/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6303/// garbage collection attribute.
6304///
John McCall553d45a2011-01-12 00:34:59 +00006305Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006306 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006307 return Qualifiers::GCNone;
6308
David Blaikiebbafb8a2012-03-11 07:00:24 +00006309 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006310 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6311
6312 // Default behaviour under objective-C's gc is for ObjC pointers
6313 // (or pointers to them) be treated as though they were declared
6314 // as __strong.
6315 if (GCAttrs == Qualifiers::GCNone) {
6316 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6317 return Qualifiers::Strong;
6318 else if (Ty->isPointerType())
6319 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6320 } else {
6321 // It's not valid to set GC attributes on anything that isn't a
6322 // pointer.
6323#ifndef NDEBUG
6324 QualType CT = Ty->getCanonicalTypeInternal();
6325 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6326 CT = AT->getElementType();
6327 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6328#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006329 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006330 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006331}
6332
Chris Lattner49af6a42008-04-07 06:51:04 +00006333//===----------------------------------------------------------------------===//
6334// Type Compatibility Testing
6335//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006336
Mike Stump11289f42009-09-09 15:08:12 +00006337/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006338/// compatible.
6339static bool areCompatVectorTypes(const VectorType *LHS,
6340 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006341 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006342 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006343 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006344}
6345
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006346bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6347 QualType SecondVec) {
6348 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6349 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6350
6351 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6352 return true;
6353
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006354 // Treat Neon vector types and most AltiVec vector types as if they are the
6355 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006356 const VectorType *First = FirstVec->getAs<VectorType>();
6357 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006358 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006359 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006360 First->getVectorKind() != VectorType::AltiVecPixel &&
6361 First->getVectorKind() != VectorType::AltiVecBool &&
6362 Second->getVectorKind() != VectorType::AltiVecPixel &&
6363 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006364 return true;
6365
6366 return false;
6367}
6368
Steve Naroff8e6aee52009-07-23 01:01:38 +00006369//===----------------------------------------------------------------------===//
6370// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6371//===----------------------------------------------------------------------===//
6372
6373/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6374/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006375bool
6376ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6377 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006378 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006379 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006380 for (auto *PI : rProto->protocols())
6381 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006382 return true;
6383 return false;
6384}
6385
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006386/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6387/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006388bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6389 QualType rhs) {
6390 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6391 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6392 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6393
Aaron Ballman83731462014-03-17 16:14:00 +00006394 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006395 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006396 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006397 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6398 match = true;
6399 break;
6400 }
6401 }
6402 if (!match)
6403 return false;
6404 }
6405 return true;
6406}
6407
Steve Naroff8e6aee52009-07-23 01:01:38 +00006408/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6409/// ObjCQualifiedIDType.
6410bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6411 bool compare) {
6412 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006413 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006414 lhs->isObjCIdType() || lhs->isObjCClassType())
6415 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006416 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006417 rhs->isObjCIdType() || rhs->isObjCClassType())
6418 return true;
6419
6420 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006421 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006422
Steve Naroff8e6aee52009-07-23 01:01:38 +00006423 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006424
Steve Naroff8e6aee52009-07-23 01:01:38 +00006425 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006426 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006427 // make sure we check the class hierarchy.
6428 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006429 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006430 // when comparing an id<P> on lhs with a static type on rhs,
6431 // see if static class implements all of id's protocols, directly or
6432 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006433 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006434 return false;
6435 }
6436 }
6437 // If there are no qualifiers and no interface, we have an 'id'.
6438 return true;
6439 }
Mike Stump11289f42009-09-09 15:08:12 +00006440 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006441 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006442 bool match = false;
6443
6444 // when comparing an id<P> on lhs with a static type on rhs,
6445 // see if static class implements all of id's protocols, directly or
6446 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006447 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006448 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6449 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6450 match = true;
6451 break;
6452 }
6453 }
Mike Stump11289f42009-09-09 15:08:12 +00006454 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006455 // make sure we check the class hierarchy.
6456 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006457 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006458 // when comparing an id<P> on lhs with a static type on rhs,
6459 // see if static class implements all of id's protocols, directly or
6460 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006461 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006462 match = true;
6463 break;
6464 }
6465 }
6466 }
6467 if (!match)
6468 return false;
6469 }
Mike Stump11289f42009-09-09 15:08:12 +00006470
Steve Naroff8e6aee52009-07-23 01:01:38 +00006471 return true;
6472 }
Mike Stump11289f42009-09-09 15:08:12 +00006473
Steve Naroff8e6aee52009-07-23 01:01:38 +00006474 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6475 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6476
Mike Stump11289f42009-09-09 15:08:12 +00006477 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006478 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006479 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006480 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006481 bool match = false;
6482
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006483 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006484 // see if static class implements all of id's protocols, directly or
6485 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006486 // First, lhs protocols in the qualifier list must be found, direct
6487 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00006488 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006489 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6490 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6491 match = true;
6492 break;
6493 }
6494 }
6495 if (!match)
6496 return false;
6497 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006498
6499 // Static class's protocols, or its super class or category protocols
6500 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6501 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6502 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6503 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6504 // This is rather dubious but matches gcc's behavior. If lhs has
6505 // no type qualifier and its class has no static protocol(s)
6506 // assume that it is mismatch.
6507 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6508 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00006509 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006510 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006511 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006512 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6513 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6514 match = true;
6515 break;
6516 }
6517 }
6518 if (!match)
6519 return false;
6520 }
6521 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006522 return true;
6523 }
6524 return false;
6525}
6526
Eli Friedman47f77112008-08-22 00:56:42 +00006527/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006528/// compatible for assignment from RHS to LHS. This handles validation of any
6529/// protocol qualifiers on the LHS or RHS.
6530///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006531bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6532 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006533 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6534 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6535
Steve Naroff1329fa02009-07-15 18:40:39 +00006536 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006537 if (LHS->isObjCUnqualifiedIdOrClass() ||
6538 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006539 return true;
6540
John McCall8b07ec22010-05-15 11:32:37 +00006541 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006542 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6543 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006544 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006545
6546 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6547 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6548 QualType(RHSOPT,0));
6549
John McCall8b07ec22010-05-15 11:32:37 +00006550 // If we have 2 user-defined types, fall into that path.
6551 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006552 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006553
Steve Naroff8e6aee52009-07-23 01:01:38 +00006554 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006555}
6556
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006557/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006558/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006559/// arguments in block literals. When passed as arguments, passing 'A*' where
6560/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6561/// not OK. For the return type, the opposite is not OK.
6562bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6563 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006564 const ObjCObjectPointerType *RHSOPT,
6565 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006566 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006567 return true;
6568
6569 if (LHSOPT->isObjCBuiltinType()) {
6570 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6571 }
6572
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006573 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006574 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6575 QualType(RHSOPT,0),
6576 false);
6577
6578 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6579 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6580 if (LHS && RHS) { // We have 2 user-defined types.
6581 if (LHS != RHS) {
6582 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006583 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006584 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006585 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006586 }
6587 else
6588 return true;
6589 }
6590 return false;
6591}
6592
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006593/// getIntersectionOfProtocols - This routine finds the intersection of set
6594/// of protocols inherited from two distinct objective-c pointer objects.
6595/// It is used to build composite qualifier list of the composite type of
6596/// the conditional expression involving two objective-c pointer objects.
6597static
6598void getIntersectionOfProtocols(ASTContext &Context,
6599 const ObjCObjectPointerType *LHSOPT,
6600 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006601 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006602
John McCall8b07ec22010-05-15 11:32:37 +00006603 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6604 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6605 assert(LHS->getInterface() && "LHS must have an interface base");
6606 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006607
6608 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6609 unsigned LHSNumProtocols = LHS->getNumProtocols();
6610 if (LHSNumProtocols > 0)
6611 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6612 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006613 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006614 Context.CollectInheritedProtocols(LHS->getInterface(),
6615 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006616 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6617 LHSInheritedProtocols.end());
6618 }
6619
6620 unsigned RHSNumProtocols = RHS->getNumProtocols();
6621 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006622 ObjCProtocolDecl **RHSProtocols =
6623 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006624 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6625 if (InheritedProtocolSet.count(RHSProtocols[i]))
6626 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006627 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006628 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006629 Context.CollectInheritedProtocols(RHS->getInterface(),
6630 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006631 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6632 RHSInheritedProtocols.begin(),
6633 E = RHSInheritedProtocols.end(); I != E; ++I)
6634 if (InheritedProtocolSet.count((*I)))
6635 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006636 }
6637}
6638
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006639/// areCommonBaseCompatible - Returns common base class of the two classes if
6640/// one found. Note that this is O'2 algorithm. But it will be called as the
6641/// last type comparison in a ?-exp of ObjC pointer types before a
6642/// warning is issued. So, its invokation is extremely rare.
6643QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006644 const ObjCObjectPointerType *Lptr,
6645 const ObjCObjectPointerType *Rptr) {
6646 const ObjCObjectType *LHS = Lptr->getObjectType();
6647 const ObjCObjectType *RHS = Rptr->getObjectType();
6648 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6649 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006650 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006651 return QualType();
6652
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006653 do {
John McCall8b07ec22010-05-15 11:32:37 +00006654 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006655 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006656 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006657 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6658
6659 QualType Result = QualType(LHS, 0);
6660 if (!Protocols.empty())
6661 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6662 Result = getObjCObjectPointerType(Result);
6663 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006664 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006665 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006666
6667 return QualType();
6668}
6669
John McCall8b07ec22010-05-15 11:32:37 +00006670bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6671 const ObjCObjectType *RHS) {
6672 assert(LHS->getInterface() && "LHS is not an interface type");
6673 assert(RHS->getInterface() && "RHS is not an interface type");
6674
Chris Lattner49af6a42008-04-07 06:51:04 +00006675 // Verify that the base decls are compatible: the RHS must be a subclass of
6676 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006677 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006678 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006679
Chris Lattner49af6a42008-04-07 06:51:04 +00006680 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6681 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006682 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006683 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006684
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006685 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6686 // more detailed analysis is required.
6687 if (RHS->getNumProtocols() == 0) {
6688 // OK, if LHS is a superclass of RHS *and*
6689 // this superclass is assignment compatible with LHS.
6690 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006691 bool IsSuperClass =
6692 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6693 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006694 // OK if conversion of LHS to SuperClass results in narrowing of types
6695 // ; i.e., SuperClass may implement at least one of the protocols
6696 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6697 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6698 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006699 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006700 // If super class has no protocols, it is not a match.
6701 if (SuperClassInheritedProtocols.empty())
6702 return false;
6703
Aaron Ballman1683f7b2014-03-17 15:55:30 +00006704 for (const auto *LHSProto : LHS->quals()) {
6705 bool SuperImplementsProtocol = false;
6706 for (auto *SuperClassProto : SuperClassInheritedProtocols) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006707 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6708 SuperImplementsProtocol = true;
6709 break;
6710 }
6711 }
6712 if (!SuperImplementsProtocol)
6713 return false;
6714 }
6715 return true;
6716 }
6717 return false;
6718 }
Mike Stump11289f42009-09-09 15:08:12 +00006719
Aaron Ballman1683f7b2014-03-17 15:55:30 +00006720 for (const auto *LHSPI : LHS->quals()) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006721 bool RHSImplementsProtocol = false;
6722
6723 // If the RHS doesn't implement the protocol on the left, the types
6724 // are incompatible.
Aaron Ballman1683f7b2014-03-17 15:55:30 +00006725 for (auto *RHSPI : RHS->quals()) {
6726 if (RHSPI->lookupProtocolNamed(LHSPI->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006727 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006728 break;
6729 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006730 }
6731 // FIXME: For better diagnostics, consider passing back the protocol name.
6732 if (!RHSImplementsProtocol)
6733 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006734 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006735 // The RHS implements all protocols listed on the LHS.
6736 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006737}
6738
Steve Naroffb7605152009-02-12 17:52:19 +00006739bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6740 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006741 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6742 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006743
Steve Naroff7cae42b2009-07-10 23:34:53 +00006744 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006745 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006746
6747 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6748 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006749}
6750
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006751bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6752 return canAssignObjCInterfaces(
6753 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6754 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6755}
6756
Mike Stump11289f42009-09-09 15:08:12 +00006757/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006758/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006759/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006760/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006761bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6762 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006763 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006764 return hasSameType(LHS, RHS);
6765
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006766 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006767}
6768
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006769bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006770 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006771}
6772
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006773bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6774 return !mergeTypes(LHS, RHS, true).isNull();
6775}
6776
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006777/// mergeTransparentUnionType - if T is a transparent union type and a member
6778/// of T is compatible with SubType, return the merged type, else return
6779/// QualType()
6780QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6781 bool OfBlockPointer,
6782 bool Unqualified) {
6783 if (const RecordType *UT = T->getAsUnionType()) {
6784 RecordDecl *UD = UT->getDecl();
6785 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006786 for (const auto *I : UD->fields()) {
6787 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006788 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6789 if (!MT.isNull())
6790 return MT;
6791 }
6792 }
6793 }
6794
6795 return QualType();
6796}
6797
Alp Toker9cacbab2014-01-20 20:26:09 +00006798/// mergeFunctionParameterTypes - merge two types which appear as function
6799/// parameter types
6800QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
6801 bool OfBlockPointer,
6802 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006803 // GNU extension: two types are compatible if they appear as a function
6804 // argument, one of the types is a transparent union type and the other
6805 // type is compatible with a union member
6806 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6807 Unqualified);
6808 if (!lmerge.isNull())
6809 return lmerge;
6810
6811 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6812 Unqualified);
6813 if (!rmerge.isNull())
6814 return rmerge;
6815
6816 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6817}
6818
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006819QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006820 bool OfBlockPointer,
6821 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006822 const FunctionType *lbase = lhs->getAs<FunctionType>();
6823 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006824 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6825 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006826 bool allLTypes = true;
6827 bool allRTypes = true;
6828
6829 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006830 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006831 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00006832 QualType RHS = rbase->getReturnType();
6833 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00006834 bool UnqualifiedResult = Unqualified;
6835 if (!UnqualifiedResult)
6836 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006837 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006838 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006839 else
Alp Toker314cc812014-01-25 16:55:45 +00006840 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00006841 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006842 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006843
6844 if (Unqualified)
6845 retType = retType.getUnqualifiedType();
6846
Alp Toker314cc812014-01-25 16:55:45 +00006847 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
6848 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006849 if (Unqualified) {
6850 LRetType = LRetType.getUnqualifiedType();
6851 RRetType = RRetType.getUnqualifiedType();
6852 }
6853
6854 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006855 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006856 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006857 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006858
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006859 // FIXME: double check this
6860 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6861 // rbase->getRegParmAttr() != 0 &&
6862 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006863 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6864 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006865
Douglas Gregor8c940862010-01-18 17:14:39 +00006866 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00006867 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00006868 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006869
John McCall8c6b56f2010-12-15 01:06:38 +00006870 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006871 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6872 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006873 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6874 return QualType();
6875
John McCall31168b02011-06-15 23:02:42 +00006876 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6877 return QualType();
6878
John McCall8c6b56f2010-12-15 01:06:38 +00006879 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6880 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006881
Rafael Espindola8778c282012-11-29 16:09:03 +00006882 if (lbaseInfo.getNoReturn() != NoReturn)
6883 allLTypes = false;
6884 if (rbaseInfo.getNoReturn() != NoReturn)
6885 allRTypes = false;
6886
John McCall31168b02011-06-15 23:02:42 +00006887 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006888
Eli Friedman47f77112008-08-22 00:56:42 +00006889 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006890 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6891 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00006892 // Compatible functions must have the same number of parameters
6893 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00006894 return QualType();
6895
6896 // Variadic and non-variadic functions aren't compatible
6897 if (lproto->isVariadic() != rproto->isVariadic())
6898 return QualType();
6899
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006900 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6901 return QualType();
6902
Fariborz Jahanian97676972011-09-28 21:52:05 +00006903 if (LangOpts.ObjCAutoRefCount &&
6904 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6905 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00006906
6907 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006908 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00006909 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
6910 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
6911 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
6912 QualType paramType = mergeFunctionParameterTypes(
6913 lParamType, rParamType, OfBlockPointer, Unqualified);
6914 if (paramType.isNull())
6915 return QualType();
6916
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006917 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00006918 paramType = paramType.getUnqualifiedType();
6919
6920 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006921 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00006922 lParamType = lParamType.getUnqualifiedType();
6923 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006924 }
Alp Toker601b22c2014-01-21 23:35:24 +00006925
6926 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00006927 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00006928 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00006929 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006930 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006931
Eli Friedman47f77112008-08-22 00:56:42 +00006932 if (allLTypes) return lhs;
6933 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006934
6935 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6936 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00006937 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006938 }
6939
6940 if (lproto) allRTypes = false;
6941 if (rproto) allLTypes = false;
6942
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006943 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006944 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006945 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006946 if (proto->isVariadic()) return QualType();
6947 // Check that the types are compatible with the types that
6948 // would result from default argument promotions (C99 6.7.5.3p15).
6949 // The only types actually affected are promotable integer
6950 // types and floats, which would be passed as a different
6951 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00006952 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
6953 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00006954
Eli Friedman448ce402012-08-30 00:44:15 +00006955 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00006956 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00006957 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
6958 paramTy = Enum->getDecl()->getIntegerType();
6959 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00006960 return QualType();
6961 }
Alp Toker601b22c2014-01-21 23:35:24 +00006962
6963 if (paramTy->isPromotableIntegerType() ||
6964 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00006965 return QualType();
6966 }
6967
6968 if (allLTypes) return lhs;
6969 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006970
6971 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6972 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00006973 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006974 }
6975
6976 if (allLTypes) return lhs;
6977 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00006978 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00006979}
6980
John McCall433c2e62013-03-21 00:10:07 +00006981/// Given that we have an enum type and a non-enum type, try to merge them.
6982static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
6983 QualType other, bool isBlockReturnType) {
6984 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
6985 // a signed integer type, or an unsigned integer type.
6986 // Compatibility is based on the underlying type, not the promotion
6987 // type.
6988 QualType underlyingType = ET->getDecl()->getIntegerType();
6989 if (underlyingType.isNull()) return QualType();
6990 if (Context.hasSameType(underlyingType, other))
6991 return other;
6992
6993 // In block return types, we're more permissive and accept any
6994 // integral type of the same size.
6995 if (isBlockReturnType && other->isIntegerType() &&
6996 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
6997 return other;
6998
6999 return QualType();
7000}
7001
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007002QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007003 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007004 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007005 // C++ [expr]: If an expression initially has the type "reference to T", the
7006 // type is adjusted to "T" prior to any further analysis, the expression
7007 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007008 // expression is an lvalue unless the reference is an rvalue reference and
7009 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007010 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7011 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007012
7013 if (Unqualified) {
7014 LHS = LHS.getUnqualifiedType();
7015 RHS = RHS.getUnqualifiedType();
7016 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007017
Eli Friedman47f77112008-08-22 00:56:42 +00007018 QualType LHSCan = getCanonicalType(LHS),
7019 RHSCan = getCanonicalType(RHS);
7020
7021 // If two types are identical, they are compatible.
7022 if (LHSCan == RHSCan)
7023 return LHS;
7024
John McCall8ccfcb52009-09-24 19:53:00 +00007025 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007026 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7027 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007028 if (LQuals != RQuals) {
7029 // If any of these qualifiers are different, we have a type
7030 // mismatch.
7031 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007032 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7033 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007034 return QualType();
7035
7036 // Exactly one GC qualifier difference is allowed: __strong is
7037 // okay if the other type has no GC qualifier but is an Objective
7038 // C object pointer (i.e. implicitly strong by default). We fix
7039 // this by pretending that the unqualified type was actually
7040 // qualified __strong.
7041 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7042 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7043 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7044
7045 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7046 return QualType();
7047
7048 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7049 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7050 }
7051 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7052 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7053 }
Eli Friedman47f77112008-08-22 00:56:42 +00007054 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007055 }
7056
7057 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007058
Eli Friedmandcca6332009-06-01 01:22:52 +00007059 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7060 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007061
Chris Lattnerfd652912008-01-14 05:45:46 +00007062 // We want to consider the two function types to be the same for these
7063 // comparisons, just force one to the other.
7064 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7065 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007066
7067 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007068 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7069 LHSClass = Type::ConstantArray;
7070 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7071 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007072
John McCall8b07ec22010-05-15 11:32:37 +00007073 // ObjCInterfaces are just specialized ObjCObjects.
7074 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7075 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7076
Nate Begemance4d7fc2008-04-18 23:10:10 +00007077 // Canonicalize ExtVector -> Vector.
7078 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7079 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007080
Chris Lattner95554662008-04-07 05:43:21 +00007081 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007082 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007083 // Note that we only have special rules for turning block enum
7084 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007085 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007086 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007087 }
John McCall9dd450b2009-09-21 23:43:11 +00007088 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007089 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007090 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007091 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007092 if (OfBlockPointer && !BlockReturnType) {
7093 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7094 return LHS;
7095 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7096 return RHS;
7097 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007098
Eli Friedman47f77112008-08-22 00:56:42 +00007099 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007100 }
Eli Friedman47f77112008-08-22 00:56:42 +00007101
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007102 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007103 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007104#define TYPE(Class, Base)
7105#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007106#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007107#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7108#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7109#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007110 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007111
Richard Smith27d807c2013-04-30 13:56:41 +00007112 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007113 case Type::LValueReference:
7114 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007115 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007116 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007117
John McCall8b07ec22010-05-15 11:32:37 +00007118 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007119 case Type::IncompleteArray:
7120 case Type::VariableArray:
7121 case Type::FunctionProto:
7122 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007123 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007124
Chris Lattnerfd652912008-01-14 05:45:46 +00007125 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007126 {
7127 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007128 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7129 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007130 if (Unqualified) {
7131 LHSPointee = LHSPointee.getUnqualifiedType();
7132 RHSPointee = RHSPointee.getUnqualifiedType();
7133 }
7134 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7135 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007136 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007137 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007138 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007139 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007140 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007141 return getPointerType(ResultType);
7142 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007143 case Type::BlockPointer:
7144 {
7145 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007146 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7147 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007148 if (Unqualified) {
7149 LHSPointee = LHSPointee.getUnqualifiedType();
7150 RHSPointee = RHSPointee.getUnqualifiedType();
7151 }
7152 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7153 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007154 if (ResultType.isNull()) return QualType();
7155 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7156 return LHS;
7157 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7158 return RHS;
7159 return getBlockPointerType(ResultType);
7160 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007161 case Type::Atomic:
7162 {
7163 // Merge two pointer types, while trying to preserve typedef info
7164 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7165 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7166 if (Unqualified) {
7167 LHSValue = LHSValue.getUnqualifiedType();
7168 RHSValue = RHSValue.getUnqualifiedType();
7169 }
7170 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7171 Unqualified);
7172 if (ResultType.isNull()) return QualType();
7173 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7174 return LHS;
7175 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7176 return RHS;
7177 return getAtomicType(ResultType);
7178 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007179 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007180 {
7181 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7182 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7183 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7184 return QualType();
7185
7186 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7187 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007188 if (Unqualified) {
7189 LHSElem = LHSElem.getUnqualifiedType();
7190 RHSElem = RHSElem.getUnqualifiedType();
7191 }
7192
7193 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007194 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007195 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7196 return LHS;
7197 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7198 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007199 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7200 ArrayType::ArraySizeModifier(), 0);
7201 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7202 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007203 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7204 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007205 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7206 return LHS;
7207 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7208 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007209 if (LVAT) {
7210 // FIXME: This isn't correct! But tricky to implement because
7211 // the array's size has to be the size of LHS, but the type
7212 // has to be different.
7213 return LHS;
7214 }
7215 if (RVAT) {
7216 // FIXME: This isn't correct! But tricky to implement because
7217 // the array's size has to be the size of RHS, but the type
7218 // has to be different.
7219 return RHS;
7220 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007221 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7222 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007223 return getIncompleteArrayType(ResultType,
7224 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007225 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007226 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007227 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007228 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007229 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007230 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007231 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007232 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007233 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007234 case Type::Complex:
7235 // Distinct complex types are incompatible.
7236 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007237 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007238 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007239 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7240 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007241 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007242 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007243 case Type::ObjCObject: {
7244 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007245 // FIXME: This should be type compatibility, e.g. whether
7246 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007247 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7248 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7249 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007250 return LHS;
7251
Eli Friedman47f77112008-08-22 00:56:42 +00007252 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007253 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007254 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007255 if (OfBlockPointer) {
7256 if (canAssignObjCInterfacesInBlockPointer(
7257 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007258 RHS->getAs<ObjCObjectPointerType>(),
7259 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007260 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007261 return QualType();
7262 }
John McCall9dd450b2009-09-21 23:43:11 +00007263 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7264 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007265 return LHS;
7266
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007267 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007268 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007269 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007270
David Blaikie8a40f702012-01-17 06:56:22 +00007271 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007272}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007273
Fariborz Jahanian97676972011-09-28 21:52:05 +00007274bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7275 const FunctionProtoType *FromFunctionType,
7276 const FunctionProtoType *ToFunctionType) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007277 if (FromFunctionType->hasAnyConsumedParams() !=
7278 ToFunctionType->hasAnyConsumedParams())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007279 return false;
7280 FunctionProtoType::ExtProtoInfo FromEPI =
7281 FromFunctionType->getExtProtoInfo();
7282 FunctionProtoType::ExtProtoInfo ToEPI =
7283 ToFunctionType->getExtProtoInfo();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007284 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
Alp Toker601b22c2014-01-21 23:35:24 +00007285 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7286 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
Fariborz Jahanian97676972011-09-28 21:52:05 +00007287 return false;
7288 }
7289 return true;
7290}
7291
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007292/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7293/// 'RHS' attributes and returns the merged version; including for function
7294/// return types.
7295QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7296 QualType LHSCan = getCanonicalType(LHS),
7297 RHSCan = getCanonicalType(RHS);
7298 // If two types are identical, they are compatible.
7299 if (LHSCan == RHSCan)
7300 return LHS;
7301 if (RHSCan->isFunctionType()) {
7302 if (!LHSCan->isFunctionType())
7303 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007304 QualType OldReturnType =
7305 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007306 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007307 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007308 QualType ResReturnType =
7309 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7310 if (ResReturnType.isNull())
7311 return QualType();
7312 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7313 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7314 // In either case, use OldReturnType to build the new function type.
7315 const FunctionType *F = LHS->getAs<FunctionType>();
7316 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007317 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7318 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007319 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007320 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007321 return ResultType;
7322 }
7323 }
7324 return QualType();
7325 }
7326
7327 // If the qualifiers are different, the types can still be merged.
7328 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7329 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7330 if (LQuals != RQuals) {
7331 // If any of these qualifiers are different, we have a type mismatch.
7332 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7333 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7334 return QualType();
7335
7336 // Exactly one GC qualifier difference is allowed: __strong is
7337 // okay if the other type has no GC qualifier but is an Objective
7338 // C object pointer (i.e. implicitly strong by default). We fix
7339 // this by pretending that the unqualified type was actually
7340 // qualified __strong.
7341 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7342 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7343 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7344
7345 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7346 return QualType();
7347
7348 if (GC_L == Qualifiers::Strong)
7349 return LHS;
7350 if (GC_R == Qualifiers::Strong)
7351 return RHS;
7352 return QualType();
7353 }
7354
7355 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7356 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7357 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7358 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7359 if (ResQT == LHSBaseQT)
7360 return LHS;
7361 if (ResQT == RHSBaseQT)
7362 return RHS;
7363 }
7364 return QualType();
7365}
7366
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007367//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007368// Integer Predicates
7369//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007370
Jay Foad39c79802011-01-12 09:06:06 +00007371unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007372 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007373 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007374 if (T->isBooleanType())
7375 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007376 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007377 return (unsigned)getTypeSize(T);
7378}
7379
Abramo Bagnara13640492012-09-09 10:21:24 +00007380QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007381 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007382
7383 // Turn <4 x signed int> -> <4 x unsigned int>
7384 if (const VectorType *VTy = T->getAs<VectorType>())
7385 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007386 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007387
7388 // For enums, we return the unsigned version of the base type.
7389 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007390 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007391
7392 const BuiltinType *BTy = T->getAs<BuiltinType>();
7393 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007394 switch (BTy->getKind()) {
7395 case BuiltinType::Char_S:
7396 case BuiltinType::SChar:
7397 return UnsignedCharTy;
7398 case BuiltinType::Short:
7399 return UnsignedShortTy;
7400 case BuiltinType::Int:
7401 return UnsignedIntTy;
7402 case BuiltinType::Long:
7403 return UnsignedLongTy;
7404 case BuiltinType::LongLong:
7405 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007406 case BuiltinType::Int128:
7407 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007408 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007409 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007410 }
7411}
7412
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007413ASTMutationListener::~ASTMutationListener() { }
7414
Richard Smith1fa5d642013-05-11 05:45:24 +00007415void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7416 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007417
7418//===----------------------------------------------------------------------===//
7419// Builtin Type Computation
7420//===----------------------------------------------------------------------===//
7421
7422/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007423/// pointer over the consumed characters. This returns the resultant type. If
7424/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7425/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7426/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007427///
7428/// RequiresICE is filled in on return to indicate whether the value is required
7429/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007430static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007431 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007432 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007433 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007434 // Modifiers.
7435 int HowLong = 0;
7436 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007437 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007438
Chris Lattnerdc226c22010-10-01 22:42:38 +00007439 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007440 bool Done = false;
7441 while (!Done) {
7442 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007443 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007444 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007445 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007446 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007447 case 'S':
7448 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7449 assert(!Signed && "Can't use 'S' modifier multiple times!");
7450 Signed = true;
7451 break;
7452 case 'U':
7453 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7454 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7455 Unsigned = true;
7456 break;
7457 case 'L':
7458 assert(HowLong <= 2 && "Can't have LLLL modifier");
7459 ++HowLong;
7460 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00007461 case 'W':
7462 // This modifier represents int64 type.
7463 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7464 switch (Context.getTargetInfo().getInt64Type()) {
7465 default:
7466 llvm_unreachable("Unexpected integer type");
7467 case TargetInfo::SignedLong:
7468 HowLong = 1;
7469 break;
7470 case TargetInfo::SignedLongLong:
7471 HowLong = 2;
7472 break;
7473 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00007474 }
7475 }
7476
7477 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007478
Chris Lattnerecd79c62009-06-14 00:45:47 +00007479 // Read the base type.
7480 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007481 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007482 case 'v':
7483 assert(HowLong == 0 && !Signed && !Unsigned &&
7484 "Bad modifiers used with 'v'!");
7485 Type = Context.VoidTy;
7486 break;
Jack Carter24bef982013-08-15 15:16:57 +00007487 case 'h':
7488 assert(HowLong == 0 && !Signed && !Unsigned &&
7489 "Bad modifiers used with 'f'!");
7490 Type = Context.HalfTy;
7491 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007492 case 'f':
7493 assert(HowLong == 0 && !Signed && !Unsigned &&
7494 "Bad modifiers used with 'f'!");
7495 Type = Context.FloatTy;
7496 break;
7497 case 'd':
7498 assert(HowLong < 2 && !Signed && !Unsigned &&
7499 "Bad modifiers used with 'd'!");
7500 if (HowLong)
7501 Type = Context.LongDoubleTy;
7502 else
7503 Type = Context.DoubleTy;
7504 break;
7505 case 's':
7506 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7507 if (Unsigned)
7508 Type = Context.UnsignedShortTy;
7509 else
7510 Type = Context.ShortTy;
7511 break;
7512 case 'i':
7513 if (HowLong == 3)
7514 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7515 else if (HowLong == 2)
7516 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7517 else if (HowLong == 1)
7518 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7519 else
7520 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7521 break;
7522 case 'c':
7523 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7524 if (Signed)
7525 Type = Context.SignedCharTy;
7526 else if (Unsigned)
7527 Type = Context.UnsignedCharTy;
7528 else
7529 Type = Context.CharTy;
7530 break;
7531 case 'b': // boolean
7532 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7533 Type = Context.BoolTy;
7534 break;
7535 case 'z': // size_t.
7536 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7537 Type = Context.getSizeType();
7538 break;
7539 case 'F':
7540 Type = Context.getCFConstantStringType();
7541 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007542 case 'G':
7543 Type = Context.getObjCIdType();
7544 break;
7545 case 'H':
7546 Type = Context.getObjCSelType();
7547 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007548 case 'M':
7549 Type = Context.getObjCSuperType();
7550 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007551 case 'a':
7552 Type = Context.getBuiltinVaListType();
7553 assert(!Type.isNull() && "builtin va list type not initialized!");
7554 break;
7555 case 'A':
7556 // This is a "reference" to a va_list; however, what exactly
7557 // this means depends on how va_list is defined. There are two
7558 // different kinds of va_list: ones passed by value, and ones
7559 // passed by reference. An example of a by-value va_list is
7560 // x86, where va_list is a char*. An example of by-ref va_list
7561 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7562 // we want this argument to be a char*&; for x86-64, we want
7563 // it to be a __va_list_tag*.
7564 Type = Context.getBuiltinVaListType();
7565 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007566 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007567 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007568 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007569 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007570 break;
7571 case 'V': {
7572 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007573 unsigned NumElements = strtoul(Str, &End, 10);
7574 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007575 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007576
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007577 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7578 RequiresICE, false);
7579 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007580
7581 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007582 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007583 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007584 break;
7585 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007586 case 'E': {
7587 char *End;
7588
7589 unsigned NumElements = strtoul(Str, &End, 10);
7590 assert(End != Str && "Missing vector size");
7591
7592 Str = End;
7593
7594 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7595 false);
7596 Type = Context.getExtVectorType(ElementType, NumElements);
7597 break;
7598 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007599 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007600 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7601 false);
7602 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007603 Type = Context.getComplexType(ElementType);
7604 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007605 }
7606 case 'Y' : {
7607 Type = Context.getPointerDiffType();
7608 break;
7609 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007610 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007611 Type = Context.getFILEType();
7612 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007613 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007614 return QualType();
7615 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007616 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007617 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007618 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007619 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007620 else
7621 Type = Context.getjmp_bufType();
7622
Mike Stump2adb4da2009-07-28 23:47:15 +00007623 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007624 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007625 return QualType();
7626 }
7627 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007628 case 'K':
7629 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7630 Type = Context.getucontext_tType();
7631
7632 if (Type.isNull()) {
7633 Error = ASTContext::GE_Missing_ucontext;
7634 return QualType();
7635 }
7636 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007637 case 'p':
7638 Type = Context.getProcessIDType();
7639 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007640 }
Mike Stump11289f42009-09-09 15:08:12 +00007641
Chris Lattnerdc226c22010-10-01 22:42:38 +00007642 // If there are modifiers and if we're allowed to parse them, go for it.
7643 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007644 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007645 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007646 default: Done = true; --Str; break;
7647 case '*':
7648 case '&': {
7649 // Both pointers and references can have their pointee types
7650 // qualified with an address space.
7651 char *End;
7652 unsigned AddrSpace = strtoul(Str, &End, 10);
7653 if (End != Str && AddrSpace != 0) {
7654 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7655 Str = End;
7656 }
7657 if (c == '*')
7658 Type = Context.getPointerType(Type);
7659 else
7660 Type = Context.getLValueReferenceType(Type);
7661 break;
7662 }
7663 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7664 case 'C':
7665 Type = Type.withConst();
7666 break;
7667 case 'D':
7668 Type = Context.getVolatileType(Type);
7669 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007670 case 'R':
7671 Type = Type.withRestrict();
7672 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007673 }
7674 }
Chris Lattner84733392010-10-01 07:13:18 +00007675
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007676 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007677 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007678
Chris Lattnerecd79c62009-06-14 00:45:47 +00007679 return Type;
7680}
7681
7682/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007683QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007684 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007685 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007686 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007687
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007688 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007689
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007690 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007691 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007692 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7693 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007694 if (Error != GE_None)
7695 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007696
7697 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7698
Chris Lattnerecd79c62009-06-14 00:45:47 +00007699 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007700 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007701 if (Error != GE_None)
7702 return QualType();
7703
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007704 // If this argument is required to be an IntegerConstantExpression and the
7705 // caller cares, fill in the bitmask we return.
7706 if (RequiresICE && IntegerConstantArgs)
7707 *IntegerConstantArgs |= 1 << ArgTypes.size();
7708
Chris Lattnerecd79c62009-06-14 00:45:47 +00007709 // Do array -> pointer decay. The builtin should use the decayed type.
7710 if (Ty->isArrayType())
7711 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007712
Chris Lattnerecd79c62009-06-14 00:45:47 +00007713 ArgTypes.push_back(Ty);
7714 }
7715
7716 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7717 "'.' should only occur at end of builtin type list!");
7718
Reid Kleckner78af0702013-08-27 23:08:25 +00007719 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00007720 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7721
7722 bool Variadic = (TypeStr[0] == '.');
7723
7724 // We really shouldn't be making a no-proto type here, especially in C++.
7725 if (ArgTypes.empty() && Variadic)
7726 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007727
John McCalldb40c7f2010-12-14 08:05:40 +00007728 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007729 EPI.ExtInfo = EI;
7730 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007731
Jordan Rose5c382722013-03-08 21:51:21 +00007732 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007733}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007734
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007735GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007736 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007737 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007738
Rafael Espindola3ae00052013-05-13 00:12:11 +00007739 GVALinkage External = GVA_StrongExternal;
7740 switch (FD->getTemplateSpecializationKind()) {
7741 case TSK_Undeclared:
7742 case TSK_ExplicitSpecialization:
7743 External = GVA_StrongExternal;
7744 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007745
Rafael Espindola3ae00052013-05-13 00:12:11 +00007746 case TSK_ExplicitInstantiationDefinition:
7747 return GVA_ExplicitTemplateInstantiation;
7748
7749 case TSK_ExplicitInstantiationDeclaration:
7750 case TSK_ImplicitInstantiation:
7751 External = GVA_TemplateInstantiation;
7752 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007753 }
7754
7755 if (!FD->isInlined())
7756 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00007757
Alp Tokerbfa39342014-01-14 12:51:41 +00007758 if ((!getLangOpts().CPlusPlus && !getLangOpts().MSVCCompat) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00007759 FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007760 // GNU or C99 inline semantics. Determine whether this symbol should be
7761 // externally visible.
7762 if (FD->isInlineDefinitionExternallyVisible())
7763 return External;
7764
7765 // C99 inline semantics, where the symbol is not externally visible.
7766 return GVA_C99Inline;
7767 }
7768
7769 // C++0x [temp.explicit]p9:
7770 // [ Note: The intent is that an inline function that is the subject of
7771 // an explicit instantiation declaration will still be implicitly
7772 // instantiated when used so that the body can be considered for
7773 // inlining, but that no out-of-line copy of the inline function would be
7774 // generated in the translation unit. -- end note ]
7775 if (FD->getTemplateSpecializationKind()
7776 == TSK_ExplicitInstantiationDeclaration)
7777 return GVA_C99Inline;
7778
7779 return GVA_CXXInline;
7780}
7781
7782GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007783 if (!VD->isExternallyVisible())
7784 return GVA_Internal;
7785
Richard Smith8809a0c2013-09-27 20:14:12 +00007786 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007787 case TSK_Undeclared:
7788 case TSK_ExplicitSpecialization:
7789 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007790
Rafael Espindola3ae00052013-05-13 00:12:11 +00007791 case TSK_ExplicitInstantiationDeclaration:
7792 llvm_unreachable("Variable should not be instantiated");
7793 // Fall through to treat this like any other instantiation.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007794
Rafael Espindola3ae00052013-05-13 00:12:11 +00007795 case TSK_ExplicitInstantiationDefinition:
7796 return GVA_ExplicitTemplateInstantiation;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007797
Rafael Espindola3ae00052013-05-13 00:12:11 +00007798 case TSK_ImplicitInstantiation:
7799 return GVA_TemplateInstantiation;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007800 }
Rafael Espindola27699c82013-05-13 14:05:53 +00007801
7802 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007803}
7804
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007805bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007806 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7807 if (!VD->isFileVarDecl())
7808 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00007809 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7810 // We never need to emit an uninstantiated function template.
7811 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7812 return false;
7813 } else
7814 return false;
7815
7816 // If this is a member of a class template, we do not need to emit it.
7817 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007818 return false;
7819
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007820 // Weak references don't produce any output by themselves.
7821 if (D->hasAttr<WeakRefAttr>())
7822 return false;
7823
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007824 // Aliases and used decls are required.
7825 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7826 return true;
7827
7828 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7829 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007830 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007831 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007832
7833 // Constructors and destructors are required.
7834 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7835 return true;
7836
John McCall6bd2a892013-01-25 22:31:03 +00007837 // The key function for a class is required. This rule only comes
7838 // into play when inline functions can be key functions, though.
7839 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7840 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7841 const CXXRecordDecl *RD = MD->getParent();
7842 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7843 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7844 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7845 return true;
7846 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007847 }
7848 }
7849
7850 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7851
7852 // static, static inline, always_inline, and extern inline functions can
7853 // always be deferred. Normal inline functions can be deferred in C99/C++.
7854 // Implicit template instantiations can also be deferred in C++.
7855 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007856 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007857 return false;
7858 return true;
7859 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007860
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007861 const VarDecl *VD = cast<VarDecl>(D);
7862 assert(VD->isFileVarDecl() && "Expected file scoped var");
7863
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007864 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7865 return false;
7866
Richard Smitha0e5e542012-11-12 21:38:00 +00007867 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007868 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smitha0e5e542012-11-12 21:38:00 +00007869 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7870 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007871
Richard Smitha0e5e542012-11-12 21:38:00 +00007872 // Variables that have destruction with side-effects are required.
7873 if (VD->getType().isDestructedType())
7874 return true;
7875
7876 // Variables that have initialization with side-effects are required.
7877 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7878 return true;
7879
7880 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007881}
Charles Davis53c59df2010-08-16 03:33:14 +00007882
Reid Kleckner78af0702013-08-27 23:08:25 +00007883CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
7884 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00007885 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00007886 if (IsCXXMethod)
7887 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007888
Reid Kleckner78af0702013-08-27 23:08:25 +00007889 return (LangOpts.MRTD && !IsVariadic) ? CC_X86StdCall : CC_C;
Charles Davis99202b32010-11-09 18:04:24 +00007890}
7891
Jay Foad39c79802011-01-12 09:06:06 +00007892bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007893 // Pass through to the C++ ABI object
7894 return ABI->isNearlyEmpty(RD);
7895}
7896
Reid Kleckner96f8f932014-02-05 17:27:08 +00007897VTableContextBase *ASTContext::getVTableContext() {
7898 if (!VTContext.get()) {
7899 if (Target->getCXXABI().isMicrosoft())
7900 VTContext.reset(new MicrosoftVTableContext(*this));
7901 else
7902 VTContext.reset(new ItaniumVTableContext(*this));
7903 }
7904 return VTContext.get();
7905}
7906
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007907MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00007908 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00007909 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00007910 case TargetCXXABI::GenericItanium:
7911 case TargetCXXABI::GenericARM:
7912 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00007913 case TargetCXXABI::iOS64:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00007914 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00007915 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00007916 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007917 }
David Blaikie83d382b2011-09-23 05:06:16 +00007918 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007919}
7920
Charles Davis53c59df2010-08-16 03:33:14 +00007921CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007922
7923size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00007924 return ASTRecordLayouts.getMemorySize() +
7925 llvm::capacity_in_bytes(ObjCLayouts) +
7926 llvm::capacity_in_bytes(KeyFunctions) +
7927 llvm::capacity_in_bytes(ObjCImpls) +
7928 llvm::capacity_in_bytes(BlockVarCopyInits) +
7929 llvm::capacity_in_bytes(DeclAttrs) +
7930 llvm::capacity_in_bytes(TemplateOrInstantiation) +
7931 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
7932 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
7933 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
7934 llvm::capacity_in_bytes(OverriddenMethods) +
7935 llvm::capacity_in_bytes(Types) +
7936 llvm::capacity_in_bytes(VariableArrayTypes) +
7937 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007938}
Ted Kremenek540017e2011-10-06 05:00:56 +00007939
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007940/// getIntTypeForBitwidth -
7941/// sets integer QualTy according to specified details:
7942/// bitwidth, signed/unsigned.
7943/// Returns empty type if there is no appropriate target types.
7944QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
7945 unsigned Signed) const {
7946 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
7947 CanQualType QualTy = getFromTargetType(Ty);
7948 if (!QualTy && DestWidth == 128)
7949 return Signed ? Int128Ty : UnsignedInt128Ty;
7950 return QualTy;
7951}
7952
7953/// getRealTypeForBitwidth -
7954/// sets floating point QualTy according to specified bitwidth.
7955/// Returns empty type if there is no appropriate target types.
7956QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
7957 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
7958 switch (Ty) {
7959 case TargetInfo::Float:
7960 return FloatTy;
7961 case TargetInfo::Double:
7962 return DoubleTy;
7963 case TargetInfo::LongDouble:
7964 return LongDoubleTy;
7965 case TargetInfo::NoFloat:
7966 return QualType();
7967 }
7968
7969 llvm_unreachable("Unhandled TargetInfo::RealType value");
7970}
7971
Eli Friedman3b7d46c2013-07-10 00:30:46 +00007972void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
7973 if (Number > 1)
7974 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00007975}
7976
Eli Friedman3b7d46c2013-07-10 00:30:46 +00007977unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
7978 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
7979 MangleNumbers.find(ND);
7980 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00007981}
7982
David Majnemer2206bf52014-03-05 08:57:59 +00007983void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
7984 if (Number > 1)
7985 StaticLocalNumbers[VD] = Number;
7986}
7987
7988unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
7989 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
7990 StaticLocalNumbers.find(VD);
7991 return I != StaticLocalNumbers.end() ? I->second : 1;
7992}
7993
Eli Friedman3b7d46c2013-07-10 00:30:46 +00007994MangleNumberingContext &
7995ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00007996 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
7997 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
7998 if (!MCtx)
7999 MCtx = createMangleNumberingContext();
8000 return *MCtx;
8001}
8002
8003MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8004 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008005}
8006
Ted Kremenek540017e2011-10-06 05:00:56 +00008007void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8008 ParamIndices[D] = index;
8009}
8010
8011unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8012 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8013 assert(I != ParamIndices.end() &&
8014 "ParmIndices lacks entry set by ParmVarDecl");
8015 return I->second;
8016}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008017
Richard Smithe6c01442013-06-05 00:46:14 +00008018APValue *
8019ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8020 bool MayCreate) {
8021 assert(E && E->getStorageDuration() == SD_Static &&
8022 "don't need to cache the computed value for this temporary");
8023 if (MayCreate)
8024 return &MaterializedTemporaryValues[E];
8025
8026 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8027 MaterializedTemporaryValues.find(E);
8028 return I == MaterializedTemporaryValues.end() ? 0 : &I->second;
8029}
8030
Fariborz Jahanian615de762013-05-28 17:37:39 +00008031bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8032 const llvm::Triple &T = getTargetInfo().getTriple();
8033 if (!T.isOSDarwin())
8034 return false;
8035
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008036 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8037 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8038 return false;
8039
Fariborz Jahanian615de762013-05-28 17:37:39 +00008040 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8041 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8042 uint64_t Size = sizeChars.getQuantity();
8043 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8044 unsigned Align = alignChars.getQuantity();
8045 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8046 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8047}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008048
8049namespace {
8050
8051 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8052 /// parents as defined by the \c RecursiveASTVisitor.
8053 ///
8054 /// Note that the relationship described here is purely in terms of AST
8055 /// traversal - there are other relationships (for example declaration context)
8056 /// in the AST that are better modeled by special matchers.
8057 ///
8058 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8059 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8060
8061 public:
8062 /// \brief Builds and returns the translation unit's parent map.
8063 ///
8064 /// The caller takes ownership of the returned \c ParentMap.
8065 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8066 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8067 Visitor.TraverseDecl(&TU);
8068 return Visitor.Parents;
8069 }
8070
8071 private:
8072 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8073
8074 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8075 }
8076
8077 bool shouldVisitTemplateInstantiations() const {
8078 return true;
8079 }
8080 bool shouldVisitImplicitCode() const {
8081 return true;
8082 }
8083 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8084 // are not triggered during data recursion.
8085 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8086 return false;
8087 }
8088
8089 template <typename T>
8090 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
8091 if (Node == NULL)
8092 return true;
8093 if (ParentStack.size() > 0)
8094 // FIXME: Currently we add the same parent multiple times, for example
8095 // when we visit all subexpressions of template instantiations; this is
8096 // suboptimal, bug benign: the only way to visit those is with
8097 // hasAncestor / hasParent, and those do not create new matches.
8098 // The plan is to enable DynTypedNode to be storable in a map or hash
8099 // map. The main problem there is to implement hash functions /
8100 // comparison operators for all types that DynTypedNode supports that
8101 // do not have pointer identity.
8102 (*Parents)[Node].push_back(ParentStack.back());
8103 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8104 bool Result = (this ->* traverse) (Node);
8105 ParentStack.pop_back();
8106 return Result;
8107 }
8108
8109 bool TraverseDecl(Decl *DeclNode) {
8110 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8111 }
8112
8113 bool TraverseStmt(Stmt *StmtNode) {
8114 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8115 }
8116
8117 ASTContext::ParentMap *Parents;
8118 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8119
8120 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8121 };
8122
8123} // end namespace
8124
8125ASTContext::ParentVector
8126ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8127 assert(Node.getMemoizationData() &&
8128 "Invariant broken: only nodes that support memoization may be "
8129 "used in the parent map.");
8130 if (!AllParents) {
8131 // We always need to run over the whole translation unit, as
8132 // hasAncestor can escape any subtree.
8133 AllParents.reset(
8134 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8135 }
8136 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8137 if (I == AllParents->end()) {
8138 return ParentVector();
8139 }
8140 return I->second;
8141}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008142
8143bool
8144ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8145 const ObjCMethodDecl *MethodImpl) {
8146 // No point trying to match an unavailable/deprecated mothod.
8147 if (MethodDecl->hasAttr<UnavailableAttr>()
8148 || MethodDecl->hasAttr<DeprecatedAttr>())
8149 return false;
8150 if (MethodDecl->getObjCDeclQualifier() !=
8151 MethodImpl->getObjCDeclQualifier())
8152 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008153 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008154 return false;
8155
8156 if (MethodDecl->param_size() != MethodImpl->param_size())
8157 return false;
8158
8159 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8160 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8161 EF = MethodDecl->param_end();
8162 IM != EM && IF != EF; ++IM, ++IF) {
8163 const ParmVarDecl *DeclVar = (*IF);
8164 const ParmVarDecl *ImplVar = (*IM);
8165 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8166 return false;
8167 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8168 return false;
8169 }
8170 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8171
8172}