blob: 6e3fcd87f136fb01dc2fa1bce4a401f489a333b1 [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())
Craig Topper36250ad2014-05-12 05:36:57 +000080 return nullptr;
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000081
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)
Craig Topper36250ad2014-05-12 05:36:57 +000085 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +000086 }
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)
Craig Topper36250ad2014-05-12 05:36:57 +000091 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000092 }
93
94 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
95 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000096 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000097 }
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)
Craig Topper36250ad2014-05-12 05:36:57 +0000104 return nullptr;
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000105 }
106
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000107 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
108 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000109 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000110 }
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())
Craig Topper36250ad2014-05-12 05:36:57 +0000115 return nullptr;
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000116 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000117 // TODO: handle comments for function parameters properly.
118 if (isa<ParmVarDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000119 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000120
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))
Craig Topper36250ad2014-05-12 05:36:57 +0000126 return nullptr;
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000127
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())
Craig Topper36250ad2014-05-12 05:36:57 +0000132 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000133
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())
Craig Topper36250ad2014-05-12 05:36:57 +0000170 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000171
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())
Craig Topper36250ad2014-05-12 05:36:57 +0000224 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000225 --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())
Craig Topper36250ad2014-05-12 05:36:57 +0000229 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000230
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)
Craig Topper36250ad2014-05-12 05:36:57 +0000238 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000239
240 // Get the corresponding buffer.
241 bool Invalid = false;
242 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
243 &Invalid).data();
244 if (Invalid)
Craig Topper36250ad2014-05-12 05:36:57 +0000245 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000246
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)
Craig Topper36250ad2014-05-12 05:36:57 +0000254 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000255
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.
Craig Topper36250ad2014-05-12 05:36:57 +0000352 const RawComment *RC = nullptr;
353 const Decl *OriginalDeclForRC = nullptr;
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) {
Will Wilsonf9de5362015-10-27 17:01:10 +0000369 // Call order swapped to work around ICE in VS2015 RTM (Release Win32)
370 // https://connect.microsoft.com/VisualStudio/feedback/details/1741530
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000371 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
Will Wilsonf9de5362015-10-27 17:01:10 +0000372 Raw.setRaw(RC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000373 } else
374 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000375 Raw.setOriginalDecl(I);
376 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000377 if (RC)
378 break;
379 }
380 }
381
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000382 // If we found a comment, it should be a documentation comment.
383 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000384
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000385 if (OriginalDecl)
386 *OriginalDecl = OriginalDeclForRC;
387
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000388 // Update cache for every declaration in the redeclaration chain.
389 RawCommentAndCacheFlags Raw;
390 Raw.setRaw(RC);
391 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000392 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000393
Aaron Ballman86c93902014-03-06 23:45:36 +0000394 for (auto I : D->redecls()) {
395 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000396 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
397 R = Raw;
398 }
399
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000400 return RC;
401}
402
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000403static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
404 SmallVectorImpl<const NamedDecl *> &Redeclared) {
405 const DeclContext *DC = ObjCMethod->getDeclContext();
406 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
407 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
408 if (!ID)
409 return;
410 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000411 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000412 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000413 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000414 ObjCMethod->isInstanceMethod()))
415 Redeclared.push_back(RedeclaredMethod);
416 }
417 }
418}
419
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000420comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
421 const Decl *D) const {
422 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
423 ThisDeclInfo->CommentDecl = D;
424 ThisDeclInfo->IsFilled = false;
425 ThisDeclInfo->fill();
426 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000427 if (!ThisDeclInfo->TemplateParameters)
428 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000429 comments::FullComment *CFC =
430 new (*this) comments::FullComment(FC->getBlocks(),
431 ThisDeclInfo);
432 return CFC;
433
434}
435
Richard Smithb39b9d52013-05-21 05:24:00 +0000436comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
437 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000438 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000439}
440
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000441comments::FullComment *ASTContext::getCommentForDecl(
442 const Decl *D,
443 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000444 if (D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000445 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000446 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000447
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000448 const Decl *Canonical = D->getCanonicalDecl();
449 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
450 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000451
452 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000453 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000454 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000455 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000456 return CFC;
457 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000458 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000459 }
460
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000461 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000462
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000463 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000464 if (!RC) {
465 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000466 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000467 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000468 if (OMD && OMD->isPropertyAccessor())
469 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
470 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
471 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000472 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000473 addRedeclaredMethods(OMD, Overridden);
474 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000475 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
476 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
477 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000478 }
Fariborz Jahanian6384fbb2013-05-02 15:44:16 +0000479 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000480 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000481 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000482 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000483 if (const TagType *TT = QT->getAs<TagType>())
484 if (const Decl *TD = TT->getDecl())
485 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000486 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000487 }
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000488 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
489 while (IC->getSuperClass()) {
490 IC = IC->getSuperClass();
491 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
492 return cloneFullComment(FC, D);
493 }
494 }
495 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
496 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
497 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
498 return cloneFullComment(FC, D);
499 }
500 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
501 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000502 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000503 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000504 for (const auto &I : RD->bases()) {
505 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000506 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000507 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000508 if (Ty.isNull())
509 continue;
510 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
511 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
512 continue;
513
514 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
515 return cloneFullComment(FC, D);
516 }
517 }
518 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000519 for (const auto &I : RD->vbases()) {
520 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000521 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000522 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000523 if (Ty.isNull())
524 continue;
525 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
526 if (!(VirtualBase= VirtualBase->getDefinition()))
527 continue;
528 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
529 return cloneFullComment(FC, D);
530 }
531 }
532 }
Craig Topper36250ad2014-05-12 05:36:57 +0000533 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000534 }
535
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000536 // If the RawComment was attached to other redeclaration of this Decl, we
537 // should parse the comment in context of that other Decl. This is important
538 // because comments can contain references to parameter names which can be
539 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000540 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000541 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000542
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000543 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000544 ParsedComments[Canonical] = FC;
545 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000546}
547
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000548void
549ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
550 TemplateTemplateParmDecl *Parm) {
551 ID.AddInteger(Parm->getDepth());
552 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000553 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000554
555 TemplateParameterList *Params = Parm->getTemplateParameters();
556 ID.AddInteger(Params->size());
557 for (TemplateParameterList::const_iterator P = Params->begin(),
558 PEnd = Params->end();
559 P != PEnd; ++P) {
560 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
561 ID.AddInteger(0);
562 ID.AddBoolean(TTP->isParameterPack());
563 continue;
564 }
565
566 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
567 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000568 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000569 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000570 if (NTTP->isExpandedParameterPack()) {
571 ID.AddBoolean(true);
572 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000573 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
574 QualType T = NTTP->getExpansionType(I);
575 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
576 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000577 } else
578 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000579 continue;
580 }
581
582 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
583 ID.AddInteger(2);
584 Profile(ID, TTP);
585 }
586}
587
588TemplateTemplateParmDecl *
589ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000590 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000591 // Check if we already have a canonical template template parameter.
592 llvm::FoldingSetNodeID ID;
593 CanonicalTemplateTemplateParm::Profile(ID, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000594 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000595 CanonicalTemplateTemplateParm *Canonical
596 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
597 if (Canonical)
598 return Canonical->getParam();
599
600 // Build a canonical template parameter list.
601 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000602 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000603 CanonParams.reserve(Params->size());
604 for (TemplateParameterList::const_iterator P = Params->begin(),
605 PEnd = Params->end();
606 P != PEnd; ++P) {
607 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
608 CanonParams.push_back(
609 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000610 SourceLocation(),
611 SourceLocation(),
612 TTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000613 TTP->getIndex(), nullptr, false,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000614 TTP->isParameterPack()));
615 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000616 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
617 QualType T = getCanonicalType(NTTP->getType());
618 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
619 NonTypeTemplateParmDecl *Param;
620 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000621 SmallVector<QualType, 2> ExpandedTypes;
622 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000623 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
624 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
625 ExpandedTInfos.push_back(
626 getTrivialTypeSourceInfo(ExpandedTypes.back()));
627 }
628
629 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000630 SourceLocation(),
631 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000632 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000633 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000634 T,
635 TInfo,
636 ExpandedTypes.data(),
637 ExpandedTypes.size(),
638 ExpandedTInfos.data());
639 } else {
640 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000641 SourceLocation(),
642 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000643 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000644 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000645 T,
646 NTTP->isParameterPack(),
647 TInfo);
648 }
649 CanonParams.push_back(Param);
650
651 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000652 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
653 cast<TemplateTemplateParmDecl>(*P)));
654 }
655
656 TemplateTemplateParmDecl *CanonTTP
657 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
658 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000659 TTP->getPosition(),
660 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000661 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000662 TemplateParameterList::Create(*this, SourceLocation(),
663 SourceLocation(),
664 CanonParams.data(),
665 CanonParams.size(),
666 SourceLocation()));
667
668 // Get the new insert position for the node we care about.
669 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000670 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000671 (void)Canonical;
672
673 // Create the canonical template template parameter entry.
674 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
675 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
676 return CanonTTP;
677}
678
Charles Davis53c59df2010-08-16 03:33:14 +0000679CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000680 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000681
John McCall359b8852013-01-25 22:30:49 +0000682 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000683 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000684 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000685 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +0000686 case TargetCXXABI::WatchOS:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000687 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000688 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000689 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000690 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000691 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000692 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000693 return CreateMicrosoftCXXABI(*this);
694 }
David Blaikie8a40f702012-01-17 06:56:22 +0000695 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000696}
697
Douglas Gregore8bbc122011-09-02 00:18:52 +0000698static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000699 const LangOptions &LOpts) {
700 if (LOpts.FakeAddressSpaceMap) {
701 // The fake address space map must have a distinct entry for each
702 // language-specific address space.
703 static const unsigned FakeAddrSpaceMap[] = {
704 1, // opencl_global
705 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000706 3, // opencl_constant
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000707 4, // opencl_generic
708 5, // cuda_device
709 6, // cuda_constant
710 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000711 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000712 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000713 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000714 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000715 }
716}
717
David Tweed31d09b02013-09-13 12:04:22 +0000718static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
719 const LangOptions &LangOpts) {
720 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000721 case LangOptions::ASMM_Target:
722 return TI.useAddressSpaceMapMangling();
723 case LangOptions::ASMM_On:
724 return true;
725 case LangOptions::ASMM_Off:
726 return false;
727 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000728 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000729}
730
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000731ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000732 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000733 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000734 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
735 DependentTemplateSpecializationTypes(this_()),
736 SubstTemplateTemplateParmPacks(this_()),
737 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
738 UInt128Decl(nullptr), Float128StubDecl(nullptr),
Charles Davisc7d5c942015-09-17 20:55:33 +0000739 BuiltinVaListDecl(nullptr), BuiltinMSVaListDecl(nullptr),
740 ObjCIdDecl(nullptr), ObjCSelDecl(nullptr), ObjCClassDecl(nullptr),
741 ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000742 CFConstantStringTypeDecl(nullptr), ObjCInstanceTypeDecl(nullptr),
743 FILEDecl(nullptr), jmp_bufDecl(nullptr), sigjmp_bufDecl(nullptr),
744 ucontext_tDecl(nullptr), BlockDescriptorType(nullptr),
745 BlockDescriptorExtendedType(nullptr), cudaConfigureCallDecl(nullptr),
Richard Smithf19e1272015-03-07 00:04:49 +0000746 FirstLocalImport(), LastLocalImport(), ExternCContext(nullptr),
747 SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000748 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000749 AddrSpaceMap(nullptr), Target(nullptr), AuxTarget(nullptr),
750 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
751 BuiltinInfo(builtins), DeclarationNames(*this), ExternalSource(nullptr),
752 Listener(nullptr), Comments(SM), CommentsLoaded(false),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000753 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000754 TUDecl = TranslationUnitDecl::Create(*this);
755}
756
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000757ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000758 ReleaseParentMapEntries();
759
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000760 // Release the DenseMaps associated with DeclContext objects.
761 // FIXME: Is this the ideal solution?
762 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000763
Manuel Klimeka7328992013-06-03 13:51:33 +0000764 // Call all of the deallocation functions on all of their targets.
765 for (DeallocationMap::const_iterator I = Deallocations.begin(),
766 E = Deallocations.end(); I != E; ++I)
767 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
768 (I->first)((I->second)[J]);
769
Ted Kremenek076baeb2010-06-08 23:00:58 +0000770 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000771 // because they can contain DenseMaps.
772 for (llvm::DenseMap<const ObjCContainerDecl*,
773 const ASTRecordLayout*>::iterator
774 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
775 // Increment in loop to prevent using deallocated memory.
776 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
777 R->Destroy(*this);
778
Ted Kremenek076baeb2010-06-08 23:00:58 +0000779 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
780 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.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 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000785
786 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
787 AEnd = DeclAttrs.end();
788 A != AEnd; ++A)
789 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000790
David Majnemere694f3e2015-08-14 14:43:50 +0000791 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
792 MaterializedTemporaryValues)
793 MTVPair.second->~APValue();
794
Reid Kleckner588c9372014-02-19 23:44:52 +0000795 llvm::DeleteContainerSeconds(MangleNumberingContexts);
Douglas Gregor561eceb2010-08-30 16:49:28 +0000796}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000797
Manuel Klimek95403e62014-05-21 13:28:59 +0000798void ASTContext::ReleaseParentMapEntries() {
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000799 if (!PointerParents) return;
800 for (const auto &Entry : *PointerParents) {
801 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
802 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
803 } else if (Entry.second.is<ParentVector *>()) {
804 delete Entry.second.get<ParentVector *>();
805 }
806 }
807 for (const auto &Entry : *OtherParents) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000808 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
809 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +0000810 } else if (Entry.second.is<ParentVector *>()) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000811 delete Entry.second.get<ParentVector *>();
812 }
813 }
814}
815
Douglas Gregor1a809332010-05-23 18:26:36 +0000816void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimeka7328992013-06-03 13:51:33 +0000817 Deallocations[Callback].push_back(Data);
Douglas Gregor1a809332010-05-23 18:26:36 +0000818}
819
Mike Stump11289f42009-09-09 15:08:12 +0000820void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000821ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
822 ExternalSource = Source;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000823}
824
Chris Lattner4eb445d2007-01-26 01:27:23 +0000825void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000826 llvm::errs() << "\n*** AST Context Stats:\n";
827 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000828
Douglas Gregora30d0462009-05-26 14:40:08 +0000829 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000830#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000831#define ABSTRACT_TYPE(Name, Parent)
832#include "clang/AST/TypeNodes.def"
833 0 // Extra
834 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000835
Chris Lattner4eb445d2007-01-26 01:27:23 +0000836 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
837 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000838 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000839 }
840
Douglas Gregora30d0462009-05-26 14:40:08 +0000841 unsigned Idx = 0;
842 unsigned TotalBytes = 0;
843#define TYPE(Name, Parent) \
844 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000845 llvm::errs() << " " << counts[Idx] << " " << #Name \
846 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000847 TotalBytes += counts[Idx] * sizeof(Name##Type); \
848 ++Idx;
849#define ABSTRACT_TYPE(Name, Parent)
850#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000851
Chandler Carruth3c147a72011-07-04 05:32:14 +0000852 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
853
Douglas Gregor7454c562010-07-02 20:37:36 +0000854 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000855 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
856 << NumImplicitDefaultConstructors
857 << " implicit default constructors created\n";
858 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
859 << NumImplicitCopyConstructors
860 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000861 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000862 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
863 << NumImplicitMoveConstructors
864 << " implicit move constructors created\n";
865 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
866 << NumImplicitCopyAssignmentOperators
867 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000868 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000869 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
870 << NumImplicitMoveAssignmentOperators
871 << " implicit move assignment operators created\n";
872 llvm::errs() << NumImplicitDestructorsDeclared << "/"
873 << NumImplicitDestructors
874 << " implicit destructors created\n";
875
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000876 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000877 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000878 ExternalSource->PrintStats();
879 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000880
Douglas Gregor5b11d492010-07-25 17:53:33 +0000881 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000882}
883
Richard Smith42413142015-05-15 20:05:43 +0000884void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
885 bool NotifyListeners) {
886 if (NotifyListeners)
887 if (auto *Listener = getASTMutationListener())
888 Listener->RedefinedHiddenDefinition(ND, M);
889
890 if (getLangOpts().ModulesLocalVisibility)
891 MergedDefModules[ND].push_back(M);
892 else
893 ND->setHidden(false);
894}
895
896void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
897 auto It = MergedDefModules.find(ND);
898 if (It == MergedDefModules.end())
899 return;
900
901 auto &Merged = It->second;
902 llvm::DenseSet<Module*> Found;
903 for (Module *&M : Merged)
904 if (!Found.insert(M).second)
905 M = nullptr;
906 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
907}
908
Richard Smithf19e1272015-03-07 00:04:49 +0000909ExternCContextDecl *ASTContext::getExternCContextDecl() const {
910 if (!ExternCContext)
911 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
912
913 return ExternCContext;
914}
915
Alp Toker2dea15b2013-12-17 01:22:38 +0000916RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
917 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000918 SourceLocation Loc;
919 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +0000920 if (getLangOpts().CPlusPlus)
921 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
922 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000923 else
Alp Toker2dea15b2013-12-17 01:22:38 +0000924 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
925 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000926 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +0000927 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
928 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +0000929 return NewDecl;
930}
931
932TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
933 StringRef Name) const {
934 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
935 TypedefDecl *NewDecl = TypedefDecl::Create(
936 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
937 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
938 NewDecl->setImplicit();
939 return NewDecl;
940}
941
Douglas Gregor801c99d2011-08-12 06:49:56 +0000942TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000943 if (!Int128Decl)
944 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000945 return Int128Decl;
946}
947
948TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000949 if (!UInt128Decl)
950 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000951 return UInt128Decl;
952}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000953
Nico Webere1687c52013-06-20 21:44:55 +0000954TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber5b0b46f2013-06-21 01:29:36 +0000955 assert(LangOpts.CPlusPlus && "should only be called for c++");
Alp Toker56b5cc92013-12-15 10:36:26 +0000956 if (!Float128StubDecl)
Alp Toker2dea15b2013-12-17 01:22:38 +0000957 Float128StubDecl = buildImplicitRecord("__float128");
Alp Toker56b5cc92013-12-15 10:36:26 +0000958
Nico Webere1687c52013-06-20 21:44:55 +0000959 return Float128StubDecl;
960}
961
John McCall48f2d582009-10-23 23:03:21 +0000962void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000963 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000964 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000965 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000966}
967
Artem Belevichb5bc9232015-09-22 17:23:22 +0000968void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
969 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000970 assert((!this->Target || this->Target == &Target) &&
971 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000972 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000973
Douglas Gregore8bbc122011-09-02 00:18:52 +0000974 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +0000975 this->AuxTarget = AuxTarget;
976
Douglas Gregore8bbc122011-09-02 00:18:52 +0000977 ABI.reset(createCXXABI(Target));
978 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +0000979 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000980
Chris Lattner970e54e2006-11-12 00:37:36 +0000981 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000982 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000983
Chris Lattner970e54e2006-11-12 00:37:36 +0000984 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000985 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000986 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000987 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000988 InitBuiltinType(CharTy, BuiltinType::Char_S);
989 else
990 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000991 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000992 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
993 InitBuiltinType(ShortTy, BuiltinType::Short);
994 InitBuiltinType(IntTy, BuiltinType::Int);
995 InitBuiltinType(LongTy, BuiltinType::Long);
996 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000997
Chris Lattner970e54e2006-11-12 00:37:36 +0000998 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000999 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1000 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1001 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1002 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1003 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001004
Chris Lattner970e54e2006-11-12 00:37:36 +00001005 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001006 InitBuiltinType(FloatTy, BuiltinType::Float);
1007 InitBuiltinType(DoubleTy, BuiltinType::Double);
1008 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001009
Chris Lattnerf122cef2009-04-30 02:43:43 +00001010 // GNU extension, 128-bit integers.
1011 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1012 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1013
Hans Wennborg0d81e012013-05-10 10:08:40 +00001014 // C++ 3.9.1p5
1015 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1016 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1017 else // -fshort-wchar makes wchar_t be unsigned.
1018 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1019 if (LangOpts.CPlusPlus && LangOpts.WChar)
1020 WideCharTy = WCharTy;
1021 else {
1022 // C99 (or C++ using -fno-wchar).
1023 WideCharTy = getFromTargetType(Target.getWCharType());
1024 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001025
James Molloy36365542012-05-04 10:55:22 +00001026 WIntTy = getFromTargetType(Target.getWIntType());
1027
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001028 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1029 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1030 else // C99
1031 Char16Ty = getFromTargetType(Target.getChar16Type());
1032
1033 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1034 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1035 else // C99
1036 Char32Ty = getFromTargetType(Target.getChar32Type());
1037
Douglas Gregor4619e432008-12-05 23:32:09 +00001038 // Placeholder type for type-dependent expressions whose type is
1039 // completely unknown. No code should ever check a type against
1040 // DependentTy and users should never see it; however, it is here to
1041 // help diagnose failures to properly check for type-dependent
1042 // expressions.
1043 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001044
John McCall36e7fe32010-10-12 00:20:44 +00001045 // Placeholder type for functions.
1046 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1047
John McCall0009fcc2011-04-26 20:42:42 +00001048 // Placeholder type for bound members.
1049 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1050
John McCall526ab472011-10-25 17:37:35 +00001051 // Placeholder type for pseudo-objects.
1052 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1053
John McCall31996342011-04-07 08:22:57 +00001054 // "any" type; useful for debugger-like clients.
1055 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1056
John McCall8a6b59a2011-10-17 18:09:15 +00001057 // Placeholder type for unbridged ARC casts.
1058 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1059
Eli Friedman34866c72012-08-31 00:14:07 +00001060 // Placeholder type for builtin functions.
1061 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1062
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001063 // Placeholder type for OMP array sections.
1064 if (LangOpts.OpenMP)
1065 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1066
Chris Lattner970e54e2006-11-12 00:37:36 +00001067 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001068 FloatComplexTy = getComplexType(FloatTy);
1069 DoubleComplexTy = getComplexType(DoubleTy);
1070 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001071
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001072 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001073 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1074 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001075 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001076
1077 if (LangOpts.OpenCL) {
1078 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1079 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1080 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1081 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1082 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001083 InitBuiltinType(OCLImage2dDepthTy, BuiltinType::OCLImage2dDepth);
1084 InitBuiltinType(OCLImage2dArrayDepthTy, BuiltinType::OCLImage2dArrayDepth);
1085 InitBuiltinType(OCLImage2dMSAATy, BuiltinType::OCLImage2dMSAA);
1086 InitBuiltinType(OCLImage2dArrayMSAATy, BuiltinType::OCLImage2dArrayMSAA);
1087 InitBuiltinType(OCLImage2dMSAADepthTy, BuiltinType::OCLImage2dMSAADepth);
1088 InitBuiltinType(OCLImage2dArrayMSAADepthTy,
1089 BuiltinType::OCLImage2dArrayMSAADepth);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001090 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001091
Guy Benyei61054192013-02-07 10:55:47 +00001092 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001093 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001094 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1095 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1096 InitBuiltinType(OCLNDRangeTy, BuiltinType::OCLNDRange);
1097 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001098 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001099
1100 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001101 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1102 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001103
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001104 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001105
1106 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001107
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001108 // void * type
1109 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001110
1111 // nullptr type (C++0x 2.14.7)
1112 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001113
1114 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1115 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001116
1117 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001118 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001119}
1120
David Blaikie9c902b52011-09-25 23:23:43 +00001121DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001122 return SourceMgr.getDiagnostics();
1123}
1124
Douglas Gregor561eceb2010-08-30 16:49:28 +00001125AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1126 AttrVec *&Result = DeclAttrs[D];
1127 if (!Result) {
1128 void *Mem = Allocate(sizeof(AttrVec));
1129 Result = new (Mem) AttrVec;
1130 }
1131
1132 return *Result;
1133}
1134
1135/// \brief Erase the attributes corresponding to the given declaration.
1136void ASTContext::eraseDeclAttrs(const Decl *D) {
1137 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1138 if (Pos != DeclAttrs.end()) {
1139 Pos->second->~AttrVec();
1140 DeclAttrs.erase(Pos);
1141 }
1142}
1143
Larisse Voufo39a1e502013-08-06 01:03:05 +00001144// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001145MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001146ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001147 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001148 return getTemplateOrSpecializationInfo(Var)
1149 .dyn_cast<MemberSpecializationInfo *>();
1150}
1151
1152ASTContext::TemplateOrSpecializationInfo
1153ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1154 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1155 TemplateOrInstantiation.find(Var);
1156 if (Pos == TemplateOrInstantiation.end())
1157 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001158
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001159 return Pos->second;
1160}
1161
Mike Stump11289f42009-09-09 15:08:12 +00001162void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001163ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001164 TemplateSpecializationKind TSK,
1165 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001166 assert(Inst->isStaticDataMember() && "Not a static data member");
1167 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001168 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1169 Tmpl, TSK, PointOfInstantiation));
1170}
1171
1172void
1173ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1174 TemplateOrSpecializationInfo TSI) {
1175 assert(!TemplateOrInstantiation[Inst] &&
1176 "Already noted what the variable was instantiated from");
1177 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001178}
1179
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001180FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1181 const FunctionDecl *FD){
1182 assert(FD && "Specialization is 0");
1183 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001184 = ClassScopeSpecializationPattern.find(FD);
1185 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001186 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001187
1188 return Pos->second;
1189}
1190
1191void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1192 FunctionDecl *Pattern) {
1193 assert(FD && "Specialization is 0");
1194 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001195 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001196}
1197
John McCalle61f2ba2009-11-18 02:36:19 +00001198NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001199ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001200 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001201 = InstantiatedFromUsingDecl.find(UUD);
1202 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001203 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001204
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001205 return Pos->second;
1206}
1207
1208void
John McCallb96ec562009-12-04 22:46:56 +00001209ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1210 assert((isa<UsingDecl>(Pattern) ||
1211 isa<UnresolvedUsingValueDecl>(Pattern) ||
1212 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1213 "pattern decl is not a using decl");
1214 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1215 InstantiatedFromUsingDecl[Inst] = Pattern;
1216}
1217
1218UsingShadowDecl *
1219ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1220 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1221 = InstantiatedFromUsingShadowDecl.find(Inst);
1222 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001223 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001224
1225 return Pos->second;
1226}
1227
1228void
1229ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1230 UsingShadowDecl *Pattern) {
1231 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1232 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001233}
1234
Anders Carlsson5da84842009-09-01 04:26:58 +00001235FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1236 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1237 = InstantiatedFromUnnamedFieldDecl.find(Field);
1238 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001239 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001240
Anders Carlsson5da84842009-09-01 04:26:58 +00001241 return Pos->second;
1242}
1243
1244void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1245 FieldDecl *Tmpl) {
1246 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1247 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1248 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1249 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001250
Anders Carlsson5da84842009-09-01 04:26:58 +00001251 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1252}
1253
Douglas Gregor832940b2010-03-02 23:58:15 +00001254ASTContext::overridden_cxx_method_iterator
1255ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1256 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001257 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001258 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001259 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001260
1261 return Pos->second.begin();
1262}
1263
1264ASTContext::overridden_cxx_method_iterator
1265ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1266 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001267 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001268 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001269 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001270
1271 return Pos->second.end();
1272}
1273
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001274unsigned
1275ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1276 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001277 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001278 if (Pos == OverriddenMethods.end())
1279 return 0;
1280
1281 return Pos->second.size();
1282}
1283
Douglas Gregor832940b2010-03-02 23:58:15 +00001284void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1285 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001286 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001287 OverriddenMethods[Method].push_back(Overridden);
1288}
1289
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001290void ASTContext::getOverriddenMethods(
1291 const NamedDecl *D,
1292 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001293 assert(D);
1294
1295 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001296 Overridden.append(overridden_methods_begin(CXXMethod),
1297 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001298 return;
1299 }
1300
1301 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1302 if (!Method)
1303 return;
1304
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001305 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1306 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001307 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001308}
1309
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001310void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1311 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1312 assert(!Import->isFromASTFile() && "Non-local import declaration");
1313 if (!FirstLocalImport) {
1314 FirstLocalImport = Import;
1315 LastLocalImport = Import;
1316 return;
1317 }
1318
1319 LastLocalImport->NextLocalImport = Import;
1320 LastLocalImport = Import;
1321}
1322
Chris Lattner53cfe802007-07-18 17:52:12 +00001323//===----------------------------------------------------------------------===//
1324// Type Sizing and Analysis
1325//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001326
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001327/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1328/// scalar floating point type.
1329const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001330 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001331 assert(BT && "Not a floating point type!");
1332 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001333 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001334 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001335 case BuiltinType::Float: return Target->getFloatFormat();
1336 case BuiltinType::Double: return Target->getDoubleFormat();
1337 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001338 }
1339}
1340
Rafael Espindola71eccb32013-08-08 19:53:46 +00001341CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001342 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001343
John McCall94268702010-10-08 18:24:19 +00001344 bool UseAlignAttrOnly = false;
1345 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1346 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001347
John McCall94268702010-10-08 18:24:19 +00001348 // __attribute__((aligned)) can increase or decrease alignment
1349 // *except* on a struct or struct member, where it only increases
1350 // alignment unless 'packed' is also specified.
1351 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001352 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001353 // ignore that possibility; Sema should diagnose it.
1354 if (isa<FieldDecl>(D)) {
1355 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1356 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1357 } else {
1358 UseAlignAttrOnly = true;
1359 }
1360 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001361 else if (isa<FieldDecl>(D))
1362 UseAlignAttrOnly =
1363 D->hasAttr<PackedAttr>() ||
1364 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001365
John McCall4e819612011-01-20 07:57:12 +00001366 // If we're using the align attribute only, just ignore everything
1367 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001368 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001369 // do nothing
1370
John McCall94268702010-10-08 18:24:19 +00001371 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001372 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001373 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001374 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001375 T = RT->getPointeeType();
1376 else
1377 T = getPointerType(RT->getPointeeType());
1378 }
Richard Smithf6d70302014-06-10 23:34:28 +00001379 QualType BaseT = getBaseElementType(T);
1380 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001381 // Adjust alignments of declarations with array type by the
1382 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001383 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001384 unsigned MinWidth = Target->getLargeArrayMinWidth();
1385 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001386 if (isa<VariableArrayType>(arrayType))
1387 Align = std::max(Align, Target->getLargeArrayAlign());
1388 else if (isa<ConstantArrayType>(arrayType) &&
1389 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1390 Align = std::max(Align, Target->getLargeArrayAlign());
1391 }
John McCall33ddac02011-01-19 10:06:00 +00001392 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001393 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001394 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001395 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001396 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1397 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001398 }
John McCall4e819612011-01-20 07:57:12 +00001399
1400 // Fields can be subject to extra alignment constraints, like if
1401 // the field is packed, the struct is packed, or the struct has a
1402 // a max-field-alignment constraint (#pragma pack). So calculate
1403 // the actual alignment of the field within the struct, and then
1404 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001405 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1406 const RecordDecl *Parent = Field->getParent();
1407 // We can only produce a sensible answer if the record is valid.
1408 if (!Parent->isInvalidDecl()) {
1409 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001410
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001411 // Start with the record's overall alignment.
1412 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001413
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001414 // Use the GCD of that and the offset within the record.
1415 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1416 if (Offset > 0) {
1417 // Alignment is always a power of 2, so the GCD will be a power of 2,
1418 // which means we get to do this crazy thing instead of Euclid's.
1419 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1420 if (LowBitOfOffset < FieldAlign)
1421 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1422 }
1423
1424 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001425 }
Charles Davis3fc51072010-02-23 04:52:00 +00001426 }
Chris Lattner68061312009-01-24 21:53:27 +00001427 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001428
Ken Dyckcc56c542011-01-15 18:38:59 +00001429 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001430}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001431
John McCallf1249922012-08-21 04:10:00 +00001432// getTypeInfoDataSizeInChars - Return the size of a type, in
1433// chars. If the type is a record, its data size is returned. This is
1434// the size of the memcpy that's performed when assigning this type
1435// using a trivial copy/move assignment operator.
1436std::pair<CharUnits, CharUnits>
1437ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1438 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1439
1440 // In C++, objects can sometimes be allocated into the tail padding
1441 // of a base-class subobject. We decide whether that's possible
1442 // during class layout, so here we can just trust the layout results.
1443 if (getLangOpts().CPlusPlus) {
1444 if (const RecordType *RT = T->getAs<RecordType>()) {
1445 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1446 sizeAndAlign.first = layout.getDataSize();
1447 }
1448 }
1449
1450 return sizeAndAlign;
1451}
1452
Richard Trieu04d2d942013-05-14 21:59:17 +00001453/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1454/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1455std::pair<CharUnits, CharUnits>
1456static getConstantArrayInfoInChars(const ASTContext &Context,
1457 const ConstantArrayType *CAT) {
1458 std::pair<CharUnits, CharUnits> EltInfo =
1459 Context.getTypeInfoInChars(CAT->getElementType());
1460 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001461 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1462 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001463 "Overflow in array type char size evaluation");
1464 uint64_t Width = EltInfo.first.getQuantity() * Size;
1465 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001466 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1467 Context.getTargetInfo().getPointerWidth(0) == 64)
1468 Width = llvm::RoundUpToAlignment(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001469 return std::make_pair(CharUnits::fromQuantity(Width),
1470 CharUnits::fromQuantity(Align));
1471}
1472
John McCall87fe5d52010-05-20 01:18:31 +00001473std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001474ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001475 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1476 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001477 TypeInfo Info = getTypeInfo(T);
1478 return std::make_pair(toCharUnitsFromBits(Info.Width),
1479 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001480}
1481
1482std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001483ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001484 return getTypeInfoInChars(T.getTypePtr());
1485}
1486
David Majnemer34b57492014-07-30 01:30:47 +00001487bool ASTContext::isAlignmentRequired(const Type *T) const {
1488 return getTypeInfo(T).AlignIsRequired;
1489}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001490
David Majnemer34b57492014-07-30 01:30:47 +00001491bool ASTContext::isAlignmentRequired(QualType T) const {
1492 return isAlignmentRequired(T.getTypePtr());
1493}
1494
1495TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001496 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1497 if (I != MemoizedTypeInfo.end())
1498 return I->second;
1499
1500 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1501 TypeInfo TI = getTypeInfoImpl(T);
1502 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001503 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001504}
1505
1506/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1507/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001508///
1509/// FIXME: Pointers into different addr spaces could have different sizes and
1510/// alignment requirements: getPointerInfo should take an AddrSpace, this
1511/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001512TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1513 uint64_t Width = 0;
1514 unsigned Align = 8;
1515 bool AlignIsRequired = false;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001516 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001517#define TYPE(Class, Base)
1518#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001519#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001520#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001521#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1522 case Type::Class: \
1523 assert(!T->isDependentType() && "should not see dependent types here"); \
1524 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001525#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001526 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001527
Chris Lattner355332d2007-07-13 22:27:08 +00001528 case Type::FunctionNoProto:
1529 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001530 // GCC extension: alignof(function) = 32 bits
1531 Width = 0;
1532 Align = 32;
1533 break;
1534
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001535 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001536 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001537 Width = 0;
1538 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1539 break;
1540
Steve Naroff5c131802007-08-30 01:06:46 +00001541 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001542 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001543
David Majnemer34b57492014-07-30 01:30:47 +00001544 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001545 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001546 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001547 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001548 Width = EltInfo.Width * Size;
1549 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001550 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1551 getTargetInfo().getPointerWidth(0) == 64)
1552 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001553 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001554 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001555 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001556 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001557 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001558 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1559 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001560 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001561 // If the alignment is not a power of 2, round up to the next power of 2.
1562 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001563 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001564 Align = llvm::NextPowerOf2(Align);
1565 Width = llvm::RoundUpToAlignment(Width, Align);
1566 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001567 // Adjust the alignment based on the target max.
1568 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1569 if (TargetVectorAlign && TargetVectorAlign < Align)
1570 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001571 break;
1572 }
Chris Lattner647fb222007-07-18 18:26:58 +00001573
Chris Lattner7570e9c2008-03-08 08:52:55 +00001574 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001575 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001576 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001577 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001578 // GCC extension: alignof(void) = 8 bits.
1579 Width = 0;
1580 Align = 8;
1581 break;
1582
Chris Lattner6a4f7452007-12-19 19:23:28 +00001583 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001584 Width = Target->getBoolWidth();
1585 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001586 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001587 case BuiltinType::Char_S:
1588 case BuiltinType::Char_U:
1589 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001590 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001591 Width = Target->getCharWidth();
1592 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001593 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001594 case BuiltinType::WChar_S:
1595 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001596 Width = Target->getWCharWidth();
1597 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001598 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001599 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001600 Width = Target->getChar16Width();
1601 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001602 break;
1603 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001604 Width = Target->getChar32Width();
1605 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001606 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001607 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001608 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001609 Width = Target->getShortWidth();
1610 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001611 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001612 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001613 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001614 Width = Target->getIntWidth();
1615 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001616 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001617 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001618 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001619 Width = Target->getLongWidth();
1620 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001621 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001622 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001623 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001624 Width = Target->getLongLongWidth();
1625 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001626 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001627 case BuiltinType::Int128:
1628 case BuiltinType::UInt128:
1629 Width = 128;
1630 Align = 128; // int128_t is 128-bit aligned on all targets.
1631 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001632 case BuiltinType::Half:
1633 Width = Target->getHalfWidth();
1634 Align = Target->getHalfAlign();
1635 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001636 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001637 Width = Target->getFloatWidth();
1638 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001639 break;
1640 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001641 Width = Target->getDoubleWidth();
1642 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001643 break;
1644 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001645 Width = Target->getLongDoubleWidth();
1646 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001647 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001648 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001649 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1650 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001651 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001652 case BuiltinType::ObjCId:
1653 case BuiltinType::ObjCClass:
1654 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001655 Width = Target->getPointerWidth(0);
1656 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001657 break;
Guy Benyei61054192013-02-07 10:55:47 +00001658 case BuiltinType::OCLSampler:
1659 // Samplers are modeled as integers.
1660 Width = Target->getIntWidth();
1661 Align = Target->getIntAlign();
1662 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001663 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001664 case BuiltinType::OCLClkEvent:
1665 case BuiltinType::OCLQueue:
1666 case BuiltinType::OCLNDRange:
1667 case BuiltinType::OCLReserveID:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001668 case BuiltinType::OCLImage1d:
1669 case BuiltinType::OCLImage1dArray:
1670 case BuiltinType::OCLImage1dBuffer:
1671 case BuiltinType::OCLImage2d:
1672 case BuiltinType::OCLImage2dArray:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001673 case BuiltinType::OCLImage2dDepth:
1674 case BuiltinType::OCLImage2dArrayDepth:
1675 case BuiltinType::OCLImage2dMSAA:
1676 case BuiltinType::OCLImage2dArrayMSAA:
1677 case BuiltinType::OCLImage2dMSAADepth:
1678 case BuiltinType::OCLImage2dArrayMSAADepth:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001679 case BuiltinType::OCLImage3d:
1680 // Currently these types are pointers to opaque types.
1681 Width = Target->getPointerWidth(0);
1682 Align = Target->getPointerAlign(0);
1683 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001684 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001685 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001686 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001687 Width = Target->getPointerWidth(0);
1688 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001689 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001690 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001691 unsigned AS = getTargetAddressSpace(
1692 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001693 Width = Target->getPointerWidth(AS);
1694 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001695 break;
1696 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001697 case Type::LValueReference:
1698 case Type::RValueReference: {
1699 // alignof and sizeof should never enter this code path here, so we go
1700 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001701 unsigned AS = getTargetAddressSpace(
1702 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001703 Width = Target->getPointerWidth(AS);
1704 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001705 break;
1706 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001707 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001708 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001709 Width = Target->getPointerWidth(AS);
1710 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001711 break;
1712 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001713 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001714 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001715 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001716 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001717 }
Chris Lattner647fb222007-07-18 18:26:58 +00001718 case Type::Complex: {
1719 // Complex types have the same alignment as their elements, but twice the
1720 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001721 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1722 Width = EltInfo.Width * 2;
1723 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001724 break;
1725 }
John McCall8b07ec22010-05-15 11:32:37 +00001726 case Type::ObjCObject:
1727 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001728 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001729 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001730 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001731 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001732 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001733 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001734 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001735 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001736 break;
1737 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001738 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001739 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001740 const TagType *TT = cast<TagType>(T);
1741
1742 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001743 Width = 8;
1744 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001745 break;
1746 }
Mike Stump11289f42009-09-09 15:08:12 +00001747
David Majnemer475b25e2015-01-21 10:54:38 +00001748 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1749 const EnumDecl *ED = ET->getDecl();
1750 TypeInfo Info =
1751 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1752 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1753 Info.Align = AttrAlign;
1754 Info.AlignIsRequired = true;
1755 }
1756 return Info;
1757 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001758
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001759 const RecordType *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001760 const RecordDecl *RD = RT->getDecl();
1761 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001762 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001763 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001764 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001765 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001766 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001767
Chris Lattner63d2b362009-10-22 05:17:15 +00001768 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001769 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1770 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001771
Richard Smith30482bc2011-02-20 03:19:35 +00001772 case Type::Auto: {
1773 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001774 assert(!A->getDeducedType().isNull() &&
1775 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001776 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001777 }
1778
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001779 case Type::Paren:
1780 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1781
Douglas Gregoref462e62009-04-30 17:32:17 +00001782 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001783 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001784 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001785 // If the typedef has an aligned attribute on it, it overrides any computed
1786 // alignment we have. This violates the GCC documentation (which says that
1787 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001788 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001789 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001790 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001791 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001792 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001793 AlignIsRequired = Info.AlignIsRequired;
1794 }
David Majnemer34b57492014-07-30 01:30:47 +00001795 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001796 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001797 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001798
Abramo Bagnara6150c882010-05-11 21:36:43 +00001799 case Type::Elaborated:
1800 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001801
John McCall81904512011-01-06 01:58:22 +00001802 case Type::Attributed:
1803 return getTypeInfo(
1804 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1805
Eli Friedman0dfb8892011-10-06 23:00:33 +00001806 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001807 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001808 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1809 Width = Info.Width;
1810 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001811
1812 // If the size of the type doesn't exceed the platform's max
1813 // atomic promotion width, make the size and alignment more
1814 // favorable to atomic operations:
1815 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1816 // Round the size up to a power of 2.
1817 if (!llvm::isPowerOf2_64(Width))
1818 Width = llvm::NextPowerOf2(Width);
1819
1820 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001821 Align = static_cast<unsigned>(Width);
1822 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001823 }
1824
Douglas Gregoref462e62009-04-30 17:32:17 +00001825 }
Mike Stump11289f42009-09-09 15:08:12 +00001826
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001827 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001828 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001829}
1830
Alexey Bataev00396512015-07-02 03:40:19 +00001831unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1832 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1833 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1834 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1835 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1836 getTargetInfo().getABI() == "elfv1-qpx" &&
1837 T->isSpecificBuiltinType(BuiltinType::Double))
1838 SimdAlign = 256;
1839 return SimdAlign;
1840}
1841
Ken Dyckcc56c542011-01-15 18:38:59 +00001842/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1843CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1844 return CharUnits::fromQuantity(BitSize / getCharWidth());
1845}
1846
Ken Dyckb0fcc592011-02-11 01:54:29 +00001847/// toBits - Convert a size in characters to a size in characters.
1848int64_t ASTContext::toBits(CharUnits CharSize) const {
1849 return CharSize.getQuantity() * getCharWidth();
1850}
1851
Ken Dyck8c89d592009-12-22 14:23:30 +00001852/// getTypeSizeInChars - Return the size of the specified type, in characters.
1853/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001854CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001855 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001856}
Jay Foad39c79802011-01-12 09:06:06 +00001857CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001858 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001859}
1860
Ken Dycka6046ab2010-01-26 17:25:18 +00001861/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001862/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001863CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001864 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001865}
Jay Foad39c79802011-01-12 09:06:06 +00001866CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001867 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001868}
1869
Chris Lattnera3402cd2009-01-27 18:08:34 +00001870/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1871/// type for the current target in bits. This can be different than the ABI
1872/// alignment in cases where it is beneficial for performance to overalign
1873/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001874unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00001875 TypeInfo TI = getTypeInfo(T);
1876 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00001877
David Majnemere1544562015-04-24 01:25:05 +00001878 T = T->getBaseElementTypeUnsafe();
1879
1880 // The preferred alignment of member pointers is that of a pointer.
1881 if (T->isMemberPointerType())
1882 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
1883
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001884 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1885 return ABIAlign; // Never overalign on XCore.
1886
Eli Friedman7ab09572009-05-25 21:27:19 +00001887 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00001888 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001889 T = CT->getElementType().getTypePtr();
David Majnemer475b25e2015-01-21 10:54:38 +00001890 if (const EnumType *ET = T->getAs<EnumType>())
1891 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00001892 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001893 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1894 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00001895 // Don't increase the alignment if an alignment attribute was specified on a
1896 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00001897 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00001898 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00001899
Chris Lattnera3402cd2009-01-27 18:08:34 +00001900 return ABIAlign;
1901}
1902
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00001903/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
1904/// for __attribute__((aligned)) on this target, to be used if no alignment
1905/// value is specified.
1906unsigned ASTContext::getTargetDefaultAlignForAttributeAligned(void) const {
1907 return getTargetInfo().getDefaultAlignForAttributeAligned();
1908}
1909
Ulrich Weigandfa806422013-05-06 16:23:57 +00001910/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1911/// to a global variable of the specified type.
1912unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1913 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1914}
1915
1916/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1917/// should be given to a global variable of the specified type.
1918CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1919 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1920}
1921
David Majnemer08ef2ba2015-06-23 20:34:18 +00001922CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
1923 CharUnits Offset = CharUnits::Zero();
1924 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
1925 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
1926 Offset += Layout->getBaseClassOffset(Base);
1927 Layout = &getASTRecordLayout(Base);
1928 }
1929 return Offset;
1930}
1931
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001932/// DeepCollectObjCIvars -
1933/// This routine first collects all declared, but not synthesized, ivars in
1934/// super class and then collects all ivars, including those synthesized for
1935/// current class. This routine is used for implementation of current class
1936/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001937///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001938void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1939 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001940 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001941 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1942 DeepCollectObjCIvars(SuperClass, false, Ivars);
1943 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00001944 for (const auto *I : OI->ivars())
1945 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001946 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001947 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001948 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001949 Iv= Iv->getNextIvar())
1950 Ivars.push_back(Iv);
1951 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001952}
1953
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001954/// CollectInheritedProtocols - Collect all protocols in current class and
1955/// those inherited by it.
1956void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001957 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001958 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001959 // We can use protocol_iterator here instead of
1960 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001961 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001962 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001963 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001964
1965 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00001966 for (const auto *Cat : OI->visible_categories())
1967 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001968
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001969 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1970 while (SD) {
1971 CollectInheritedProtocols(SD, Protocols);
1972 SD = SD->getSuperClass();
1973 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001974 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00001975 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001976 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001977 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001978 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001979 // Insert the protocol.
1980 if (!Protocols.insert(
1981 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
1982 return;
1983
1984 for (auto *Proto : OP->protocols())
1985 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001986 }
1987}
1988
Jay Foad39c79802011-01-12 09:06:06 +00001989unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001990 unsigned count = 0;
1991 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00001992 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001993 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001994
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001995 // Count ivar defined in this class's implementation. This
1996 // includes synthesized ivars.
1997 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001998 count += ImplDecl->ivar_size();
1999
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002000 return count;
2001}
2002
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002003bool ASTContext::isSentinelNullExpr(const Expr *E) {
2004 if (!E)
2005 return false;
2006
2007 // nullptr_t is always treated as null.
2008 if (E->getType()->isNullPtrType()) return true;
2009
2010 if (E->getType()->isAnyPointerType() &&
2011 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2012 Expr::NPC_ValueDependentIsNull))
2013 return true;
2014
2015 // Unfortunately, __null has type 'int'.
2016 if (isa<GNUNullExpr>(E)) return true;
2017
2018 return false;
2019}
2020
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002021/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
2022ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2023 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2024 I = ObjCImpls.find(D);
2025 if (I != ObjCImpls.end())
2026 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002027 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002028}
2029/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
2030ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2031 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2032 I = ObjCImpls.find(D);
2033 if (I != ObjCImpls.end())
2034 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002035 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002036}
2037
2038/// \brief Set the implementation of ObjCInterfaceDecl.
2039void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2040 ObjCImplementationDecl *ImplD) {
2041 assert(IFaceD && ImplD && "Passed null params");
2042 ObjCImpls[IFaceD] = ImplD;
2043}
2044/// \brief Set the implementation of ObjCCategoryDecl.
2045void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2046 ObjCCategoryImplDecl *ImplD) {
2047 assert(CatD && ImplD && "Passed null params");
2048 ObjCImpls[CatD] = ImplD;
2049}
2050
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002051const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2052 const NamedDecl *ND) const {
2053 if (const ObjCInterfaceDecl *ID =
2054 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002055 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002056 if (const ObjCCategoryDecl *CD =
2057 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002058 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002059 if (const ObjCImplDecl *IMD =
2060 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002061 return IMD->getClassInterface();
2062
Craig Topper36250ad2014-05-12 05:36:57 +00002063 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002064}
2065
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002066/// \brief Get the copy initialization expression of VarDecl,or NULL if
2067/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00002068Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002069 assert(VD && "Passed null params");
2070 assert(VD->hasAttr<BlocksAttr>() &&
2071 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00002072 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002073 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00002074 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002075}
2076
2077/// \brief Set the copy inialization expression of a block var decl.
2078void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2079 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002080 assert(VD->hasAttr<BlocksAttr>() &&
2081 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002082 BlockVarCopyInits[VD] = Init;
2083}
2084
John McCallbcd03502009-12-07 02:54:59 +00002085TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002086 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002087 if (!DataSize)
2088 DataSize = TypeLoc::getFullDataSizeForType(T);
2089 else
2090 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002091 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002092
John McCallbcd03502009-12-07 02:54:59 +00002093 TypeSourceInfo *TInfo =
2094 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2095 new (TInfo) TypeSourceInfo(T);
2096 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002097}
2098
John McCallbcd03502009-12-07 02:54:59 +00002099TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002100 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002101 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002102 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002103 return DI;
2104}
2105
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002106const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002107ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002108 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002109}
2110
2111const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002112ASTContext::getASTObjCImplementationLayout(
2113 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002114 return getObjCLayout(D->getClassInterface(), D);
2115}
2116
Chris Lattner983a8bb2007-07-13 22:13:22 +00002117//===----------------------------------------------------------------------===//
2118// Type creation/memoization methods
2119//===----------------------------------------------------------------------===//
2120
Jay Foad39c79802011-01-12 09:06:06 +00002121QualType
John McCall33ddac02011-01-19 10:06:00 +00002122ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2123 unsigned fastQuals = quals.getFastQualifiers();
2124 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002125
2126 // Check if we've already instantiated this type.
2127 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002128 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002129 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002130 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2131 assert(eq->getQualifiers() == quals);
2132 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002133 }
2134
John McCall33ddac02011-01-19 10:06:00 +00002135 // If the base type is not canonical, make the appropriate canonical type.
2136 QualType canon;
2137 if (!baseType->isCanonicalUnqualified()) {
2138 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002139 canonSplit.Quals.addConsistentQualifiers(quals);
2140 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002141
2142 // Re-find the insert position.
2143 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2144 }
2145
2146 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2147 ExtQualNodes.InsertNode(eq, insertPos);
2148 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002149}
2150
Jay Foad39c79802011-01-12 09:06:06 +00002151QualType
2152ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002153 QualType CanT = getCanonicalType(T);
2154 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002155 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002156
John McCall8ccfcb52009-09-24 19:53:00 +00002157 // If we are composing extended qualifiers together, merge together
2158 // into one ExtQuals node.
2159 QualifierCollector Quals;
2160 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002161
John McCall8ccfcb52009-09-24 19:53:00 +00002162 // If this type already has an address space specified, it cannot get
2163 // another one.
2164 assert(!Quals.hasAddressSpace() &&
2165 "Type cannot be in multiple addr spaces!");
2166 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002167
John McCall8ccfcb52009-09-24 19:53:00 +00002168 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002169}
2170
Chris Lattnerd60183d2009-02-18 22:53:11 +00002171QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002172 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002173 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002174 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002175 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002176
John McCall53fa7142010-12-24 02:08:15 +00002177 if (const PointerType *ptr = T->getAs<PointerType>()) {
2178 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002179 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002180 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2181 return getPointerType(ResultType);
2182 }
2183 }
Mike Stump11289f42009-09-09 15:08:12 +00002184
John McCall8ccfcb52009-09-24 19:53:00 +00002185 // If we are composing extended qualifiers together, merge together
2186 // into one ExtQuals node.
2187 QualifierCollector Quals;
2188 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002189
John McCall8ccfcb52009-09-24 19:53:00 +00002190 // If this type already has an ObjCGC specified, it cannot get
2191 // another one.
2192 assert(!Quals.hasObjCGCAttr() &&
2193 "Type cannot have multiple ObjCGCs!");
2194 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002195
John McCall8ccfcb52009-09-24 19:53:00 +00002196 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002197}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002198
John McCall4f5019e2010-12-19 02:44:49 +00002199const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2200 FunctionType::ExtInfo Info) {
2201 if (T->getExtInfo() == Info)
2202 return T;
2203
2204 QualType Result;
2205 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002206 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002207 } else {
2208 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2209 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2210 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002211 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002212 }
2213
2214 return cast<FunctionType>(Result.getTypePtr());
2215}
2216
Richard Smith2a7d4812013-05-04 07:00:32 +00002217void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2218 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002219 FD = FD->getMostRecentDecl();
2220 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002221 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2222 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002223 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002224 if (FunctionDecl *Next = FD->getPreviousDecl())
2225 FD = Next;
2226 else
2227 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002228 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002229 if (ASTMutationListener *L = getASTMutationListener())
2230 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002231}
2232
Richard Smith0b3a4622014-11-13 20:01:57 +00002233/// Get a function type and produce the equivalent function type with the
2234/// specified exception specification. Type sugar that can be present on a
2235/// declaration of a function with an exception specification is permitted
2236/// and preserved. Other type sugar (for instance, typedefs) is not.
2237static QualType getFunctionTypeWithExceptionSpec(
2238 ASTContext &Context, QualType Orig,
2239 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2240 // Might have some parens.
2241 if (auto *PT = dyn_cast<ParenType>(Orig))
2242 return Context.getParenType(
2243 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2244
2245 // Might have a calling-convention attribute.
2246 if (auto *AT = dyn_cast<AttributedType>(Orig))
2247 return Context.getAttributedType(
2248 AT->getAttrKind(),
2249 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2250 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2251 ESI));
2252
2253 // Anything else must be a function type. Rebuild it with the new exception
2254 // specification.
2255 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2256 return Context.getFunctionType(
2257 Proto->getReturnType(), Proto->getParamTypes(),
2258 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2259}
2260
2261void ASTContext::adjustExceptionSpec(
2262 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2263 bool AsWritten) {
2264 // Update the type.
2265 QualType Updated =
2266 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2267 FD->setType(Updated);
2268
2269 if (!AsWritten)
2270 return;
2271
2272 // Update the type in the type source information too.
2273 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2274 // If the type and the type-as-written differ, we may need to update
2275 // the type-as-written too.
2276 if (TSInfo->getType() != FD->getType())
2277 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2278
2279 // FIXME: When we get proper type location information for exceptions,
2280 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2281 // up the TypeSourceInfo;
2282 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2283 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2284 "TypeLoc size mismatch from updating exception specification");
2285 TSInfo->overrideType(Updated);
2286 }
2287}
2288
Chris Lattnerc6395932007-06-22 20:56:16 +00002289/// getComplexType - Return the uniqued reference to the type for a complex
2290/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002291QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002292 // Unique pointers, to guarantee there is only one pointer of a particular
2293 // structure.
2294 llvm::FoldingSetNodeID ID;
2295 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002296
Craig Topper36250ad2014-05-12 05:36:57 +00002297 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002298 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2299 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002300
Chris Lattnerc6395932007-06-22 20:56:16 +00002301 // If the pointee type isn't canonical, this won't be a canonical type either,
2302 // so fill in the canonical type field.
2303 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002304 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002305 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002306
Chris Lattnerc6395932007-06-22 20:56:16 +00002307 // Get the new insert position for the node we care about.
2308 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002309 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002310 }
John McCall90d1c2d2009-09-24 23:30:46 +00002311 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002312 Types.push_back(New);
2313 ComplexTypes.InsertNode(New, InsertPos);
2314 return QualType(New, 0);
2315}
2316
Chris Lattner970e54e2006-11-12 00:37:36 +00002317/// getPointerType - Return the uniqued reference to the type for a pointer to
2318/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002319QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002320 // Unique pointers, to guarantee there is only one pointer of a particular
2321 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002322 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002323 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002324
Craig Topper36250ad2014-05-12 05:36:57 +00002325 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002326 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002327 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002328
Chris Lattner7ccecb92006-11-12 08:50:50 +00002329 // If the pointee type isn't canonical, this won't be a canonical type either,
2330 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002331 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002332 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002333 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002334
Bob Wilsonc8541f22013-03-15 17:12:43 +00002335 // Get the new insert position for the node we care about.
2336 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002337 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002338 }
John McCall90d1c2d2009-09-24 23:30:46 +00002339 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002340 Types.push_back(New);
2341 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002342 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002343}
2344
Reid Kleckner0503a872013-12-05 01:23:43 +00002345QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2346 llvm::FoldingSetNodeID ID;
2347 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002348 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002349 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2350 if (AT)
2351 return QualType(AT, 0);
2352
2353 QualType Canonical = getCanonicalType(New);
2354
2355 // Get the new insert position for the node we care about.
2356 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002357 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002358
2359 AT = new (*this, TypeAlignment)
2360 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2361 Types.push_back(AT);
2362 AdjustedTypes.InsertNode(AT, InsertPos);
2363 return QualType(AT, 0);
2364}
2365
Reid Kleckner8a365022013-06-24 17:51:48 +00002366QualType ASTContext::getDecayedType(QualType T) const {
2367 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2368
Reid Kleckner8a365022013-06-24 17:51:48 +00002369 QualType Decayed;
2370
2371 // C99 6.7.5.3p7:
2372 // A declaration of a parameter as "array of type" shall be
2373 // adjusted to "qualified pointer to type", where the type
2374 // qualifiers (if any) are those specified within the [ and ] of
2375 // the array type derivation.
2376 if (T->isArrayType())
2377 Decayed = getArrayDecayedType(T);
2378
2379 // C99 6.7.5.3p8:
2380 // A declaration of a parameter as "function returning type"
2381 // shall be adjusted to "pointer to function returning type", as
2382 // in 6.3.2.1.
2383 if (T->isFunctionType())
2384 Decayed = getPointerType(T);
2385
Reid Kleckner0503a872013-12-05 01:23:43 +00002386 llvm::FoldingSetNodeID ID;
2387 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002388 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002389 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2390 if (AT)
2391 return QualType(AT, 0);
2392
Reid Kleckner8a365022013-06-24 17:51:48 +00002393 QualType Canonical = getCanonicalType(Decayed);
2394
2395 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002396 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002397 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002398
Reid Kleckner0503a872013-12-05 01:23:43 +00002399 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2400 Types.push_back(AT);
2401 AdjustedTypes.InsertNode(AT, InsertPos);
2402 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002403}
2404
Mike Stump11289f42009-09-09 15:08:12 +00002405/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002406/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002407QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002408 assert(T->isFunctionType() && "block of function types only");
2409 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002410 // structure.
2411 llvm::FoldingSetNodeID ID;
2412 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002413
Craig Topper36250ad2014-05-12 05:36:57 +00002414 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002415 if (BlockPointerType *PT =
2416 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2417 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002418
2419 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002420 // type either so fill in the canonical type field.
2421 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002422 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002423 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002424
Steve Naroffec33ed92008-08-27 16:04:49 +00002425 // Get the new insert position for the node we care about.
2426 BlockPointerType *NewIP =
2427 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002428 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002429 }
John McCall90d1c2d2009-09-24 23:30:46 +00002430 BlockPointerType *New
2431 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002432 Types.push_back(New);
2433 BlockPointerTypes.InsertNode(New, InsertPos);
2434 return QualType(New, 0);
2435}
2436
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002437/// getLValueReferenceType - Return the uniqued reference to the type for an
2438/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002439QualType
2440ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002441 assert(getCanonicalType(T) != OverloadTy &&
2442 "Unresolved overloaded function type");
2443
Bill Wendling3708c182007-05-27 10:15:43 +00002444 // Unique pointers, to guarantee there is only one pointer of a particular
2445 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002446 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002447 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002448
Craig Topper36250ad2014-05-12 05:36:57 +00002449 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002450 if (LValueReferenceType *RT =
2451 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002452 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002453
John McCallfc93cf92009-10-22 22:37:11 +00002454 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2455
Bill Wendling3708c182007-05-27 10:15:43 +00002456 // If the referencee type isn't canonical, this won't be a canonical type
2457 // either, so fill in the canonical type field.
2458 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002459 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2460 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2461 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002462
Bill Wendling3708c182007-05-27 10:15:43 +00002463 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002464 LValueReferenceType *NewIP =
2465 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002466 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002467 }
2468
John McCall90d1c2d2009-09-24 23:30:46 +00002469 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002470 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2471 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002472 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002473 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002474
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002475 return QualType(New, 0);
2476}
2477
2478/// getRValueReferenceType - Return the uniqued reference to the type for an
2479/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002480QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002481 // Unique pointers, to guarantee there is only one pointer of a particular
2482 // structure.
2483 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002484 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002485
Craig Topper36250ad2014-05-12 05:36:57 +00002486 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002487 if (RValueReferenceType *RT =
2488 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2489 return QualType(RT, 0);
2490
John McCallfc93cf92009-10-22 22:37:11 +00002491 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2492
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002493 // If the referencee type isn't canonical, this won't be a canonical type
2494 // either, so fill in the canonical type field.
2495 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002496 if (InnerRef || !T.isCanonical()) {
2497 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2498 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002499
2500 // Get the new insert position for the node we care about.
2501 RValueReferenceType *NewIP =
2502 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002503 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002504 }
2505
John McCall90d1c2d2009-09-24 23:30:46 +00002506 RValueReferenceType *New
2507 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002508 Types.push_back(New);
2509 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002510 return QualType(New, 0);
2511}
2512
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002513/// getMemberPointerType - Return the uniqued reference to the type for a
2514/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002515QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002516 // Unique pointers, to guarantee there is only one pointer of a particular
2517 // structure.
2518 llvm::FoldingSetNodeID ID;
2519 MemberPointerType::Profile(ID, T, Cls);
2520
Craig Topper36250ad2014-05-12 05:36:57 +00002521 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002522 if (MemberPointerType *PT =
2523 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2524 return QualType(PT, 0);
2525
2526 // If the pointee or class type isn't canonical, this won't be a canonical
2527 // type either, so fill in the canonical type field.
2528 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002529 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002530 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2531
2532 // Get the new insert position for the node we care about.
2533 MemberPointerType *NewIP =
2534 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002535 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002536 }
John McCall90d1c2d2009-09-24 23:30:46 +00002537 MemberPointerType *New
2538 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002539 Types.push_back(New);
2540 MemberPointerTypes.InsertNode(New, InsertPos);
2541 return QualType(New, 0);
2542}
2543
Mike Stump11289f42009-09-09 15:08:12 +00002544/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002545/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002546QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002547 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002548 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002549 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002550 assert((EltTy->isDependentType() ||
2551 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002552 "Constant array of VLAs is illegal!");
2553
Chris Lattnere2df3f92009-05-13 04:12:56 +00002554 // Convert the array size into a canonical width matching the pointer size for
2555 // the target.
2556 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002557 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002558 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002559
Chris Lattner23b7eb62007-06-15 23:05:46 +00002560 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002561 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002562
Craig Topper36250ad2014-05-12 05:36:57 +00002563 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002564 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002565 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002566 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002567
John McCall33ddac02011-01-19 10:06:00 +00002568 // If the element type isn't canonical or has qualifiers, this won't
2569 // be a canonical type either, so fill in the canonical type field.
2570 QualType Canon;
2571 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2572 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002573 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002574 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002575 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002576
Chris Lattner36f8e652007-01-27 08:31:04 +00002577 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002578 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002579 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002580 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002581 }
Mike Stump11289f42009-09-09 15:08:12 +00002582
John McCall90d1c2d2009-09-24 23:30:46 +00002583 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002584 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002585 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002586 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002587 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002588}
2589
John McCall06549462011-01-18 08:40:38 +00002590/// getVariableArrayDecayedType - Turns the given type, which may be
2591/// variably-modified, into the corresponding type with all the known
2592/// sizes replaced with [*].
2593QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2594 // Vastly most common case.
2595 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002596
John McCall06549462011-01-18 08:40:38 +00002597 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002598
John McCall06549462011-01-18 08:40:38 +00002599 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002600 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002601 switch (ty->getTypeClass()) {
2602#define TYPE(Class, Base)
2603#define ABSTRACT_TYPE(Class, Base)
2604#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2605#include "clang/AST/TypeNodes.def"
2606 llvm_unreachable("didn't desugar past all non-canonical types?");
2607
2608 // These types should never be variably-modified.
2609 case Type::Builtin:
2610 case Type::Complex:
2611 case Type::Vector:
2612 case Type::ExtVector:
2613 case Type::DependentSizedExtVector:
2614 case Type::ObjCObject:
2615 case Type::ObjCInterface:
2616 case Type::ObjCObjectPointer:
2617 case Type::Record:
2618 case Type::Enum:
2619 case Type::UnresolvedUsing:
2620 case Type::TypeOfExpr:
2621 case Type::TypeOf:
2622 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002623 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002624 case Type::DependentName:
2625 case Type::InjectedClassName:
2626 case Type::TemplateSpecialization:
2627 case Type::DependentTemplateSpecialization:
2628 case Type::TemplateTypeParm:
2629 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002630 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002631 case Type::PackExpansion:
2632 llvm_unreachable("type should never be variably-modified");
2633
2634 // These types can be variably-modified but should never need to
2635 // further decay.
2636 case Type::FunctionNoProto:
2637 case Type::FunctionProto:
2638 case Type::BlockPointer:
2639 case Type::MemberPointer:
2640 return type;
2641
2642 // These types can be variably-modified. All these modifications
2643 // preserve structure except as noted by comments.
2644 // TODO: if we ever care about optimizing VLAs, there are no-op
2645 // optimizations available here.
2646 case Type::Pointer:
2647 result = getPointerType(getVariableArrayDecayedType(
2648 cast<PointerType>(ty)->getPointeeType()));
2649 break;
2650
2651 case Type::LValueReference: {
2652 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2653 result = getLValueReferenceType(
2654 getVariableArrayDecayedType(lv->getPointeeType()),
2655 lv->isSpelledAsLValue());
2656 break;
2657 }
2658
2659 case Type::RValueReference: {
2660 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2661 result = getRValueReferenceType(
2662 getVariableArrayDecayedType(lv->getPointeeType()));
2663 break;
2664 }
2665
Eli Friedman0dfb8892011-10-06 23:00:33 +00002666 case Type::Atomic: {
2667 const AtomicType *at = cast<AtomicType>(ty);
2668 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2669 break;
2670 }
2671
John McCall06549462011-01-18 08:40:38 +00002672 case Type::ConstantArray: {
2673 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2674 result = getConstantArrayType(
2675 getVariableArrayDecayedType(cat->getElementType()),
2676 cat->getSize(),
2677 cat->getSizeModifier(),
2678 cat->getIndexTypeCVRQualifiers());
2679 break;
2680 }
2681
2682 case Type::DependentSizedArray: {
2683 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2684 result = getDependentSizedArrayType(
2685 getVariableArrayDecayedType(dat->getElementType()),
2686 dat->getSizeExpr(),
2687 dat->getSizeModifier(),
2688 dat->getIndexTypeCVRQualifiers(),
2689 dat->getBracketsRange());
2690 break;
2691 }
2692
2693 // Turn incomplete types into [*] types.
2694 case Type::IncompleteArray: {
2695 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2696 result = getVariableArrayType(
2697 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002698 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002699 ArrayType::Normal,
2700 iat->getIndexTypeCVRQualifiers(),
2701 SourceRange());
2702 break;
2703 }
2704
2705 // Turn VLA types into [*] types.
2706 case Type::VariableArray: {
2707 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2708 result = getVariableArrayType(
2709 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002710 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002711 ArrayType::Star,
2712 vat->getIndexTypeCVRQualifiers(),
2713 vat->getBracketsRange());
2714 break;
2715 }
2716 }
2717
2718 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002719 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002720}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002721
Steve Naroffcadebd02007-08-30 18:14:25 +00002722/// getVariableArrayType - Returns a non-unique reference to the type for a
2723/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002724QualType ASTContext::getVariableArrayType(QualType EltTy,
2725 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002726 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002727 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002728 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002729 // Since we don't unique expressions, it isn't possible to unique VLA's
2730 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002731 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002732
John McCall33ddac02011-01-19 10:06:00 +00002733 // Be sure to pull qualifiers off the element type.
2734 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2735 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002736 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002737 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002738 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002739 }
2740
John McCall90d1c2d2009-09-24 23:30:46 +00002741 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002742 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002743
2744 VariableArrayTypes.push_back(New);
2745 Types.push_back(New);
2746 return QualType(New, 0);
2747}
2748
Douglas Gregor4619e432008-12-05 23:32:09 +00002749/// getDependentSizedArrayType - Returns a non-unique reference to
2750/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002751/// type.
John McCall33ddac02011-01-19 10:06:00 +00002752QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2753 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002754 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002755 unsigned elementTypeQuals,
2756 SourceRange brackets) const {
2757 assert((!numElements || numElements->isTypeDependent() ||
2758 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002759 "Size must be type- or value-dependent!");
2760
John McCall33ddac02011-01-19 10:06:00 +00002761 // Dependently-sized array types that do not have a specified number
2762 // of elements will have their sizes deduced from a dependent
2763 // initializer. We do no canonicalization here at all, which is okay
2764 // because they can't be used in most locations.
2765 if (!numElements) {
2766 DependentSizedArrayType *newType
2767 = new (*this, TypeAlignment)
2768 DependentSizedArrayType(*this, elementType, QualType(),
2769 numElements, ASM, elementTypeQuals,
2770 brackets);
2771 Types.push_back(newType);
2772 return QualType(newType, 0);
2773 }
2774
2775 // Otherwise, we actually build a new type every time, but we
2776 // also build a canonical type.
2777
2778 SplitQualType canonElementType = getCanonicalType(elementType).split();
2779
Craig Topper36250ad2014-05-12 05:36:57 +00002780 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002781 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002782 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002783 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002784 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002785
John McCall33ddac02011-01-19 10:06:00 +00002786 // Look for an existing type with these properties.
2787 DependentSizedArrayType *canonTy =
2788 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002789
John McCall33ddac02011-01-19 10:06:00 +00002790 // If we don't have one, build one.
2791 if (!canonTy) {
2792 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002793 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002794 QualType(), numElements, ASM, elementTypeQuals,
2795 brackets);
2796 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2797 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002798 }
2799
John McCall33ddac02011-01-19 10:06:00 +00002800 // Apply qualifiers from the element type to the array.
2801 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002802 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002803
David Majnemer16a74702015-07-24 05:54:19 +00002804 // If we didn't need extra canonicalization for the element type or the size
2805 // expression, then just use that as our result.
2806 if (QualType(canonElementType.Ty, 0) == elementType &&
2807 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00002808 return canon;
2809
2810 // Otherwise, we need to build a type which follows the spelling
2811 // of the element type.
2812 DependentSizedArrayType *sugaredType
2813 = new (*this, TypeAlignment)
2814 DependentSizedArrayType(*this, elementType, canon, numElements,
2815 ASM, elementTypeQuals, brackets);
2816 Types.push_back(sugaredType);
2817 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002818}
2819
John McCall33ddac02011-01-19 10:06:00 +00002820QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002821 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002822 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002823 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002824 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002825
Craig Topper36250ad2014-05-12 05:36:57 +00002826 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002827 if (IncompleteArrayType *iat =
2828 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2829 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002830
2831 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002832 // either, so fill in the canonical type field. We also have to pull
2833 // qualifiers off the element type.
2834 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002835
John McCall33ddac02011-01-19 10:06:00 +00002836 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2837 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002838 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002839 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002840 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002841
2842 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002843 IncompleteArrayType *existing =
2844 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2845 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002846 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002847
John McCall33ddac02011-01-19 10:06:00 +00002848 IncompleteArrayType *newType = new (*this, TypeAlignment)
2849 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002850
John McCall33ddac02011-01-19 10:06:00 +00002851 IncompleteArrayTypes.InsertNode(newType, insertPos);
2852 Types.push_back(newType);
2853 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002854}
2855
Steve Naroff91fcddb2007-07-18 18:00:27 +00002856/// getVectorType - Return the unique reference to a vector type of
2857/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002858QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002859 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002860 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002861
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002862 // Check if we've already instantiated a vector of this type.
2863 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002864 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002865
Craig Topper36250ad2014-05-12 05:36:57 +00002866 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002867 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2868 return QualType(VTP, 0);
2869
2870 // If the element type isn't canonical, this won't be a canonical type either,
2871 // so fill in the canonical type field.
2872 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002873 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002874 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002875
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002876 // Get the new insert position for the node we care about.
2877 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002878 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002879 }
John McCall90d1c2d2009-09-24 23:30:46 +00002880 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002881 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002882 VectorTypes.InsertNode(New, InsertPos);
2883 Types.push_back(New);
2884 return QualType(New, 0);
2885}
2886
Nate Begemance4d7fc2008-04-18 23:10:10 +00002887/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002888/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002889QualType
2890ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002891 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002892
Steve Naroff91fcddb2007-07-18 18:00:27 +00002893 // Check if we've already instantiated a vector of this type.
2894 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002895 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002896 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00002897 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002898 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2899 return QualType(VTP, 0);
2900
2901 // If the element type isn't canonical, this won't be a canonical type either,
2902 // so fill in the canonical type field.
2903 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002904 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002905 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002906
Steve Naroff91fcddb2007-07-18 18:00:27 +00002907 // Get the new insert position for the node we care about.
2908 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002909 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002910 }
John McCall90d1c2d2009-09-24 23:30:46 +00002911 ExtVectorType *New = new (*this, TypeAlignment)
2912 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002913 VectorTypes.InsertNode(New, InsertPos);
2914 Types.push_back(New);
2915 return QualType(New, 0);
2916}
2917
Jay Foad39c79802011-01-12 09:06:06 +00002918QualType
2919ASTContext::getDependentSizedExtVectorType(QualType vecType,
2920 Expr *SizeExpr,
2921 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002922 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002923 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002924 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002925
Craig Topper36250ad2014-05-12 05:36:57 +00002926 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00002927 DependentSizedExtVectorType *Canon
2928 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2929 DependentSizedExtVectorType *New;
2930 if (Canon) {
2931 // We already have a canonical version of this array type; use it as
2932 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002933 New = new (*this, TypeAlignment)
2934 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2935 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002936 } else {
2937 QualType CanonVecTy = getCanonicalType(vecType);
2938 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002939 New = new (*this, TypeAlignment)
2940 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2941 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002942
2943 DependentSizedExtVectorType *CanonCheck
2944 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2945 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2946 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002947 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2948 } else {
2949 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2950 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002951 New = new (*this, TypeAlignment)
2952 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002953 }
2954 }
Mike Stump11289f42009-09-09 15:08:12 +00002955
Douglas Gregor758a8692009-06-17 21:51:59 +00002956 Types.push_back(New);
2957 return QualType(New, 0);
2958}
2959
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002960/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002961///
Jay Foad39c79802011-01-12 09:06:06 +00002962QualType
2963ASTContext::getFunctionNoProtoType(QualType ResultTy,
2964 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002965 const CallingConv CallConv = Info.getCC();
2966
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002967 // Unique functions, to guarantee there is only one function of a particular
2968 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002969 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002970 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002971
Craig Topper36250ad2014-05-12 05:36:57 +00002972 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002973 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002974 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002975 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002976
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002977 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002978 if (!ResultTy.isCanonical()) {
2979 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002980
Chris Lattner47955de2007-01-27 08:37:20 +00002981 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002982 FunctionNoProtoType *NewIP =
2983 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002984 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002985 }
Mike Stump11289f42009-09-09 15:08:12 +00002986
Roman Divacky65b88cd2011-03-01 17:40:53 +00002987 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002988 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002989 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002990 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002991 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002992 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002993}
2994
Douglas Gregorcd780372013-01-17 23:36:45 +00002995/// \brief Determine whether \p T is canonical as the result type of a function.
2996static bool isCanonicalResultType(QualType T) {
2997 return T.isCanonical() &&
2998 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2999 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3000}
3001
Douglas Gregora602a152015-10-01 20:20:47 +00003002CanQualType
3003ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3004 CanQualType CanResultType = getCanonicalType(ResultType);
3005
3006 // Canonical result types do not have ARC lifetime qualifiers.
3007 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3008 Qualifiers Qs = CanResultType.getQualifiers();
3009 Qs.removeObjCLifetime();
3010 return CanQualType::CreateUnsafe(
3011 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3012 }
3013
3014 return CanResultType;
3015}
3016
Jay Foad39c79802011-01-12 09:06:06 +00003017QualType
Jordan Rose5c382722013-03-08 21:51:21 +00003018ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00003019 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003020 size_t NumArgs = ArgArray.size();
3021
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003022 // Unique functions, to guarantee there is only one function of a particular
3023 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003024 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00003025 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3026 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00003027
Craig Topper36250ad2014-05-12 05:36:57 +00003028 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003029 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003030 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003031 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003032
3033 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00003034 bool isCanonical =
Richard Smith8acb4282014-07-31 21:57:55 +00003035 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00003036 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003037 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003038 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003039 isCanonical = false;
3040
3041 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003042 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003043 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00003044 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003045 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003046 CanonicalArgs.reserve(NumArgs);
3047 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003048 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003049
John McCalldb40c7f2010-12-14 08:05:40 +00003050 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003051 CanonicalEPI.HasTrailingReturn = false;
Richard Smith8acb4282014-07-31 21:57:55 +00003052 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00003053
Douglas Gregora602a152015-10-01 20:20:47 +00003054 // Adjust the canonical function result type.
3055 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Jordan Rose5c382722013-03-08 21:51:21 +00003056 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003057
Chris Lattnerfd4de792007-01-27 01:15:32 +00003058 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003059 FunctionProtoType *NewIP =
3060 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003061 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003062 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003063
John McCall31168b02011-06-15 23:02:42 +00003064 // FunctionProtoType objects are allocated with extra bytes after
3065 // them for three variable size arrays at the end:
3066 // - parameter types
3067 // - exception types
3068 // - consumed-arguments flags
3069 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003070 // expression, or information used to resolve the exception
3071 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00003072 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003073 NumArgs * sizeof(QualType);
Richard Smith8acb4282014-07-31 21:57:55 +00003074 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3075 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3076 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00003077 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00003078 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00003079 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00003080 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003081 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003082 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003083 if (EPI.ConsumedParameters)
John McCall31168b02011-06-15 23:02:42 +00003084 Size += NumArgs * sizeof(bool);
3085
John McCalldb40c7f2010-12-14 08:05:40 +00003086 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003087 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003088 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003089 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003090 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003091 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003092}
Chris Lattneref51c202006-11-10 07:17:23 +00003093
John McCalle78aac42010-03-10 03:28:59 +00003094#ifndef NDEBUG
3095static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3096 if (!isa<CXXRecordDecl>(D)) return false;
3097 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3098 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3099 return true;
3100 if (RD->getDescribedClassTemplate() &&
3101 !isa<ClassTemplateSpecializationDecl>(RD))
3102 return true;
3103 return false;
3104}
3105#endif
3106
3107/// getInjectedClassNameType - Return the unique reference to the
3108/// injected class name type for the specified templated declaration.
3109QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003110 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003111 assert(NeedsInjectedClassNameType(Decl));
3112 if (Decl->TypeForDecl) {
3113 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003114 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003115 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3116 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3117 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3118 } else {
John McCall424cec92011-01-19 06:33:43 +00003119 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003120 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003121 Decl->TypeForDecl = newType;
3122 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003123 }
3124 return QualType(Decl->TypeForDecl, 0);
3125}
3126
Douglas Gregor83a586e2008-04-13 21:07:44 +00003127/// getTypeDeclType - Return the unique reference to the type for the
3128/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003129QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003130 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003131 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003132
Richard Smithdda56e42011-04-15 14:24:37 +00003133 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003134 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003135
John McCall96f0b5f2010-03-10 06:48:02 +00003136 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3137 "Template type parameter types are always available.");
3138
John McCall81e38502010-02-16 03:57:14 +00003139 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003140 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003141 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003142 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003143 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003144 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003145 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003146 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003147 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003148 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3149 Decl->TypeForDecl = newType;
3150 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003151 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003152 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003153
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003154 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003155}
3156
Chris Lattner32d920b2007-01-26 02:01:53 +00003157/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003158/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003159QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003160ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3161 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003162 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003163
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003164 if (Canonical.isNull())
3165 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003166 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003167 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003168 Decl->TypeForDecl = newType;
3169 Types.push_back(newType);
3170 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003171}
3172
Jay Foad39c79802011-01-12 09:06:06 +00003173QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003174 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3175
Douglas Gregorec9fd132012-01-14 16:38:05 +00003176 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003177 if (PrevDecl->TypeForDecl)
3178 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3179
John McCall424cec92011-01-19 06:33:43 +00003180 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3181 Decl->TypeForDecl = newType;
3182 Types.push_back(newType);
3183 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003184}
3185
Jay Foad39c79802011-01-12 09:06:06 +00003186QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003187 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3188
Douglas Gregorec9fd132012-01-14 16:38:05 +00003189 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003190 if (PrevDecl->TypeForDecl)
3191 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3192
John McCall424cec92011-01-19 06:33:43 +00003193 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3194 Decl->TypeForDecl = newType;
3195 Types.push_back(newType);
3196 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003197}
3198
John McCall81904512011-01-06 01:58:22 +00003199QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3200 QualType modifiedType,
3201 QualType equivalentType) {
3202 llvm::FoldingSetNodeID id;
3203 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3204
Craig Topper36250ad2014-05-12 05:36:57 +00003205 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003206 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3207 if (type) return QualType(type, 0);
3208
3209 QualType canon = getCanonicalType(equivalentType);
3210 type = new (*this, TypeAlignment)
3211 AttributedType(canon, attrKind, modifiedType, equivalentType);
3212
3213 Types.push_back(type);
3214 AttributedTypes.InsertNode(type, insertPos);
3215
3216 return QualType(type, 0);
3217}
3218
3219
John McCallcebee162009-10-18 09:09:24 +00003220/// \brief Retrieve a substitution-result type.
3221QualType
3222ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003223 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003224 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003225 && "replacement types must always be canonical");
3226
3227 llvm::FoldingSetNodeID ID;
3228 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003229 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003230 SubstTemplateTypeParmType *SubstParm
3231 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3232
3233 if (!SubstParm) {
3234 SubstParm = new (*this, TypeAlignment)
3235 SubstTemplateTypeParmType(Parm, Replacement);
3236 Types.push_back(SubstParm);
3237 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3238 }
3239
3240 return QualType(SubstParm, 0);
3241}
3242
Douglas Gregorada4b792011-01-14 02:55:32 +00003243/// \brief Retrieve a
3244QualType ASTContext::getSubstTemplateTypeParmPackType(
3245 const TemplateTypeParmType *Parm,
3246 const TemplateArgument &ArgPack) {
3247#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003248 for (const auto &P : ArgPack.pack_elements()) {
3249 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3250 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003251 }
3252#endif
3253
3254 llvm::FoldingSetNodeID ID;
3255 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003256 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003257 if (SubstTemplateTypeParmPackType *SubstParm
3258 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3259 return QualType(SubstParm, 0);
3260
3261 QualType Canon;
3262 if (!Parm->isCanonicalUnqualified()) {
3263 Canon = getCanonicalType(QualType(Parm, 0));
3264 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3265 ArgPack);
3266 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3267 }
3268
3269 SubstTemplateTypeParmPackType *SubstParm
3270 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3271 ArgPack);
3272 Types.push_back(SubstParm);
3273 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3274 return QualType(SubstParm, 0);
3275}
3276
Douglas Gregoreff93e02009-02-05 23:33:38 +00003277/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003278/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003279/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003280QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003281 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003282 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003283 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003284 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003285 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003286 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003287 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3288
3289 if (TypeParm)
3290 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003291
Chandler Carruth08836322011-05-01 00:51:33 +00003292 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003293 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003294 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003295
3296 TemplateTypeParmType *TypeCheck
3297 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3298 assert(!TypeCheck && "Template type parameter canonical type broken");
3299 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003300 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003301 TypeParm = new (*this, TypeAlignment)
3302 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003303
3304 Types.push_back(TypeParm);
3305 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3306
3307 return QualType(TypeParm, 0);
3308}
3309
John McCalle78aac42010-03-10 03:28:59 +00003310TypeSourceInfo *
3311ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3312 SourceLocation NameLoc,
3313 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003314 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003315 assert(!Name.getAsDependentTemplateName() &&
3316 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003317 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003318
3319 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003320 TemplateSpecializationTypeLoc TL =
3321 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003322 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003323 TL.setTemplateNameLoc(NameLoc);
3324 TL.setLAngleLoc(Args.getLAngleLoc());
3325 TL.setRAngleLoc(Args.getRAngleLoc());
3326 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3327 TL.setArgLocInfo(i, Args[i].getLocInfo());
3328 return DI;
3329}
3330
Mike Stump11289f42009-09-09 15:08:12 +00003331QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003332ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003333 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003334 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003335 assert(!Template.getAsDependentTemplateName() &&
3336 "No dependent template names here!");
3337
John McCall6b51f282009-11-23 01:53:49 +00003338 unsigned NumArgs = Args.size();
3339
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003340 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003341 ArgVec.reserve(NumArgs);
3342 for (unsigned i = 0; i != NumArgs; ++i)
3343 ArgVec.push_back(Args[i].getArgument());
3344
John McCall2408e322010-04-27 00:57:59 +00003345 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003346 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003347}
3348
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003349#ifndef NDEBUG
3350static bool hasAnyPackExpansions(const TemplateArgument *Args,
3351 unsigned NumArgs) {
3352 for (unsigned I = 0; I != NumArgs; ++I)
3353 if (Args[I].isPackExpansion())
3354 return true;
3355
3356 return true;
3357}
3358#endif
3359
John McCall0ad16662009-10-29 08:12:44 +00003360QualType
3361ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003362 const TemplateArgument *Args,
3363 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003364 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003365 assert(!Template.getAsDependentTemplateName() &&
3366 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003367 // Look through qualified template names.
3368 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3369 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003370
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003371 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003372 Template.getAsTemplateDecl() &&
3373 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003374 QualType CanonType;
3375 if (!Underlying.isNull())
3376 CanonType = getCanonicalType(Underlying);
3377 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003378 // We can get here with an alias template when the specialization contains
3379 // a pack expansion that does not match up with a parameter pack.
3380 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3381 "Caller must compute aliased type");
3382 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003383 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3384 NumArgs);
3385 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003386
Douglas Gregora8e02e72009-07-28 23:00:59 +00003387 // Allocate the (non-canonical) template specialization type, but don't
3388 // try to unique it: these types typically have location information that
3389 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003390 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3391 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003392 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003393 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003394 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003395 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3396 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003397
Douglas Gregor8bf42052009-02-09 18:46:07 +00003398 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003399 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003400}
3401
Mike Stump11289f42009-09-09 15:08:12 +00003402QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003403ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3404 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003405 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003406 assert(!Template.getAsDependentTemplateName() &&
3407 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003408
Douglas Gregore29139c2011-03-03 17:04:51 +00003409 // Look through qualified template names.
3410 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3411 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003412
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003413 // Build the canonical template specialization type.
3414 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003415 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003416 CanonArgs.reserve(NumArgs);
3417 for (unsigned I = 0; I != NumArgs; ++I)
3418 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3419
3420 // Determine whether this canonical template specialization type already
3421 // exists.
3422 llvm::FoldingSetNodeID ID;
3423 TemplateSpecializationType::Profile(ID, CanonTemplate,
3424 CanonArgs.data(), NumArgs, *this);
3425
Craig Topper36250ad2014-05-12 05:36:57 +00003426 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003427 TemplateSpecializationType *Spec
3428 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3429
3430 if (!Spec) {
3431 // Allocate a new canonical template specialization type.
3432 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3433 sizeof(TemplateArgument) * NumArgs),
3434 TypeAlignment);
3435 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3436 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003437 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003438 Types.push_back(Spec);
3439 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3440 }
3441
3442 assert(Spec->isDependentType() &&
3443 "Non-dependent template-id type must have a canonical type");
3444 return QualType(Spec, 0);
3445}
3446
3447QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003448ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3449 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003450 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003451 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003452 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003453
Craig Topper36250ad2014-05-12 05:36:57 +00003454 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003455 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003456 if (T)
3457 return QualType(T, 0);
3458
Douglas Gregorc42075a2010-02-04 18:10:26 +00003459 QualType Canon = NamedType;
3460 if (!Canon.isCanonical()) {
3461 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003462 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3463 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003464 (void)CheckT;
3465 }
3466
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003467 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003468 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003469 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003470 return QualType(T, 0);
3471}
3472
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003473QualType
Jay Foad39c79802011-01-12 09:06:06 +00003474ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003475 llvm::FoldingSetNodeID ID;
3476 ParenType::Profile(ID, InnerType);
3477
Craig Topper36250ad2014-05-12 05:36:57 +00003478 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003479 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3480 if (T)
3481 return QualType(T, 0);
3482
3483 QualType Canon = InnerType;
3484 if (!Canon.isCanonical()) {
3485 Canon = getCanonicalType(InnerType);
3486 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3487 assert(!CheckT && "Paren canonical type broken");
3488 (void)CheckT;
3489 }
3490
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003491 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003492 Types.push_back(T);
3493 ParenTypes.InsertNode(T, InsertPos);
3494 return QualType(T, 0);
3495}
3496
Douglas Gregor02085352010-03-31 20:19:30 +00003497QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3498 NestedNameSpecifier *NNS,
3499 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003500 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003501 if (Canon.isNull()) {
3502 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003503 ElaboratedTypeKeyword CanonKeyword = Keyword;
3504 if (Keyword == ETK_None)
3505 CanonKeyword = ETK_Typename;
3506
3507 if (CanonNNS != NNS || CanonKeyword != Keyword)
3508 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003509 }
3510
3511 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003512 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003513
Craig Topper36250ad2014-05-12 05:36:57 +00003514 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003515 DependentNameType *T
3516 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003517 if (T)
3518 return QualType(T, 0);
3519
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003520 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003521 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003522 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003523 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003524}
3525
Mike Stump11289f42009-09-09 15:08:12 +00003526QualType
John McCallc392f372010-06-11 00:33:02 +00003527ASTContext::getDependentTemplateSpecializationType(
3528 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003529 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003530 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003531 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003532 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003533 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003534 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3535 ArgCopy.push_back(Args[I].getArgument());
3536 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3537 ArgCopy.size(),
3538 ArgCopy.data());
3539}
3540
3541QualType
3542ASTContext::getDependentTemplateSpecializationType(
3543 ElaboratedTypeKeyword Keyword,
3544 NestedNameSpecifier *NNS,
3545 const IdentifierInfo *Name,
3546 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003547 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003548 assert((!NNS || NNS->isDependent()) &&
3549 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003550
Douglas Gregorc42075a2010-02-04 18:10:26 +00003551 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003552 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3553 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003554
Craig Topper36250ad2014-05-12 05:36:57 +00003555 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003556 DependentTemplateSpecializationType *T
3557 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003558 if (T)
3559 return QualType(T, 0);
3560
John McCallc392f372010-06-11 00:33:02 +00003561 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003562
John McCallc392f372010-06-11 00:33:02 +00003563 ElaboratedTypeKeyword CanonKeyword = Keyword;
3564 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3565
3566 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003567 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003568 for (unsigned I = 0; I != NumArgs; ++I) {
3569 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3570 if (!CanonArgs[I].structurallyEquals(Args[I]))
3571 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003572 }
3573
John McCallc392f372010-06-11 00:33:02 +00003574 QualType Canon;
3575 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3576 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3577 Name, NumArgs,
3578 CanonArgs.data());
3579
3580 // Find the insert position again.
3581 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3582 }
3583
3584 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3585 sizeof(TemplateArgument) * NumArgs),
3586 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003587 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003588 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003589 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003590 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003591 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003592}
3593
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003594QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003595 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003596 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003597 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003598
3599 assert(Pattern->containsUnexpandedParameterPack() &&
3600 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003601 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003602 PackExpansionType *T
3603 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3604 if (T)
3605 return QualType(T, 0);
3606
3607 QualType Canon;
3608 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003609 Canon = getCanonicalType(Pattern);
3610 // The canonical type might not contain an unexpanded parameter pack, if it
3611 // contains an alias template specialization which ignores one of its
3612 // parameters.
3613 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003614 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003615
Richard Smith68eea502012-07-16 00:20:35 +00003616 // Find the insert position again, in case we inserted an element into
3617 // PackExpansionTypes and invalidated our insert position.
3618 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3619 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003620 }
3621
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003622 T = new (*this, TypeAlignment)
3623 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003624 Types.push_back(T);
3625 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003626 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003627}
3628
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003629/// CmpProtocolNames - Comparison predicate for sorting protocols
3630/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003631static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3632 ObjCProtocolDecl *const *RHS) {
3633 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003634}
3635
John McCall8b07ec22010-05-15 11:32:37 +00003636static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003637 unsigned NumProtocols) {
3638 if (NumProtocols == 0) return true;
3639
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003640 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3641 return false;
3642
John McCallfc93cf92009-10-22 22:37:11 +00003643 for (unsigned i = 1; i != NumProtocols; ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003644 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003645 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003646 return false;
3647 return true;
3648}
3649
Craig Topper6a8c1512015-10-22 01:56:18 +00003650static void
3651SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003652 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00003653 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003654
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003655 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00003656 for (ObjCProtocolDecl *&P : Protocols)
3657 P = P->getCanonicalDecl();
3658
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003659 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00003660 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
3661 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003662}
3663
John McCall8b07ec22010-05-15 11:32:37 +00003664QualType ASTContext::getObjCObjectType(QualType BaseType,
3665 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003666 unsigned NumProtocols) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003667 return getObjCObjectType(BaseType, { },
Douglas Gregorab209d82015-07-07 03:58:42 +00003668 llvm::makeArrayRef(Protocols, NumProtocols),
3669 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003670}
3671
3672QualType ASTContext::getObjCObjectType(
3673 QualType baseType,
3674 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003675 ArrayRef<ObjCProtocolDecl *> protocols,
3676 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003677 // If the base type is an interface and there aren't any protocols or
3678 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00003679 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
3680 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00003681 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00003682
3683 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003684 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00003685 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00003686 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003687 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3688 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003689
Douglas Gregore9d95f12015-07-07 03:57:35 +00003690 // Determine the type arguments to be used for canonicalization,
3691 // which may be explicitly specified here or written on the base
3692 // type.
3693 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
3694 if (effectiveTypeArgs.empty()) {
3695 if (auto baseObject = baseType->getAs<ObjCObjectType>())
3696 effectiveTypeArgs = baseObject->getTypeArgs();
3697 }
John McCallfc93cf92009-10-22 22:37:11 +00003698
Douglas Gregore9d95f12015-07-07 03:57:35 +00003699 // Build the canonical type, which has the canonical base type and a
3700 // sorted-and-uniqued list of protocols and the type arguments
3701 // canonicalized.
3702 QualType canonical;
3703 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
3704 effectiveTypeArgs.end(),
3705 [&](QualType type) {
3706 return type.isCanonical();
3707 });
3708 bool protocolsSorted = areSortedAndUniqued(protocols.data(),
3709 protocols.size());
3710 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
3711 // Determine the canonical type arguments.
3712 ArrayRef<QualType> canonTypeArgs;
3713 SmallVector<QualType, 4> canonTypeArgsVec;
3714 if (!typeArgsAreCanonical) {
3715 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
3716 for (auto typeArg : effectiveTypeArgs)
3717 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
3718 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00003719 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003720 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00003721 }
3722
Douglas Gregore9d95f12015-07-07 03:57:35 +00003723 ArrayRef<ObjCProtocolDecl *> canonProtocols;
3724 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
3725 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00003726 canonProtocolsVec.append(protocols.begin(), protocols.end());
3727 SortAndUniqueProtocols(canonProtocolsVec);
3728 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00003729 } else {
3730 canonProtocols = protocols;
3731 }
3732
3733 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003734 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003735
John McCallfc93cf92009-10-22 22:37:11 +00003736 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003737 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3738 }
3739
Douglas Gregore9d95f12015-07-07 03:57:35 +00003740 unsigned size = sizeof(ObjCObjectTypeImpl);
3741 size += typeArgs.size() * sizeof(QualType);
3742 size += protocols.size() * sizeof(ObjCProtocolDecl *);
3743 void *mem = Allocate(size, TypeAlignment);
John McCall8b07ec22010-05-15 11:32:37 +00003744 ObjCObjectTypeImpl *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00003745 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
3746 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00003747
3748 Types.push_back(T);
3749 ObjCObjectTypes.InsertNode(T, InsertPos);
3750 return QualType(T, 0);
3751}
3752
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003753/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3754/// protocol list adopt all protocols in QT's qualified-id protocol
3755/// list.
3756bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3757 ObjCInterfaceDecl *IC) {
3758 if (!QT->isObjCQualifiedIdType())
3759 return false;
3760
3761 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3762 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00003763 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003764 if (!IC->ClassImplementsProtocol(Proto, false))
3765 return false;
3766 }
3767 return true;
3768 }
3769 return false;
3770}
3771
3772/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3773/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3774/// of protocols.
3775bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3776 ObjCInterfaceDecl *IDecl) {
3777 if (!QT->isObjCQualifiedIdType())
3778 return false;
3779 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3780 if (!OPT)
3781 return false;
3782 if (!IDecl->hasDefinition())
3783 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003784 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3785 CollectInheritedProtocols(IDecl, InheritedProtocols);
3786 if (InheritedProtocols.empty())
3787 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003788 // Check that if every protocol in list of id<plist> conforms to a protcol
3789 // of IDecl's, then bridge casting is ok.
3790 bool Conforms = false;
3791 for (auto *Proto : OPT->quals()) {
3792 Conforms = false;
3793 for (auto *PI : InheritedProtocols) {
3794 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3795 Conforms = true;
3796 break;
3797 }
3798 }
3799 if (!Conforms)
3800 break;
3801 }
3802 if (Conforms)
3803 return true;
3804
Aaron Ballman83731462014-03-17 16:14:00 +00003805 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003806 // If both the right and left sides have qualifiers.
3807 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00003808 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003809 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00003810 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003811 break;
3812 }
3813 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003814 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003815 }
3816 return true;
3817}
3818
John McCall8b07ec22010-05-15 11:32:37 +00003819/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3820/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003821QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003822 llvm::FoldingSetNodeID ID;
3823 ObjCObjectPointerType::Profile(ID, ObjectT);
3824
Craig Topper36250ad2014-05-12 05:36:57 +00003825 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003826 if (ObjCObjectPointerType *QT =
3827 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3828 return QualType(QT, 0);
3829
3830 // Find the canonical object type.
3831 QualType Canonical;
3832 if (!ObjectT.isCanonical()) {
3833 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3834
3835 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003836 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3837 }
3838
Douglas Gregorf85bee62010-02-08 22:59:26 +00003839 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003840 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3841 ObjCObjectPointerType *QType =
3842 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003843
Steve Narofffb4330f2009-06-17 22:40:22 +00003844 Types.push_back(QType);
3845 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003846 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003847}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003848
Douglas Gregor1c283312010-08-11 12:19:30 +00003849/// getObjCInterfaceType - Return the unique reference to the type for the
3850/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003851QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3852 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003853 if (Decl->TypeForDecl)
3854 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003855
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003856 if (PrevDecl) {
3857 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3858 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3859 return QualType(PrevDecl->TypeForDecl, 0);
3860 }
3861
Douglas Gregor7671e532011-12-16 16:34:57 +00003862 // Prefer the definition, if there is one.
3863 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3864 Decl = Def;
3865
Douglas Gregor1c283312010-08-11 12:19:30 +00003866 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3867 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3868 Decl->TypeForDecl = T;
3869 Types.push_back(T);
3870 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003871}
3872
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003873/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3874/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003875/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003876/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003877/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003878QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003879 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003880 if (tofExpr->isTypeDependent()) {
3881 llvm::FoldingSetNodeID ID;
3882 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003883
Craig Topper36250ad2014-05-12 05:36:57 +00003884 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003885 DependentTypeOfExprType *Canon
3886 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3887 if (Canon) {
3888 // We already have a "canonical" version of an identical, dependent
3889 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003890 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003891 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003892 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003893 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003894 Canon
3895 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003896 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3897 toe = Canon;
3898 }
3899 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003900 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003901 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003902 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003903 Types.push_back(toe);
3904 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003905}
3906
Steve Naroffa773cd52007-08-01 18:02:17 +00003907/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00003908/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00003909/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00003910/// an issue. This doesn't affect the type checker, since it operates
3911/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003912QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003913 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003914 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003915 Types.push_back(tot);
3916 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003917}
3918
Anders Carlssonad6bd352009-06-24 21:24:56 +00003919
Richard Smith8eb1d322014-06-05 20:13:13 +00003920/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3921/// nodes. This would never be helpful, since each such type has its own
3922/// expression, and would not give a significant memory saving, since there
3923/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00003924QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003925 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00003926
3927 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00003928 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00003929 // unique dependent type. Two such decltype-specifiers refer to the same
3930 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00003931 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003932 llvm::FoldingSetNodeID ID;
3933 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003934
Craig Topper36250ad2014-05-12 05:36:57 +00003935 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00003936 DependentDecltypeType *Canon
3937 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00003938 if (!Canon) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003939 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003940 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003941 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003942 }
Richard Smith8eb1d322014-06-05 20:13:13 +00003943 dt = new (*this, TypeAlignment)
3944 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00003945 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00003946 dt = new (*this, TypeAlignment)
3947 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003948 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003949 Types.push_back(dt);
3950 return QualType(dt, 0);
3951}
3952
Alexis Hunte852b102011-05-24 22:41:36 +00003953/// getUnaryTransformationType - We don't unique these, since the memory
3954/// savings are minimal and these are rare.
3955QualType ASTContext::getUnaryTransformType(QualType BaseType,
3956 QualType UnderlyingType,
3957 UnaryTransformType::UTTKind Kind)
3958 const {
3959 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003960 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3961 Kind,
3962 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003963 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003964 Types.push_back(Ty);
3965 return QualType(Ty, 0);
3966}
3967
Richard Smith2a7d4812013-05-04 07:00:32 +00003968/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3969/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3970/// canonical deduced-but-dependent 'auto' type.
3971QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003972 bool IsDependent) const {
3973 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003974 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003975
Richard Smith2a7d4812013-05-04 07:00:32 +00003976 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00003977 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00003978 llvm::FoldingSetNodeID ID;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003979 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003980 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3981 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003982
Richard Smith74aeef52013-04-26 16:15:35 +00003983 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003984 IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003985 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003986 Types.push_back(AT);
3987 if (InsertPos)
3988 AutoTypes.InsertNode(AT, InsertPos);
3989 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003990}
3991
Eli Friedman0dfb8892011-10-06 23:00:33 +00003992/// getAtomicType - Return the uniqued reference to the atomic type for
3993/// the given value type.
3994QualType ASTContext::getAtomicType(QualType T) const {
3995 // Unique pointers, to guarantee there is only one pointer of a particular
3996 // structure.
3997 llvm::FoldingSetNodeID ID;
3998 AtomicType::Profile(ID, T);
3999
Craig Topper36250ad2014-05-12 05:36:57 +00004000 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004001 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4002 return QualType(AT, 0);
4003
4004 // If the atomic value type isn't canonical, this won't be a canonical type
4005 // either, so fill in the canonical type field.
4006 QualType Canonical;
4007 if (!T.isCanonical()) {
4008 Canonical = getAtomicType(getCanonicalType(T));
4009
4010 // Get the new insert position for the node we care about.
4011 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004012 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004013 }
4014 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4015 Types.push_back(New);
4016 AtomicTypes.InsertNode(New, InsertPos);
4017 return QualType(New, 0);
4018}
4019
Richard Smith02e85f32011-04-14 22:09:26 +00004020/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4021QualType ASTContext::getAutoDeductType() const {
4022 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004023 AutoDeductTy = QualType(
4024 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004025 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004026 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004027 return AutoDeductTy;
4028}
4029
4030/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4031QualType ASTContext::getAutoRRefDeductType() const {
4032 if (AutoRRefDeductTy.isNull())
4033 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4034 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4035 return AutoRRefDeductTy;
4036}
4037
Chris Lattnerfb072462007-01-23 05:45:31 +00004038/// getTagDeclType - Return the unique reference to the type for the
4039/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004040QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00004041 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004042 // FIXME: What is the design on getTagDeclType when it requires casting
4043 // away const? mutable?
4044 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004045}
4046
Mike Stump11289f42009-09-09 15:08:12 +00004047/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4048/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4049/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004050CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004051 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004052}
Chris Lattnerfb072462007-01-23 05:45:31 +00004053
Hans Wennborg27541db2011-10-27 08:29:09 +00004054/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4055CanQualType ASTContext::getIntMaxType() const {
4056 return getFromTargetType(Target->getIntMaxType());
4057}
4058
4059/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4060CanQualType ASTContext::getUIntMaxType() const {
4061 return getFromTargetType(Target->getUIntMaxType());
4062}
4063
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004064/// getSignedWCharType - Return the type of "signed wchar_t".
4065/// Used when in C++, as a GCC extension.
4066QualType ASTContext::getSignedWCharType() const {
4067 // FIXME: derive from "Target" ?
4068 return WCharTy;
4069}
4070
4071/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4072/// Used when in C++, as a GCC extension.
4073QualType ASTContext::getUnsignedWCharType() const {
4074 // FIXME: derive from "Target" ?
4075 return UnsignedIntTy;
4076}
4077
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004078QualType ASTContext::getIntPtrType() const {
4079 return getFromTargetType(Target->getIntPtrType());
4080}
4081
4082QualType ASTContext::getUIntPtrType() const {
4083 return getCorrespondingUnsignedType(getIntPtrType());
4084}
4085
Hans Wennborg27541db2011-10-27 08:29:09 +00004086/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004087/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4088QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004089 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004090}
4091
Eli Friedman4e91899e2012-11-27 02:58:24 +00004092/// \brief Return the unique type for "pid_t" defined in
4093/// <sys/types.h>. We need this to compute the correct type for vfork().
4094QualType ASTContext::getProcessIDType() const {
4095 return getFromTargetType(Target->getProcessIDType());
4096}
4097
Chris Lattnera21ad802008-04-02 05:18:44 +00004098//===----------------------------------------------------------------------===//
4099// Type Operators
4100//===----------------------------------------------------------------------===//
4101
Jay Foad39c79802011-01-12 09:06:06 +00004102CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004103 // Push qualifiers into arrays, and then discard any remaining
4104 // qualifiers.
4105 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004106 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004107 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004108 QualType Result;
4109 if (isa<ArrayType>(Ty)) {
4110 Result = getArrayDecayedType(QualType(Ty,0));
4111 } else if (isa<FunctionType>(Ty)) {
4112 Result = getPointerType(QualType(Ty, 0));
4113 } else {
4114 Result = QualType(Ty, 0);
4115 }
4116
4117 return CanQualType::CreateUnsafe(Result);
4118}
4119
John McCall6c9dd522011-01-18 07:41:22 +00004120QualType ASTContext::getUnqualifiedArrayType(QualType type,
4121 Qualifiers &quals) {
4122 SplitQualType splitType = type.getSplitUnqualifiedType();
4123
4124 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4125 // the unqualified desugared type and then drops it on the floor.
4126 // We then have to strip that sugar back off with
4127 // getUnqualifiedDesugaredType(), which is silly.
4128 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00004129 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004130
4131 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004132 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00004133 quals = splitType.Quals;
4134 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004135 }
4136
John McCall6c9dd522011-01-18 07:41:22 +00004137 // Otherwise, recurse on the array's element type.
4138 QualType elementType = AT->getElementType();
4139 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4140
4141 // If that didn't change the element type, AT has no qualifiers, so we
4142 // can just use the results in splitType.
4143 if (elementType == unqualElementType) {
4144 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004145 quals = splitType.Quals;
4146 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004147 }
4148
4149 // Otherwise, add in the qualifiers from the outermost type, then
4150 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004151 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004152
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004153 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004154 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004155 CAT->getSizeModifier(), 0);
4156 }
4157
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004158 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004159 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004160 }
4161
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004162 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004163 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004164 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004165 VAT->getSizeModifier(),
4166 VAT->getIndexTypeCVRQualifiers(),
4167 VAT->getBracketsRange());
4168 }
4169
4170 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004171 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004172 DSAT->getSizeModifier(), 0,
4173 SourceRange());
4174}
4175
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004176/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4177/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4178/// they point to and return true. If T1 and T2 aren't pointer types
4179/// or pointer-to-member types, or if they are not similar at this
4180/// level, returns false and leaves T1 and T2 unchanged. Top-level
4181/// qualifiers on T1 and T2 are ignored. This function will typically
4182/// be called in a loop that successively "unwraps" pointer and
4183/// pointer-to-member types to compare them at each level.
4184bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4185 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4186 *T2PtrType = T2->getAs<PointerType>();
4187 if (T1PtrType && T2PtrType) {
4188 T1 = T1PtrType->getPointeeType();
4189 T2 = T2PtrType->getPointeeType();
4190 return true;
4191 }
4192
4193 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4194 *T2MPType = T2->getAs<MemberPointerType>();
4195 if (T1MPType && T2MPType &&
4196 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4197 QualType(T2MPType->getClass(), 0))) {
4198 T1 = T1MPType->getPointeeType();
4199 T2 = T2MPType->getPointeeType();
4200 return true;
4201 }
4202
David Blaikiebbafb8a2012-03-11 07:00:24 +00004203 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004204 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4205 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4206 if (T1OPType && T2OPType) {
4207 T1 = T1OPType->getPointeeType();
4208 T2 = T2OPType->getPointeeType();
4209 return true;
4210 }
4211 }
4212
4213 // FIXME: Block pointers, too?
4214
4215 return false;
4216}
4217
Jay Foad39c79802011-01-12 09:06:06 +00004218DeclarationNameInfo
4219ASTContext::getNameForTemplate(TemplateName Name,
4220 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004221 switch (Name.getKind()) {
4222 case TemplateName::QualifiedTemplate:
4223 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004224 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004225 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4226 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004227
John McCalld9dfe3a2011-06-30 08:33:18 +00004228 case TemplateName::OverloadedTemplate: {
4229 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4230 // DNInfo work in progress: CHECKME: what about DNLoc?
4231 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4232 }
4233
4234 case TemplateName::DependentTemplate: {
4235 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004236 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004237 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004238 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4239 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004240 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004241 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4242 // DNInfo work in progress: FIXME: source locations?
4243 DeclarationNameLoc DNLoc;
4244 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4245 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4246 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004247 }
4248 }
4249
John McCalld9dfe3a2011-06-30 08:33:18 +00004250 case TemplateName::SubstTemplateTemplateParm: {
4251 SubstTemplateTemplateParmStorage *subst
4252 = Name.getAsSubstTemplateTemplateParm();
4253 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4254 NameLoc);
4255 }
4256
4257 case TemplateName::SubstTemplateTemplateParmPack: {
4258 SubstTemplateTemplateParmPackStorage *subst
4259 = Name.getAsSubstTemplateTemplateParmPack();
4260 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4261 NameLoc);
4262 }
4263 }
4264
4265 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004266}
4267
Jay Foad39c79802011-01-12 09:06:06 +00004268TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004269 switch (Name.getKind()) {
4270 case TemplateName::QualifiedTemplate:
4271 case TemplateName::Template: {
4272 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004273 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004274 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004275 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4276
4277 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004278 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004279 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004280
John McCalld9dfe3a2011-06-30 08:33:18 +00004281 case TemplateName::OverloadedTemplate:
4282 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004283
John McCalld9dfe3a2011-06-30 08:33:18 +00004284 case TemplateName::DependentTemplate: {
4285 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4286 assert(DTN && "Non-dependent template names must refer to template decls.");
4287 return DTN->CanonicalTemplateName;
4288 }
4289
4290 case TemplateName::SubstTemplateTemplateParm: {
4291 SubstTemplateTemplateParmStorage *subst
4292 = Name.getAsSubstTemplateTemplateParm();
4293 return getCanonicalTemplateName(subst->getReplacement());
4294 }
4295
4296 case TemplateName::SubstTemplateTemplateParmPack: {
4297 SubstTemplateTemplateParmPackStorage *subst
4298 = Name.getAsSubstTemplateTemplateParmPack();
4299 TemplateTemplateParmDecl *canonParameter
4300 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4301 TemplateArgument canonArgPack
4302 = getCanonicalTemplateArgument(subst->getArgumentPack());
4303 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4304 }
4305 }
4306
4307 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004308}
4309
Douglas Gregoradee3e32009-11-11 23:06:43 +00004310bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4311 X = getCanonicalTemplateName(X);
4312 Y = getCanonicalTemplateName(Y);
4313 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4314}
4315
Mike Stump11289f42009-09-09 15:08:12 +00004316TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004317ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004318 switch (Arg.getKind()) {
4319 case TemplateArgument::Null:
4320 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004321
Douglas Gregora8e02e72009-07-28 23:00:59 +00004322 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004323 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004324
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004325 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004326 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004327 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004328 }
Mike Stump11289f42009-09-09 15:08:12 +00004329
Eli Friedmanb826a002012-09-26 02:36:12 +00004330 case TemplateArgument::NullPtr:
4331 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4332 /*isNullPtr*/true);
4333
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004334 case TemplateArgument::Template:
4335 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004336
4337 case TemplateArgument::TemplateExpansion:
4338 return TemplateArgument(getCanonicalTemplateName(
4339 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004340 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004341
Douglas Gregora8e02e72009-07-28 23:00:59 +00004342 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004343 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004344
Douglas Gregora8e02e72009-07-28 23:00:59 +00004345 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004346 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004347
Douglas Gregora8e02e72009-07-28 23:00:59 +00004348 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004349 if (Arg.pack_size() == 0)
4350 return Arg;
4351
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004352 TemplateArgument *CanonArgs
4353 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004354 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004355 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004356 AEnd = Arg.pack_end();
4357 A != AEnd; (void)++A, ++Idx)
4358 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004359
Benjamin Kramercce63472015-08-05 09:40:22 +00004360 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00004361 }
4362 }
4363
4364 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004365 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004366}
4367
Douglas Gregor333489b2009-03-27 23:10:48 +00004368NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004369ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004370 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004371 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004372
4373 switch (NNS->getKind()) {
4374 case NestedNameSpecifier::Identifier:
4375 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004376 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004377 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4378 NNS->getAsIdentifier());
4379
4380 case NestedNameSpecifier::Namespace:
4381 // A namespace is canonical; build a nested-name-specifier with
4382 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004383 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004384 NNS->getAsNamespace()->getOriginalNamespace());
4385
4386 case NestedNameSpecifier::NamespaceAlias:
4387 // A namespace is canonical; build a nested-name-specifier with
4388 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004389 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004390 NNS->getAsNamespaceAlias()->getNamespace()
4391 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004392
4393 case NestedNameSpecifier::TypeSpec:
4394 case NestedNameSpecifier::TypeSpecWithTemplate: {
4395 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004396
4397 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4398 // break it apart into its prefix and identifier, then reconsititute those
4399 // as the canonical nested-name-specifier. This is required to canonicalize
4400 // a dependent nested-name-specifier involving typedefs of dependent-name
4401 // types, e.g.,
4402 // typedef typename T::type T1;
4403 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004404 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4405 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004406 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004407
Eli Friedman5358a0a2012-03-03 04:09:56 +00004408 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4409 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4410 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004411 return NestedNameSpecifier::Create(*this, nullptr, false,
4412 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004413 }
4414
4415 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004416 case NestedNameSpecifier::Super:
4417 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004418 return NNS;
4419 }
4420
David Blaikie8a40f702012-01-17 06:56:22 +00004421 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004422}
4423
Chris Lattner7adf0762008-08-04 07:31:14 +00004424
Jay Foad39c79802011-01-12 09:06:06 +00004425const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004426 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004427 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004428 // Handle the common positive case fast.
4429 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4430 return AT;
4431 }
Mike Stump11289f42009-09-09 15:08:12 +00004432
John McCall8ccfcb52009-09-24 19:53:00 +00004433 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004434 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004435 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004436
John McCall8ccfcb52009-09-24 19:53:00 +00004437 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004438 // implements C99 6.7.3p8: "If the specification of an array type includes
4439 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004440
Chris Lattner7adf0762008-08-04 07:31:14 +00004441 // If we get here, we either have type qualifiers on the type, or we have
4442 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004443 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004444
John McCall33ddac02011-01-19 10:06:00 +00004445 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004446 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004447
Chris Lattner7adf0762008-08-04 07:31:14 +00004448 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004449 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004450 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004451 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004452
Chris Lattner7adf0762008-08-04 07:31:14 +00004453 // Otherwise, we have an array and we have qualifiers on it. Push the
4454 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004455 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004456
Chris Lattner7adf0762008-08-04 07:31:14 +00004457 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4458 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4459 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004460 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004461 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4462 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4463 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004464 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004465
Mike Stump11289f42009-09-09 15:08:12 +00004466 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004467 = dyn_cast<DependentSizedArrayType>(ATy))
4468 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004469 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004470 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004471 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004472 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004473 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004474
Chris Lattner7adf0762008-08-04 07:31:14 +00004475 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004476 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004477 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004478 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004479 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004480 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004481}
4482
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004483QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004484 if (T->isArrayType() || T->isFunctionType())
4485 return getDecayedType(T);
4486 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004487}
4488
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004489QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004490 T = getVariableArrayDecayedType(T);
4491 T = getAdjustedParameterType(T);
4492 return T.getUnqualifiedType();
4493}
4494
David Majnemerd09a51c2015-03-03 01:50:05 +00004495QualType ASTContext::getExceptionObjectType(QualType T) const {
4496 // C++ [except.throw]p3:
4497 // A throw-expression initializes a temporary object, called the exception
4498 // object, the type of which is determined by removing any top-level
4499 // cv-qualifiers from the static type of the operand of throw and adjusting
4500 // the type from "array of T" or "function returning T" to "pointer to T"
4501 // or "pointer to function returning T", [...]
4502 T = getVariableArrayDecayedType(T);
4503 if (T->isArrayType() || T->isFunctionType())
4504 T = getDecayedType(T);
4505 return T.getUnqualifiedType();
4506}
4507
Chris Lattnera21ad802008-04-02 05:18:44 +00004508/// getArrayDecayedType - Return the properly qualified result of decaying the
4509/// specified array type to a pointer. This operation is non-trivial when
4510/// handling typedefs etc. The canonical type of "T" must be an array type,
4511/// this returns a pointer to a properly qualified element of the array.
4512///
4513/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004514QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004515 // Get the element type with 'getAsArrayType' so that we don't lose any
4516 // typedefs in the element type of the array. This also handles propagation
4517 // of type qualifiers from the array type into the element type if present
4518 // (C99 6.7.3p8).
4519 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4520 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004521
Chris Lattner7adf0762008-08-04 07:31:14 +00004522 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004523
4524 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004525 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004526}
4527
John McCall33ddac02011-01-19 10:06:00 +00004528QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4529 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004530}
4531
John McCall33ddac02011-01-19 10:06:00 +00004532QualType ASTContext::getBaseElementType(QualType type) const {
4533 Qualifiers qs;
4534 while (true) {
4535 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004536 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004537 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004538
John McCall33ddac02011-01-19 10:06:00 +00004539 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004540 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004541 }
Mike Stump11289f42009-09-09 15:08:12 +00004542
John McCall33ddac02011-01-19 10:06:00 +00004543 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004544}
4545
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004546/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004547uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004548ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4549 uint64_t ElementCount = 1;
4550 do {
4551 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004552 CA = dyn_cast_or_null<ConstantArrayType>(
4553 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004554 } while (CA);
4555 return ElementCount;
4556}
4557
Steve Naroff0af91202007-04-27 21:51:21 +00004558/// getFloatingRank - Return a relative rank for floating point types.
4559/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004560static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004561 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004562 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004563
John McCall9dd450b2009-09-21 23:43:11 +00004564 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4565 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004566 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004567 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004568 case BuiltinType::Float: return FloatRank;
4569 case BuiltinType::Double: return DoubleRank;
4570 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004571 }
4572}
4573
Mike Stump11289f42009-09-09 15:08:12 +00004574/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4575/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004576/// 'typeDomain' is a real floating point or complex type.
4577/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004578QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4579 QualType Domain) const {
4580 FloatingRank EltRank = getFloatingRank(Size);
4581 if (Domain->isComplexType()) {
4582 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004583 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004584 case FloatRank: return FloatComplexTy;
4585 case DoubleRank: return DoubleComplexTy;
4586 case LongDoubleRank: return LongDoubleComplexTy;
4587 }
Steve Naroff0af91202007-04-27 21:51:21 +00004588 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004589
4590 assert(Domain->isRealFloatingType() && "Unknown domain!");
4591 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004592 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004593 case FloatRank: return FloatTy;
4594 case DoubleRank: return DoubleTy;
4595 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004596 }
David Blaikief47fa302012-01-17 02:30:50 +00004597 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004598}
4599
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004600/// getFloatingTypeOrder - Compare the rank of the two specified floating
4601/// point types, ignoring the domain of the type (i.e. 'double' ==
4602/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004603/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004604int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004605 FloatingRank LHSR = getFloatingRank(LHS);
4606 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004607
Chris Lattnerb90739d2008-04-06 23:38:49 +00004608 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004609 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004610 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004611 return 1;
4612 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004613}
4614
Chris Lattner76a00cf2008-04-06 22:59:24 +00004615/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4616/// routine will assert if passed a built-in type that isn't an integer or enum,
4617/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004618unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004619 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004620
Chris Lattner76a00cf2008-04-06 22:59:24 +00004621 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004622 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004623 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004624 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004625 case BuiltinType::Char_S:
4626 case BuiltinType::Char_U:
4627 case BuiltinType::SChar:
4628 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004629 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004630 case BuiltinType::Short:
4631 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004632 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004633 case BuiltinType::Int:
4634 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004635 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004636 case BuiltinType::Long:
4637 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004638 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004639 case BuiltinType::LongLong:
4640 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004641 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004642 case BuiltinType::Int128:
4643 case BuiltinType::UInt128:
4644 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004645 }
4646}
4647
Eli Friedman629ffb92009-08-20 04:21:42 +00004648/// \brief Whether this is a promotable bitfield reference according
4649/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4650///
4651/// \returns the type this bit-field will promote to, or NULL if no
4652/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004653QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004654 if (E->isTypeDependent() || E->isValueDependent())
4655 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00004656
4657 // FIXME: We should not do this unless E->refersToBitField() is true. This
4658 // matters in C where getSourceBitField() will find bit-fields for various
4659 // cases where the source expression is not a bit-field designator.
4660
John McCalld25db7e2013-05-06 21:39:12 +00004661 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004662 if (!Field)
4663 return QualType();
4664
4665 QualType FT = Field->getType();
4666
Richard Smithcaf33902011-10-10 18:28:20 +00004667 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004668 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00004669 // C++ [conv.prom]p5:
4670 // A prvalue for an integral bit-field can be converted to a prvalue of type
4671 // int if int can represent all the values of the bit-field; otherwise, it
4672 // can be converted to unsigned int if unsigned int can represent all the
4673 // values of the bit-field. If the bit-field is larger yet, no integral
4674 // promotion applies to it.
4675 // C11 6.3.1.1/2:
4676 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4677 // If an int can represent all values of the original type (as restricted by
4678 // the width, for a bit-field), the value is converted to an int; otherwise,
4679 // it is converted to an unsigned int.
4680 //
4681 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4682 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00004683 if (BitWidth < IntSize)
4684 return IntTy;
4685
4686 if (BitWidth == IntSize)
4687 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4688
4689 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00004690 // like the base type. GCC has some weird bugs in this area that we
4691 // deliberately do not follow (GCC follows a pre-standard resolution to
4692 // C's DR315 which treats bit-width as being part of the type, and this leaks
4693 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00004694 return QualType();
4695}
4696
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004697/// getPromotedIntegerType - Returns the type that Promotable will
4698/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4699/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004700QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004701 assert(!Promotable.isNull());
4702 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004703 if (const EnumType *ET = Promotable->getAs<EnumType>())
4704 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004705
4706 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4707 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4708 // (3.9.1) can be converted to a prvalue of the first of the following
4709 // types that can represent all the values of its underlying type:
4710 // int, unsigned int, long int, unsigned long int, long long int, or
4711 // unsigned long long int [...]
4712 // FIXME: Is there some better way to compute this?
4713 if (BT->getKind() == BuiltinType::WChar_S ||
4714 BT->getKind() == BuiltinType::WChar_U ||
4715 BT->getKind() == BuiltinType::Char16 ||
4716 BT->getKind() == BuiltinType::Char32) {
4717 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4718 uint64_t FromSize = getTypeSize(BT);
4719 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4720 LongLongTy, UnsignedLongLongTy };
4721 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4722 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4723 if (FromSize < ToSize ||
4724 (FromSize == ToSize &&
4725 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4726 return PromoteTypes[Idx];
4727 }
4728 llvm_unreachable("char type should fit into long long");
4729 }
4730 }
4731
4732 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004733 if (Promotable->isSignedIntegerType())
4734 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004735 uint64_t PromotableSize = getIntWidth(Promotable);
4736 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004737 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4738 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4739}
4740
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004741/// \brief Recurses in pointer/array types until it finds an objc retainable
4742/// type and returns its ownership.
4743Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4744 while (!T.isNull()) {
4745 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4746 return T.getObjCLifetime();
4747 if (T->isArrayType())
4748 T = getBaseElementType(T);
4749 else if (const PointerType *PT = T->getAs<PointerType>())
4750 T = PT->getPointeeType();
4751 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004752 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004753 else
4754 break;
4755 }
4756
4757 return Qualifiers::OCL_None;
4758}
4759
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004760static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4761 // Incomplete enum types are not treated as integer types.
4762 // FIXME: In C++, enum types are never integer types.
4763 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4764 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00004765 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004766}
4767
Mike Stump11289f42009-09-09 15:08:12 +00004768/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004769/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004770/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004771int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004772 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4773 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004774
4775 // Unwrap enums to their underlying type.
4776 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4777 LHSC = getIntegerTypeForEnum(ET);
4778 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4779 RHSC = getIntegerTypeForEnum(ET);
4780
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004781 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004782
Chris Lattner76a00cf2008-04-06 22:59:24 +00004783 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4784 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004785
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004786 unsigned LHSRank = getIntegerRank(LHSC);
4787 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004788
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004789 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4790 if (LHSRank == RHSRank) return 0;
4791 return LHSRank > RHSRank ? 1 : -1;
4792 }
Mike Stump11289f42009-09-09 15:08:12 +00004793
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004794 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4795 if (LHSUnsigned) {
4796 // If the unsigned [LHS] type is larger, return it.
4797 if (LHSRank >= RHSRank)
4798 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004799
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004800 // If the signed type can represent all values of the unsigned type, it
4801 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004802 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004803 return -1;
4804 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004805
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004806 // If the unsigned [RHS] type is larger, return it.
4807 if (RHSRank >= LHSRank)
4808 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004809
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004810 // If the signed type can represent all values of the unsigned type, it
4811 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004812 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004813 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004814}
Anders Carlsson98f07902007-08-17 05:31:46 +00004815
Mike Stump11289f42009-09-09 15:08:12 +00004816// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004817QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004818 if (!CFConstantStringTypeDecl) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004819 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
John McCallae580fe2010-02-05 01:33:36 +00004820 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004821
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004822 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004823
Anders Carlsson98f07902007-08-17 05:31:46 +00004824 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004825 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004826 // int flags;
4827 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004828 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004829 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004830 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004831 FieldTypes[3] = LongTy;
4832
Anders Carlsson98f07902007-08-17 05:31:46 +00004833 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004834 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004835 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004836 SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004837 SourceLocation(), nullptr,
4838 FieldTypes[i], /*TInfo=*/nullptr,
4839 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00004840 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004841 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004842 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004843 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004844 }
4845
Douglas Gregord5058122010-02-11 01:19:42 +00004846 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004847 }
Mike Stump11289f42009-09-09 15:08:12 +00004848
Anders Carlsson98f07902007-08-17 05:31:46 +00004849 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004850}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004851
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004852QualType ASTContext::getObjCSuperType() const {
4853 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004854 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004855 TUDecl->addDecl(ObjCSuperTypeDecl);
4856 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4857 }
4858 return ObjCSuperType;
4859}
4860
Douglas Gregor512b0772009-04-23 22:29:11 +00004861void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004862 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004863 assert(Rec && "Invalid CFConstantStringType");
4864 CFConstantStringTypeDecl = Rec->getDecl();
4865}
4866
Jay Foad39c79802011-01-12 09:06:06 +00004867QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004868 if (BlockDescriptorType)
4869 return getTagDeclType(BlockDescriptorType);
4870
Alp Toker2dea15b2013-12-17 01:22:38 +00004871 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004872 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004873 RD = buildImplicitRecord("__block_descriptor");
4874 RD->startDefinition();
4875
Mike Stumpd0153282009-10-20 02:12:22 +00004876 QualType FieldTypes[] = {
4877 UnsignedLongTy,
4878 UnsignedLongTy,
4879 };
4880
Craig Topperd6d31ac2013-07-15 08:24:27 +00004881 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004882 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004883 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004884 };
4885
4886 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004887 FieldDecl *Field = FieldDecl::Create(
4888 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004889 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4890 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004891 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004892 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004893 }
4894
Alp Toker2dea15b2013-12-17 01:22:38 +00004895 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004896
Alp Toker2dea15b2013-12-17 01:22:38 +00004897 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004898
4899 return getTagDeclType(BlockDescriptorType);
4900}
4901
Jay Foad39c79802011-01-12 09:06:06 +00004902QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004903 if (BlockDescriptorExtendedType)
4904 return getTagDeclType(BlockDescriptorExtendedType);
4905
Alp Toker2dea15b2013-12-17 01:22:38 +00004906 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004907 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004908 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4909 RD->startDefinition();
4910
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004911 QualType FieldTypes[] = {
4912 UnsignedLongTy,
4913 UnsignedLongTy,
4914 getPointerType(VoidPtrTy),
4915 getPointerType(VoidPtrTy)
4916 };
4917
Craig Topperd6d31ac2013-07-15 08:24:27 +00004918 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004919 "reserved",
4920 "Size",
4921 "CopyFuncPtr",
4922 "DestroyFuncPtr"
4923 };
4924
4925 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004926 FieldDecl *Field = FieldDecl::Create(
4927 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004928 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4929 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00004930 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004931 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004932 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004933 }
4934
Alp Toker2dea15b2013-12-17 01:22:38 +00004935 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004936
Alp Toker2dea15b2013-12-17 01:22:38 +00004937 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004938 return getTagDeclType(BlockDescriptorExtendedType);
4939}
4940
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004941/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4942/// requires copy/dispose. Note that this must match the logic
4943/// in buildByrefHelpers.
4944bool ASTContext::BlockRequiresCopying(QualType Ty,
4945 const VarDecl *D) {
4946 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4947 const Expr *copyExpr = getBlockVarCopyInits(D);
4948 if (!copyExpr && record->hasTrivialDestructor()) return false;
4949
Mike Stump94967902009-10-21 18:16:27 +00004950 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004951 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004952
4953 if (!Ty->isObjCRetainableType()) return false;
4954
4955 Qualifiers qs = Ty.getQualifiers();
4956
4957 // If we have lifetime, that dominates.
4958 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004959 switch (lifetime) {
4960 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4961
4962 // These are just bits as far as the runtime is concerned.
4963 case Qualifiers::OCL_ExplicitNone:
4964 case Qualifiers::OCL_Autoreleasing:
4965 return false;
4966
4967 // Tell the runtime that this is ARC __weak, called by the
4968 // byref routines.
4969 case Qualifiers::OCL_Weak:
4970 // ARC __strong __block variables need to be retained.
4971 case Qualifiers::OCL_Strong:
4972 return true;
4973 }
4974 llvm_unreachable("fell out of lifetime switch!");
4975 }
4976 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4977 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004978}
4979
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004980bool ASTContext::getByrefLifetime(QualType Ty,
4981 Qualifiers::ObjCLifetime &LifeTime,
4982 bool &HasByrefExtendedLayout) const {
4983
4984 if (!getLangOpts().ObjC1 ||
4985 getLangOpts().getGC() != LangOptions::NonGC)
4986 return false;
4987
4988 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004989 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004990 HasByrefExtendedLayout = true;
4991 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00004992 } else if ((LifeTime = Ty.getObjCLifetime())) {
4993 // Honor the ARC qualifiers.
4994 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
4995 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004996 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00004997 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004998 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00004999 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005000 return true;
5001}
5002
Douglas Gregorbab8a962011-09-08 01:46:34 +00005003TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5004 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00005005 ObjCInstanceTypeDecl =
5006 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00005007 return ObjCInstanceTypeDecl;
5008}
5009
Anders Carlsson18acd442007-10-29 06:33:42 +00005010// This returns true if a type has been typedefed to BOOL:
5011// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00005012static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00005013 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00005014 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5015 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00005016
Anders Carlssond8499822007-10-29 05:01:08 +00005017 return false;
5018}
5019
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005020/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005021/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00005022CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00005023 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5024 return CharUnits::Zero();
5025
Ken Dyck40775002010-01-11 17:06:35 +00005026 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00005027
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005028 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00005029 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00005030 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005031 // Treat arrays as pointers, since that's how they're passed in.
5032 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00005033 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00005034 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00005035}
5036
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005037bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00005038 return getTargetInfo().getCXXABI().isMicrosoft() &&
5039 VD->isStaticDataMember() &&
David Majnemerfac52432015-10-19 23:22:49 +00005040 VD->getType()->isIntegralOrEnumerationType() &&
5041 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005042}
5043
Ken Dyck40775002010-01-11 17:06:35 +00005044static inline
5045std::string charUnitsToString(const CharUnits &CU) {
5046 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005047}
5048
John McCall351762c2011-02-07 10:33:21 +00005049/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00005050/// declaration.
John McCall351762c2011-02-07 10:33:21 +00005051std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5052 std::string S;
5053
David Chisnall950a9512009-11-17 19:33:30 +00005054 const BlockDecl *Decl = Expr->getBlockDecl();
5055 QualType BlockTy =
5056 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5057 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005058 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00005059 getObjCEncodingForMethodParameter(
5060 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5061 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005062 else
Alp Toker314cc812014-01-25 16:55:45 +00005063 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00005064 // Compute size of all parameters.
5065 // Start with computing size of a pointer in number of bytes.
5066 // FIXME: There might(should) be a better way of doing this computation!
5067 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005068 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5069 CharUnits ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005070 for (auto PI : Decl->params()) {
5071 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005072 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00005073 if (sz.isZero())
5074 continue;
Ken Dyck40775002010-01-11 17:06:35 +00005075 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00005076 ParmOffset += sz;
5077 }
5078 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00005079 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00005080 // Block pointer and offset.
5081 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00005082
5083 // Argument types.
5084 ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005085 for (auto PVDecl : Decl->params()) {
David Chisnall950a9512009-11-17 19:33:30 +00005086 QualType PType = PVDecl->getOriginalType();
5087 if (const ArrayType *AT =
5088 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5089 // Use array's original type only if it has known number of
5090 // elements.
5091 if (!isa<ConstantArrayType>(AT))
5092 PType = PVDecl->getType();
5093 } else if (PType->isFunctionType())
5094 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005095 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005096 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5097 S, true /*Extended*/);
5098 else
5099 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00005100 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005101 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00005102 }
John McCall351762c2011-02-07 10:33:21 +00005103
5104 return S;
David Chisnall950a9512009-11-17 19:33:30 +00005105}
5106
Douglas Gregora9d84932011-05-27 01:19:52 +00005107bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00005108 std::string& S) {
5109 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00005110 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00005111 CharUnits ParmOffset;
5112 // Compute size of all parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005113 for (auto PI : Decl->params()) {
5114 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00005115 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005116 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005117 continue;
5118
David Chisnall50e4eba2010-12-30 14:05:53 +00005119 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00005120 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00005121 ParmOffset += sz;
5122 }
5123 S += charUnitsToString(ParmOffset);
5124 ParmOffset = CharUnits::Zero();
5125
5126 // Argument types.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005127 for (auto PVDecl : Decl->params()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005128 QualType PType = PVDecl->getOriginalType();
5129 if (const ArrayType *AT =
5130 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5131 // Use array's original type only if it has known number of
5132 // elements.
5133 if (!isa<ConstantArrayType>(AT))
5134 PType = PVDecl->getType();
5135 } else if (PType->isFunctionType())
5136 PType = PVDecl->getType();
5137 getObjCEncodingForType(PType, S);
5138 S += charUnitsToString(ParmOffset);
5139 ParmOffset += getObjCEncodingTypeSize(PType);
5140 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005141
5142 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00005143}
5144
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005145/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5146/// method parameter or return type. If Extended, include class names and
5147/// block object types.
5148void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5149 QualType T, std::string& S,
5150 bool Extended) const {
5151 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5152 getObjCEncodingForTypeQualifier(QT, S);
5153 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005154 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005155 true /*OutermostType*/,
5156 false /*EncodingProperty*/,
5157 false /*StructField*/,
5158 Extended /*EncodeBlockParameters*/,
5159 Extended /*EncodeClassNames*/);
5160}
5161
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005162/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005163/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00005164bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005165 std::string& S,
5166 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005167 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005168 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00005169 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5170 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005171 // Compute size of all parameters.
5172 // Start with computing size of a pointer in number of bytes.
5173 // FIXME: There might(should) be a better way of doing this computation!
5174 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005175 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005176 // The first two arguments (self and _cmd) are pointers; account for
5177 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00005178 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005179 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005180 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005181 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005182 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005183 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005184 continue;
5185
Ken Dyck40775002010-01-11 17:06:35 +00005186 assert (sz.isPositive() &&
5187 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005188 ParmOffset += sz;
5189 }
Ken Dyck40775002010-01-11 17:06:35 +00005190 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005191 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005192 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005193
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005194 // Argument types.
5195 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005196 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005197 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005198 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005199 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005200 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005201 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5202 // Use array's original type only if it has known number of
5203 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005204 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005205 PType = PVDecl->getType();
5206 } else if (PType->isFunctionType())
5207 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005208 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5209 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005210 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005211 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005212 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005213
5214 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005215}
5216
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005217ObjCPropertyImplDecl *
5218ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5219 const ObjCPropertyDecl *PD,
5220 const Decl *Container) const {
5221 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005222 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005223 if (const ObjCCategoryImplDecl *CID =
5224 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005225 for (auto *PID : CID->property_impls())
5226 if (PID->getPropertyDecl() == PD)
5227 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005228 } else {
5229 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5230 for (auto *PID : OID->property_impls())
5231 if (PID->getPropertyDecl() == PD)
5232 return PID;
5233 }
5234 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005235}
5236
Daniel Dunbar4932b362008-08-28 04:38:10 +00005237/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005238/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005239/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5240/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005241/// Property attributes are stored as a comma-delimited C string. The simple
5242/// attributes readonly and bycopy are encoded as single characters. The
5243/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5244/// encoded as single characters, followed by an identifier. Property types
5245/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005246/// these attributes are defined by the following enumeration:
5247/// @code
5248/// enum PropertyAttributes {
5249/// kPropertyReadOnly = 'R', // property is read-only.
5250/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5251/// kPropertyByref = '&', // property is a reference to the value last assigned
5252/// kPropertyDynamic = 'D', // property is dynamic
5253/// kPropertyGetter = 'G', // followed by getter selector name
5254/// kPropertySetter = 'S', // followed by setter selector name
5255/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005256/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005257/// kPropertyWeak = 'W' // 'weak' property
5258/// kPropertyStrong = 'P' // property GC'able
5259/// kPropertyNonAtomic = 'N' // property non-atomic
5260/// };
5261/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005262void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005263 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005264 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005265 // Collect information from the property implementation decl(s).
5266 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005267 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005268
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005269 if (ObjCPropertyImplDecl *PropertyImpDecl =
5270 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5271 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5272 Dynamic = true;
5273 else
5274 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005275 }
5276
5277 // FIXME: This is not very efficient.
5278 S = "T";
5279
5280 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005281 // GCC has some special rules regarding encoding of properties which
5282 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005283 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005284
5285 if (PD->isReadOnly()) {
5286 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005287 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5288 S += ",C";
5289 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5290 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005291 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5292 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005293 } else {
5294 switch (PD->getSetterKind()) {
5295 case ObjCPropertyDecl::Assign: break;
5296 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005297 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005298 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005299 }
5300 }
5301
5302 // It really isn't clear at all what this means, since properties
5303 // are "dynamic by default".
5304 if (Dynamic)
5305 S += ",D";
5306
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005307 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5308 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005309
Daniel Dunbar4932b362008-08-28 04:38:10 +00005310 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5311 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005312 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005313 }
5314
5315 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5316 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005317 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005318 }
5319
5320 if (SynthesizePID) {
5321 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5322 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005323 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005324 }
5325
5326 // FIXME: OBJCGC: weak & strong
5327}
5328
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005329/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005330/// Another legacy compatibility encoding: 32-bit longs are encoded as
5331/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005332/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5333///
5334void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005335 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005336 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005337 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005338 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005339 else
Jay Foad39c79802011-01-12 09:06:06 +00005340 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005341 PointeeTy = IntTy;
5342 }
5343 }
5344}
5345
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005346void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005347 const FieldDecl *Field,
5348 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005349 // We follow the behavior of gcc, expanding structures which are
5350 // directly pointed to, and expanding embedded structures. Note that
5351 // these rules are sufficient to prevent recursive encoding of the
5352 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005353 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005354 true /* outermost type */, false, false,
5355 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005356}
5357
Joe Groff98ac7d22014-07-07 22:25:15 +00005358void ASTContext::getObjCEncodingForPropertyType(QualType T,
5359 std::string& S) const {
5360 // Encode result type.
5361 // GCC has some special rules regarding encoding of properties which
5362 // closely resembles encoding of ivars.
5363 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5364 true /* outermost type */,
5365 true /* encoding property */);
5366}
5367
John McCall393a78d2012-12-20 02:45:14 +00005368static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5369 BuiltinType::Kind kind) {
5370 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005371 case BuiltinType::Void: return 'v';
5372 case BuiltinType::Bool: return 'B';
5373 case BuiltinType::Char_U:
5374 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005375 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005376 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005377 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005378 case BuiltinType::UInt: return 'I';
5379 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005380 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005381 case BuiltinType::UInt128: return 'T';
5382 case BuiltinType::ULongLong: return 'Q';
5383 case BuiltinType::Char_S:
5384 case BuiltinType::SChar: return 'c';
5385 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005386 case BuiltinType::WChar_S:
5387 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005388 case BuiltinType::Int: return 'i';
5389 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005390 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005391 case BuiltinType::LongLong: return 'q';
5392 case BuiltinType::Int128: return 't';
5393 case BuiltinType::Float: return 'f';
5394 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005395 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005396 case BuiltinType::NullPtr: return '*'; // like char*
5397
5398 case BuiltinType::Half:
5399 // FIXME: potentially need @encodes for these!
5400 return ' ';
5401
5402 case BuiltinType::ObjCId:
5403 case BuiltinType::ObjCClass:
5404 case BuiltinType::ObjCSel:
5405 llvm_unreachable("@encoding ObjC primitive type");
5406
5407 // OpenCL and placeholder types don't need @encodings.
5408 case BuiltinType::OCLImage1d:
5409 case BuiltinType::OCLImage1dArray:
5410 case BuiltinType::OCLImage1dBuffer:
5411 case BuiltinType::OCLImage2d:
5412 case BuiltinType::OCLImage2dArray:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005413 case BuiltinType::OCLImage2dDepth:
5414 case BuiltinType::OCLImage2dArrayDepth:
5415 case BuiltinType::OCLImage2dMSAA:
5416 case BuiltinType::OCLImage2dArrayMSAA:
5417 case BuiltinType::OCLImage2dMSAADepth:
5418 case BuiltinType::OCLImage2dArrayMSAADepth:
John McCall393a78d2012-12-20 02:45:14 +00005419 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005420 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005421 case BuiltinType::OCLClkEvent:
5422 case BuiltinType::OCLQueue:
5423 case BuiltinType::OCLNDRange:
5424 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00005425 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005426 case BuiltinType::Dependent:
5427#define BUILTIN_TYPE(KIND, ID)
5428#define PLACEHOLDER_TYPE(KIND, ID) \
5429 case BuiltinType::KIND:
5430#include "clang/AST/BuiltinTypes.def"
5431 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005432 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005433 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005434}
5435
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005436static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5437 EnumDecl *Enum = ET->getDecl();
5438
5439 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5440 if (!Enum->isFixed())
5441 return 'i';
5442
5443 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005444 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5445 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005446}
5447
Jay Foad39c79802011-01-12 09:06:06 +00005448static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005449 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005450 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005451 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005452 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5453 // The GNU runtime requires more information; bitfields are encoded as b,
5454 // then the offset (in bits) of the first element, then the type of the
5455 // bitfield, then the size in bits. For example, in this structure:
5456 //
5457 // struct
5458 // {
5459 // int integer;
5460 // int flags:2;
5461 // };
5462 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5463 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5464 // information is not especially sensible, but we're stuck with it for
5465 // compatibility with GCC, although providing it breaks anything that
5466 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005467 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005468 const RecordDecl *RD = FD->getParent();
5469 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005470 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005471 if (const EnumType *ET = T->getAs<EnumType>())
5472 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005473 else {
5474 const BuiltinType *BT = T->castAs<BuiltinType>();
5475 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5476 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005477 }
Richard Smithcaf33902011-10-10 18:28:20 +00005478 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005479}
5480
Daniel Dunbar07d07852009-10-18 21:17:35 +00005481// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005482void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5483 bool ExpandPointedToStructures,
5484 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005485 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005486 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005487 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005488 bool StructField,
5489 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005490 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005491 bool EncodePointerToObjCTypedef,
5492 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00005493 CanQualType CT = getCanonicalType(T);
5494 switch (CT->getTypeClass()) {
5495 case Type::Builtin:
5496 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005497 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005498 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005499 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5500 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5501 else
5502 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005503 return;
Mike Stump11289f42009-09-09 15:08:12 +00005504
John McCall393a78d2012-12-20 02:45:14 +00005505 case Type::Complex: {
5506 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005507 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005508 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005509 return;
5510 }
John McCall393a78d2012-12-20 02:45:14 +00005511
5512 case Type::Atomic: {
5513 const AtomicType *AT = T->castAs<AtomicType>();
5514 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005515 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00005516 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005517 }
John McCall393a78d2012-12-20 02:45:14 +00005518
5519 // encoding for pointer or reference types.
5520 case Type::Pointer:
5521 case Type::LValueReference:
5522 case Type::RValueReference: {
5523 QualType PointeeTy;
5524 if (isa<PointerType>(CT)) {
5525 const PointerType *PT = T->castAs<PointerType>();
5526 if (PT->isObjCSelType()) {
5527 S += ':';
5528 return;
5529 }
5530 PointeeTy = PT->getPointeeType();
5531 } else {
5532 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5533 }
5534
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005535 bool isReadOnly = false;
5536 // For historical/compatibility reasons, the read-only qualifier of the
5537 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5538 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005539 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005540 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005541 if (OutermostType && T.isConstQualified()) {
5542 isReadOnly = true;
5543 S += 'r';
5544 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005545 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005546 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005547 while (P->getAs<PointerType>())
5548 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005549 if (P.isConstQualified()) {
5550 isReadOnly = true;
5551 S += 'r';
5552 }
5553 }
5554 if (isReadOnly) {
5555 // Another legacy compatibility encoding. Some ObjC qualifier and type
5556 // combinations need to be rearranged.
5557 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005558 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005559 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005560 }
Mike Stump11289f42009-09-09 15:08:12 +00005561
Anders Carlssond8499822007-10-29 05:01:08 +00005562 if (PointeeTy->isCharType()) {
5563 // char pointer types should be encoded as '*' unless it is a
5564 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005565 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005566 S += '*';
5567 return;
5568 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005569 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005570 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5571 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5572 S += '#';
5573 return;
5574 }
5575 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5576 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5577 S += '@';
5578 return;
5579 }
5580 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005581 }
Anders Carlssond8499822007-10-29 05:01:08 +00005582 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005583 getLegacyIntegralTypeEncoding(PointeeTy);
5584
Mike Stump11289f42009-09-09 15:08:12 +00005585 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005586 nullptr, false, false, false, false, false, false,
5587 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005588 return;
5589 }
John McCall393a78d2012-12-20 02:45:14 +00005590
5591 case Type::ConstantArray:
5592 case Type::IncompleteArray:
5593 case Type::VariableArray: {
5594 const ArrayType *AT = cast<ArrayType>(CT);
5595
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005596 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005597 // Incomplete arrays are encoded as a pointer to the array element.
5598 S += '^';
5599
Mike Stump11289f42009-09-09 15:08:12 +00005600 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005601 false, ExpandStructures, FD);
5602 } else {
5603 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005604
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005605 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5606 S += llvm::utostr(CAT->getSize().getZExtValue());
5607 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005608 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005609 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5610 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005611 S += '0';
5612 }
Mike Stump11289f42009-09-09 15:08:12 +00005613
5614 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005615 false, ExpandStructures, FD,
5616 false, false, false, false, false, false,
5617 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00005618 S += ']';
5619 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005620 return;
5621 }
Mike Stump11289f42009-09-09 15:08:12 +00005622
John McCall393a78d2012-12-20 02:45:14 +00005623 case Type::FunctionNoProto:
5624 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005625 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005626 return;
Mike Stump11289f42009-09-09 15:08:12 +00005627
John McCall393a78d2012-12-20 02:45:14 +00005628 case Type::Record: {
5629 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005630 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005631 // Anonymous structures print as '?'
5632 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5633 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005634 if (ClassTemplateSpecializationDecl *Spec
5635 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5636 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005637 llvm::raw_string_ostream OS(S);
5638 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005639 TemplateArgs.data(),
5640 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005641 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005642 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005643 } else {
5644 S += '?';
5645 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005646 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005647 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005648 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005649 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005650 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005651 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005652 if (FD) {
5653 S += '"';
5654 S += Field->getNameAsString();
5655 S += '"';
5656 }
Mike Stump11289f42009-09-09 15:08:12 +00005657
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005658 // Special case bit-fields.
5659 if (Field->isBitField()) {
5660 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005661 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005662 } else {
5663 QualType qt = Field->getType();
5664 getLegacyIntegralTypeEncoding(qt);
5665 getObjCEncodingForTypeImpl(qt, S, false, true,
5666 FD, /*OutermostType*/false,
5667 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005668 /*StructField*/true,
5669 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005670 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005671 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005672 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005673 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005674 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005675 return;
5676 }
Mike Stump11289f42009-09-09 15:08:12 +00005677
John McCall393a78d2012-12-20 02:45:14 +00005678 case Type::BlockPointer: {
5679 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005680 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005681 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005682 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005683
5684 S += '<';
5685 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005686 getObjCEncodingForTypeImpl(
5687 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5688 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005689 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5690 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005691 // Block self
5692 S += "@?";
5693 // Block parameters
5694 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005695 for (const auto &I : FPT->param_types())
5696 getObjCEncodingForTypeImpl(
5697 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5698 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005699 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5700 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005701 }
5702 S += '>';
5703 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005704 return;
5705 }
Mike Stump11289f42009-09-09 15:08:12 +00005706
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005707 case Type::ObjCObject: {
5708 // hack to match legacy encoding of *id and *Class
5709 QualType Ty = getObjCObjectPointerType(CT);
5710 if (Ty->isObjCIdType()) {
5711 S += "{objc_object=}";
5712 return;
5713 }
5714 else if (Ty->isObjCClassType()) {
5715 S += "{objc_class=}";
5716 return;
5717 }
5718 }
5719
John McCall393a78d2012-12-20 02:45:14 +00005720 case Type::ObjCInterface: {
5721 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005722 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00005723 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005724 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005725 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005726 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005727 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005728 DeepCollectObjCIvars(OI, true, Ivars);
5729 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005730 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005731 if (Field->isBitField())
5732 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005733 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005734 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5735 false, false, false, false, false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005736 EncodePointerToObjCTypedef,
5737 NotEncodedT);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005738 }
5739 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005740 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005741 }
Mike Stump11289f42009-09-09 15:08:12 +00005742
John McCall393a78d2012-12-20 02:45:14 +00005743 case Type::ObjCObjectPointer: {
5744 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005745 if (OPT->isObjCIdType()) {
5746 S += '@';
5747 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005748 }
Mike Stump11289f42009-09-09 15:08:12 +00005749
Steve Narofff0c86112009-10-28 22:03:49 +00005750 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5751 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5752 // Since this is a binary compatibility issue, need to consult with runtime
5753 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005754 S += '#';
5755 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005756 }
Mike Stump11289f42009-09-09 15:08:12 +00005757
Chris Lattnere7cabb92009-07-13 00:10:46 +00005758 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005759 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005760 ExpandPointedToStructures,
5761 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005762 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005763 // Note that we do extended encoding of protocol qualifer list
5764 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005765 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00005766 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005767 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005768 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005769 S += '>';
5770 }
5771 S += '"';
5772 }
5773 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005774 }
Mike Stump11289f42009-09-09 15:08:12 +00005775
Chris Lattnere7cabb92009-07-13 00:10:46 +00005776 QualType PointeeTy = OPT->getPointeeType();
5777 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005778 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5779 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005780 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005781 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005782 // {...};
5783 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005784 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005785 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005786 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5787 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5788 DeepCollectObjCIvars(OI, true, Ivars);
5789 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5790 if (cast<FieldDecl>(Ivars[i]) == FD) {
5791 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005792 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005793 S += '}';
5794 return;
5795 }
5796 }
5797 }
Mike Stump11289f42009-09-09 15:08:12 +00005798 getObjCEncodingForTypeImpl(PointeeTy, S,
5799 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00005800 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005801 false, false, false, false, false,
5802 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005803 return;
5804 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005805
5806 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005807 if (OPT->getInterfaceDecl() &&
5808 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005809 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005810 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00005811 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005812 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005813 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00005814 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005815 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005816 S += '"';
5817 }
5818 return;
5819 }
Mike Stump11289f42009-09-09 15:08:12 +00005820
John McCalla9e6e8d2010-05-17 23:56:34 +00005821 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005822 // FIXME: we shoul do better than that. 'M' is available.
5823 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005824 // This matches gcc's encoding, even though technically it is insufficient.
5825 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00005826 case Type::Vector:
5827 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005828 // Until we have a coherent encoding of these three types, issue warning.
5829 { if (NotEncodedT)
5830 *NotEncodedT = T;
5831 return;
5832 }
5833
5834 // We could see an undeduced auto type here during error recovery.
5835 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00005836 case Type::Auto:
Richard Smith27d807c2013-04-30 13:56:41 +00005837 return;
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005838
Richard Smith27d807c2013-04-30 13:56:41 +00005839
John McCall393a78d2012-12-20 02:45:14 +00005840#define ABSTRACT_TYPE(KIND, BASE)
5841#define TYPE(KIND, BASE)
5842#define DEPENDENT_TYPE(KIND, BASE) \
5843 case Type::KIND:
5844#define NON_CANONICAL_TYPE(KIND, BASE) \
5845 case Type::KIND:
5846#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5847 case Type::KIND:
5848#include "clang/AST/TypeNodes.def"
5849 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005850 }
John McCall393a78d2012-12-20 02:45:14 +00005851 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005852}
5853
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005854void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5855 std::string &S,
5856 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005857 bool includeVBases,
5858 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005859 assert(RDecl && "Expected non-null RecordDecl");
5860 assert(!RDecl->isUnion() && "Should not be called for unions");
5861 if (!RDecl->getDefinition())
5862 return;
5863
5864 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5865 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5866 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5867
5868 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00005869 for (const auto &BI : CXXRec->bases()) {
5870 if (!BI.isVirtual()) {
5871 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005872 if (base->isEmpty())
5873 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005874 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005875 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5876 std::make_pair(offs, base));
5877 }
5878 }
5879 }
5880
5881 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00005882 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005883 uint64_t offs = layout.getFieldOffset(i);
5884 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00005885 std::make_pair(offs, Field));
5886 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005887 }
5888
5889 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005890 for (const auto &BI : CXXRec->vbases()) {
5891 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005892 if (base->isEmpty())
5893 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005894 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005895 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5896 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005897 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5898 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005899 }
5900 }
5901
5902 CharUnits size;
5903 if (CXXRec) {
5904 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5905 } else {
5906 size = layout.getSize();
5907 }
5908
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005909#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005910 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005911#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005912 std::multimap<uint64_t, NamedDecl *>::iterator
5913 CurLayObj = FieldOrBaseOffsets.begin();
5914
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005915 if (CXXRec && CXXRec->isDynamicClass() &&
5916 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005917 if (FD) {
5918 S += "\"_vptr$";
5919 std::string recname = CXXRec->getNameAsString();
5920 if (recname.empty()) recname = "?";
5921 S += recname;
5922 S += '"';
5923 }
5924 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005925#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005926 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005927#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005928 }
5929
5930 if (!RDecl->hasFlexibleArrayMember()) {
5931 // Mark the end of the structure.
5932 uint64_t offs = toBits(size);
5933 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00005934 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005935 }
5936
5937 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005938#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005939 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005940 if (CurOffs < CurLayObj->first) {
5941 uint64_t padding = CurLayObj->first - CurOffs;
5942 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5943 // packing/alignment of members is different that normal, in which case
5944 // the encoding will be out-of-sync with the real layout.
5945 // If the runtime switches to just consider the size of types without
5946 // taking into account alignment, we could make padding explicit in the
5947 // encoding (e.g. using arrays of chars). The encoding strings would be
5948 // longer then though.
5949 CurOffs += padding;
5950 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005951#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005952
5953 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00005954 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005955 break; // reached end of structure.
5956
5957 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5958 // We expand the bases without their virtual bases since those are going
5959 // in the initial structure. Note that this differs from gcc which
5960 // expands virtual bases each time one is encountered in the hierarchy,
5961 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005962 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
5963 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005964 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005965#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005966 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005967#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005968 } else {
5969 FieldDecl *field = cast<FieldDecl>(dcl);
5970 if (FD) {
5971 S += '"';
5972 S += field->getNameAsString();
5973 S += '"';
5974 }
5975
5976 if (field->isBitField()) {
5977 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005978#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00005979 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005980#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005981 } else {
5982 QualType qt = field->getType();
5983 getLegacyIntegralTypeEncoding(qt);
5984 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5985 /*OutermostType*/false,
5986 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005987 /*StructField*/true,
5988 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005989#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005990 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005991#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005992 }
5993 }
5994 }
5995}
5996
Mike Stump11289f42009-09-09 15:08:12 +00005997void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005998 std::string& S) const {
5999 if (QT & Decl::OBJC_TQ_In)
6000 S += 'n';
6001 if (QT & Decl::OBJC_TQ_Inout)
6002 S += 'N';
6003 if (QT & Decl::OBJC_TQ_Out)
6004 S += 'o';
6005 if (QT & Decl::OBJC_TQ_Bycopy)
6006 S += 'O';
6007 if (QT & Decl::OBJC_TQ_Byref)
6008 S += 'R';
6009 if (QT & Decl::OBJC_TQ_Oneway)
6010 S += 'V';
6011}
6012
Douglas Gregor3ea72692011-08-12 05:46:01 +00006013TypedefDecl *ASTContext::getObjCIdDecl() const {
6014 if (!ObjCIdDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006015 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
Douglas Gregor3ea72692011-08-12 05:46:01 +00006016 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006017 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00006018 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00006019 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00006020}
6021
Douglas Gregor52e02802011-08-12 06:17:30 +00006022TypedefDecl *ASTContext::getObjCSelDecl() const {
6023 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006024 QualType T = getPointerType(ObjCBuiltinSelTy);
6025 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00006026 }
6027 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00006028}
6029
Douglas Gregor0a586182011-08-12 05:59:41 +00006030TypedefDecl *ASTContext::getObjCClassDecl() const {
6031 if (!ObjCClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006032 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
Douglas Gregor0a586182011-08-12 05:59:41 +00006033 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006034 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00006035 }
Douglas Gregor0a586182011-08-12 05:59:41 +00006036 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00006037}
6038
Douglas Gregord53ae832012-01-17 18:09:05 +00006039ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6040 if (!ObjCProtocolClassDecl) {
6041 ObjCProtocolClassDecl
6042 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6043 SourceLocation(),
6044 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00006045 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00006046 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00006047 SourceLocation(), true);
6048 }
6049
6050 return ObjCProtocolClassDecl;
6051}
6052
Meador Inge5d3fb222012-06-16 03:34:49 +00006053//===----------------------------------------------------------------------===//
6054// __builtin_va_list Construction Functions
6055//===----------------------------------------------------------------------===//
6056
Charles Davisc7d5c942015-09-17 20:55:33 +00006057static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6058 StringRef Name) {
6059 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006060 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00006061 return Context->buildImplicitTypedef(T, Name);
6062}
6063
6064static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6065 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6066}
6067
6068static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6069 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006070}
6071
6072static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6073 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006074 QualType T = Context->getPointerType(Context->VoidTy);
6075 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006076}
6077
Tim Northover9bb857a2013-01-31 12:13:10 +00006078static TypedefDecl *
6079CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006080 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006081 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006082 if (Context->getLangOpts().CPlusPlus) {
6083 // namespace std { struct __va_list {
6084 NamespaceDecl *NS;
6085 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6086 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00006087 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00006088 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006089 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006090 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00006091 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00006092 }
6093
6094 VaListTagDecl->startDefinition();
6095
6096 const size_t NumFields = 5;
6097 QualType FieldTypes[NumFields];
6098 const char *FieldNames[NumFields];
6099
6100 // void *__stack;
6101 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6102 FieldNames[0] = "__stack";
6103
6104 // void *__gr_top;
6105 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6106 FieldNames[1] = "__gr_top";
6107
6108 // void *__vr_top;
6109 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6110 FieldNames[2] = "__vr_top";
6111
6112 // int __gr_offs;
6113 FieldTypes[3] = Context->IntTy;
6114 FieldNames[3] = "__gr_offs";
6115
6116 // int __vr_offs;
6117 FieldTypes[4] = Context->IntTy;
6118 FieldNames[4] = "__vr_offs";
6119
6120 // Create fields
6121 for (unsigned i = 0; i < NumFields; ++i) {
6122 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6123 VaListTagDecl,
6124 SourceLocation(),
6125 SourceLocation(),
6126 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006127 FieldTypes[i], /*TInfo=*/nullptr,
6128 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00006129 /*Mutable=*/false,
6130 ICIS_NoInit);
6131 Field->setAccess(AS_public);
6132 VaListTagDecl->addDecl(Field);
6133 }
6134 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006135 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00006136 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00006137
6138 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006139 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006140}
6141
Meador Inge5d3fb222012-06-16 03:34:49 +00006142static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6143 // typedef struct __va_list_tag {
6144 RecordDecl *VaListTagDecl;
6145
Alp Toker2dea15b2013-12-17 01:22:38 +00006146 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006147 VaListTagDecl->startDefinition();
6148
6149 const size_t NumFields = 5;
6150 QualType FieldTypes[NumFields];
6151 const char *FieldNames[NumFields];
6152
6153 // unsigned char gpr;
6154 FieldTypes[0] = Context->UnsignedCharTy;
6155 FieldNames[0] = "gpr";
6156
6157 // unsigned char fpr;
6158 FieldTypes[1] = Context->UnsignedCharTy;
6159 FieldNames[1] = "fpr";
6160
6161 // unsigned short reserved;
6162 FieldTypes[2] = Context->UnsignedShortTy;
6163 FieldNames[2] = "reserved";
6164
6165 // void* overflow_arg_area;
6166 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6167 FieldNames[3] = "overflow_arg_area";
6168
6169 // void* reg_save_area;
6170 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6171 FieldNames[4] = "reg_save_area";
6172
6173 // Create fields
6174 for (unsigned i = 0; i < NumFields; ++i) {
6175 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6176 SourceLocation(),
6177 SourceLocation(),
6178 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006179 FieldTypes[i], /*TInfo=*/nullptr,
6180 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006181 /*Mutable=*/false,
6182 ICIS_NoInit);
6183 Field->setAccess(AS_public);
6184 VaListTagDecl->addDecl(Field);
6185 }
6186 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006187 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006188 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6189
6190 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006191 TypedefDecl *VaListTagTypedefDecl =
6192 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6193
Meador Inge5d3fb222012-06-16 03:34:49 +00006194 QualType VaListTagTypedefType =
6195 Context->getTypedefType(VaListTagTypedefDecl);
6196
6197 // typedef __va_list_tag __builtin_va_list[1];
6198 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6199 QualType VaListTagArrayType
6200 = Context->getConstantArrayType(VaListTagTypedefType,
6201 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006202 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006203}
6204
6205static TypedefDecl *
6206CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006207 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00006208 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006209 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006210 VaListTagDecl->startDefinition();
6211
6212 const size_t NumFields = 4;
6213 QualType FieldTypes[NumFields];
6214 const char *FieldNames[NumFields];
6215
6216 // unsigned gp_offset;
6217 FieldTypes[0] = Context->UnsignedIntTy;
6218 FieldNames[0] = "gp_offset";
6219
6220 // unsigned fp_offset;
6221 FieldTypes[1] = Context->UnsignedIntTy;
6222 FieldNames[1] = "fp_offset";
6223
6224 // void* overflow_arg_area;
6225 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6226 FieldNames[2] = "overflow_arg_area";
6227
6228 // void* reg_save_area;
6229 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6230 FieldNames[3] = "reg_save_area";
6231
6232 // Create fields
6233 for (unsigned i = 0; i < NumFields; ++i) {
6234 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6235 VaListTagDecl,
6236 SourceLocation(),
6237 SourceLocation(),
6238 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006239 FieldTypes[i], /*TInfo=*/nullptr,
6240 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006241 /*Mutable=*/false,
6242 ICIS_NoInit);
6243 Field->setAccess(AS_public);
6244 VaListTagDecl->addDecl(Field);
6245 }
6246 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006247 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006248 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6249
Richard Smith9b88a4c2015-07-27 05:40:23 +00006250 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00006251
Richard Smith9b88a4c2015-07-27 05:40:23 +00006252 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00006253 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006254 QualType VaListTagArrayType =
6255 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006256 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006257}
6258
6259static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6260 // typedef int __builtin_va_list[4];
6261 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6262 QualType IntArrayType
6263 = Context->getConstantArrayType(Context->IntTy,
6264 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006265 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006266}
6267
Logan Chien57086ce2012-10-10 06:56:20 +00006268static TypedefDecl *
6269CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006270 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006271 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006272 if (Context->getLangOpts().CPlusPlus) {
6273 // namespace std { struct __va_list {
6274 NamespaceDecl *NS;
6275 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6276 Context->getTranslationUnitDecl(),
6277 /*Inline*/false, SourceLocation(),
6278 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006279 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006280 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006281 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006282 }
6283
6284 VaListDecl->startDefinition();
6285
6286 // void * __ap;
6287 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6288 VaListDecl,
6289 SourceLocation(),
6290 SourceLocation(),
6291 &Context->Idents.get("__ap"),
6292 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006293 /*TInfo=*/nullptr,
6294 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006295 /*Mutable=*/false,
6296 ICIS_NoInit);
6297 Field->setAccess(AS_public);
6298 VaListDecl->addDecl(Field);
6299
6300 // };
6301 VaListDecl->completeDefinition();
6302
6303 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006304 QualType T = Context->getRecordType(VaListDecl);
6305 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006306}
6307
Ulrich Weigand47445072013-05-06 16:26:41 +00006308static TypedefDecl *
6309CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006310 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00006311 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006312 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006313 VaListTagDecl->startDefinition();
6314
6315 const size_t NumFields = 4;
6316 QualType FieldTypes[NumFields];
6317 const char *FieldNames[NumFields];
6318
6319 // long __gpr;
6320 FieldTypes[0] = Context->LongTy;
6321 FieldNames[0] = "__gpr";
6322
6323 // long __fpr;
6324 FieldTypes[1] = Context->LongTy;
6325 FieldNames[1] = "__fpr";
6326
6327 // void *__overflow_arg_area;
6328 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6329 FieldNames[2] = "__overflow_arg_area";
6330
6331 // void *__reg_save_area;
6332 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6333 FieldNames[3] = "__reg_save_area";
6334
6335 // Create fields
6336 for (unsigned i = 0; i < NumFields; ++i) {
6337 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6338 VaListTagDecl,
6339 SourceLocation(),
6340 SourceLocation(),
6341 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006342 FieldTypes[i], /*TInfo=*/nullptr,
6343 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006344 /*Mutable=*/false,
6345 ICIS_NoInit);
6346 Field->setAccess(AS_public);
6347 VaListTagDecl->addDecl(Field);
6348 }
6349 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006350 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00006351 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00006352
Richard Smith9b88a4c2015-07-27 05:40:23 +00006353 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00006354
6355 // typedef __va_list_tag __builtin_va_list[1];
6356 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006357 QualType VaListTagArrayType =
6358 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006359
Alp Toker56b5cc92013-12-15 10:36:26 +00006360 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006361}
6362
Meador Inge5d3fb222012-06-16 03:34:49 +00006363static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6364 TargetInfo::BuiltinVaListKind Kind) {
6365 switch (Kind) {
6366 case TargetInfo::CharPtrBuiltinVaList:
6367 return CreateCharPtrBuiltinVaListDecl(Context);
6368 case TargetInfo::VoidPtrBuiltinVaList:
6369 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006370 case TargetInfo::AArch64ABIBuiltinVaList:
6371 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006372 case TargetInfo::PowerABIBuiltinVaList:
6373 return CreatePowerABIBuiltinVaListDecl(Context);
6374 case TargetInfo::X86_64ABIBuiltinVaList:
6375 return CreateX86_64ABIBuiltinVaListDecl(Context);
6376 case TargetInfo::PNaClABIBuiltinVaList:
6377 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006378 case TargetInfo::AAPCSABIBuiltinVaList:
6379 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006380 case TargetInfo::SystemZBuiltinVaList:
6381 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006382 }
6383
6384 llvm_unreachable("Unhandled __builtin_va_list type kind");
6385}
6386
6387TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006388 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006389 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006390 assert(BuiltinVaListDecl->isImplicit());
6391 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006392
6393 return BuiltinVaListDecl;
6394}
6395
Richard Smith9b88a4c2015-07-27 05:40:23 +00006396Decl *ASTContext::getVaListTagDecl() const {
6397 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00006398 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00006399 if (!VaListTagDecl)
6400 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00006401
Richard Smith9b88a4c2015-07-27 05:40:23 +00006402 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00006403}
6404
Charles Davisc7d5c942015-09-17 20:55:33 +00006405TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6406 if (!BuiltinMSVaListDecl)
6407 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6408
6409 return BuiltinMSVaListDecl;
6410}
6411
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006412void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006413 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006414 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006415
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006416 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006417}
6418
John McCalld28ae272009-12-02 08:04:21 +00006419/// \brief Retrieve the template name that corresponds to a non-empty
6420/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006421TemplateName
6422ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6423 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006424 unsigned size = End - Begin;
6425 assert(size > 1 && "set is not overloaded!");
6426
6427 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6428 size * sizeof(FunctionTemplateDecl*));
6429 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6430
6431 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006432 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006433 NamedDecl *D = *I;
6434 assert(isa<FunctionTemplateDecl>(D) ||
6435 (isa<UsingShadowDecl>(D) &&
6436 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6437 *Storage++ = D;
6438 }
6439
6440 return TemplateName(OT);
6441}
6442
Douglas Gregordc572a32009-03-30 22:58:21 +00006443/// \brief Retrieve the template name that represents a qualified
6444/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006445TemplateName
6446ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6447 bool TemplateKeyword,
6448 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006449 assert(NNS && "Missing nested-name-specifier in qualified template name");
6450
Douglas Gregorc42075a2010-02-04 18:10:26 +00006451 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006452 llvm::FoldingSetNodeID ID;
6453 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6454
Craig Topper36250ad2014-05-12 05:36:57 +00006455 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006456 QualifiedTemplateName *QTN =
6457 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6458 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006459 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6460 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006461 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6462 }
6463
6464 return TemplateName(QTN);
6465}
6466
6467/// \brief Retrieve the template name that represents a dependent
6468/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006469TemplateName
6470ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6471 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006472 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006473 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006474
6475 llvm::FoldingSetNodeID ID;
6476 DependentTemplateName::Profile(ID, NNS, Name);
6477
Craig Topper36250ad2014-05-12 05:36:57 +00006478 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006479 DependentTemplateName *QTN =
6480 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6481
6482 if (QTN)
6483 return TemplateName(QTN);
6484
6485 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6486 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006487 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6488 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006489 } else {
6490 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006491 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6492 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006493 DependentTemplateName *CheckQTN =
6494 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6495 assert(!CheckQTN && "Dependent type name canonicalization broken");
6496 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006497 }
6498
6499 DependentTemplateNames.InsertNode(QTN, InsertPos);
6500 return TemplateName(QTN);
6501}
6502
Douglas Gregor71395fa2009-11-04 00:56:37 +00006503/// \brief Retrieve the template name that represents a dependent
6504/// template name such as \c MetaFun::template operator+.
6505TemplateName
6506ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006507 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006508 assert((!NNS || NNS->isDependent()) &&
6509 "Nested name specifier must be dependent");
6510
6511 llvm::FoldingSetNodeID ID;
6512 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00006513
6514 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006515 DependentTemplateName *QTN
6516 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006517
6518 if (QTN)
6519 return TemplateName(QTN);
6520
6521 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6522 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006523 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6524 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006525 } else {
6526 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006527 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6528 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006529
6530 DependentTemplateName *CheckQTN
6531 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6532 assert(!CheckQTN && "Dependent template name canonicalization broken");
6533 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006534 }
6535
6536 DependentTemplateNames.InsertNode(QTN, InsertPos);
6537 return TemplateName(QTN);
6538}
6539
Douglas Gregor5590be02011-01-15 06:45:20 +00006540TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006541ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6542 TemplateName replacement) const {
6543 llvm::FoldingSetNodeID ID;
6544 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00006545
6546 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00006547 SubstTemplateTemplateParmStorage *subst
6548 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6549
6550 if (!subst) {
6551 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6552 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6553 }
6554
6555 return TemplateName(subst);
6556}
6557
6558TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006559ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6560 const TemplateArgument &ArgPack) const {
6561 ASTContext &Self = const_cast<ASTContext &>(*this);
6562 llvm::FoldingSetNodeID ID;
6563 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00006564
6565 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00006566 SubstTemplateTemplateParmPackStorage *Subst
6567 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6568
6569 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006570 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006571 ArgPack.pack_size(),
6572 ArgPack.pack_begin());
6573 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6574 }
6575
6576 return TemplateName(Subst);
6577}
6578
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006579/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006580/// TargetInfo, produce the corresponding type. The unsigned @p Type
6581/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006582CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006583 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006584 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006585 case TargetInfo::SignedChar: return SignedCharTy;
6586 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006587 case TargetInfo::SignedShort: return ShortTy;
6588 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6589 case TargetInfo::SignedInt: return IntTy;
6590 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6591 case TargetInfo::SignedLong: return LongTy;
6592 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6593 case TargetInfo::SignedLongLong: return LongLongTy;
6594 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6595 }
6596
David Blaikie83d382b2011-09-23 05:06:16 +00006597 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006598}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006599
6600//===----------------------------------------------------------------------===//
6601// Type Predicates.
6602//===----------------------------------------------------------------------===//
6603
Fariborz Jahanian96207692009-02-18 21:49:28 +00006604/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6605/// garbage collection attribute.
6606///
John McCall553d45a2011-01-12 00:34:59 +00006607Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006608 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006609 return Qualifiers::GCNone;
6610
David Blaikiebbafb8a2012-03-11 07:00:24 +00006611 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006612 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6613
6614 // Default behaviour under objective-C's gc is for ObjC pointers
6615 // (or pointers to them) be treated as though they were declared
6616 // as __strong.
6617 if (GCAttrs == Qualifiers::GCNone) {
6618 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6619 return Qualifiers::Strong;
6620 else if (Ty->isPointerType())
6621 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6622 } else {
6623 // It's not valid to set GC attributes on anything that isn't a
6624 // pointer.
6625#ifndef NDEBUG
6626 QualType CT = Ty->getCanonicalTypeInternal();
6627 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6628 CT = AT->getElementType();
6629 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6630#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006631 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006632 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006633}
6634
Chris Lattner49af6a42008-04-07 06:51:04 +00006635//===----------------------------------------------------------------------===//
6636// Type Compatibility Testing
6637//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006638
Mike Stump11289f42009-09-09 15:08:12 +00006639/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006640/// compatible.
6641static bool areCompatVectorTypes(const VectorType *LHS,
6642 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006643 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006644 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006645 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006646}
6647
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006648bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6649 QualType SecondVec) {
6650 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6651 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6652
6653 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6654 return true;
6655
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006656 // Treat Neon vector types and most AltiVec vector types as if they are the
6657 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006658 const VectorType *First = FirstVec->getAs<VectorType>();
6659 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006660 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006661 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006662 First->getVectorKind() != VectorType::AltiVecPixel &&
6663 First->getVectorKind() != VectorType::AltiVecBool &&
6664 Second->getVectorKind() != VectorType::AltiVecPixel &&
6665 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006666 return true;
6667
6668 return false;
6669}
6670
Steve Naroff8e6aee52009-07-23 01:01:38 +00006671//===----------------------------------------------------------------------===//
6672// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6673//===----------------------------------------------------------------------===//
6674
6675/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6676/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006677bool
6678ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6679 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006680 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006681 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006682 for (auto *PI : rProto->protocols())
6683 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006684 return true;
6685 return false;
6686}
6687
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006688/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6689/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006690bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6691 QualType rhs) {
6692 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6693 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6694 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6695
Aaron Ballman83731462014-03-17 16:14:00 +00006696 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006697 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006698 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006699 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6700 match = true;
6701 break;
6702 }
6703 }
6704 if (!match)
6705 return false;
6706 }
6707 return true;
6708}
6709
Steve Naroff8e6aee52009-07-23 01:01:38 +00006710/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6711/// ObjCQualifiedIDType.
6712bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6713 bool compare) {
6714 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006715 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006716 lhs->isObjCIdType() || lhs->isObjCClassType())
6717 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006718 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006719 rhs->isObjCIdType() || rhs->isObjCClassType())
6720 return true;
6721
6722 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006723 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006724
Steve Naroff8e6aee52009-07-23 01:01:38 +00006725 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006726
Steve Naroff8e6aee52009-07-23 01:01:38 +00006727 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006728 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006729 // make sure we check the class hierarchy.
6730 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006731 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006732 // when comparing an id<P> on lhs with a static type on rhs,
6733 // see if static class implements all of id's protocols, directly or
6734 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006735 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006736 return false;
6737 }
6738 }
6739 // If there are no qualifiers and no interface, we have an 'id'.
6740 return true;
6741 }
Mike Stump11289f42009-09-09 15:08:12 +00006742 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006743 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006744 bool match = false;
6745
6746 // when comparing an id<P> on lhs with a static type on rhs,
6747 // see if static class implements all of id's protocols, directly or
6748 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006749 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006750 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6751 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6752 match = true;
6753 break;
6754 }
6755 }
Mike Stump11289f42009-09-09 15:08:12 +00006756 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006757 // make sure we check the class hierarchy.
6758 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006759 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006760 // when comparing an id<P> on lhs with a static type on rhs,
6761 // see if static class implements all of id's protocols, directly or
6762 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006763 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006764 match = true;
6765 break;
6766 }
6767 }
6768 }
6769 if (!match)
6770 return false;
6771 }
Mike Stump11289f42009-09-09 15:08:12 +00006772
Steve Naroff8e6aee52009-07-23 01:01:38 +00006773 return true;
6774 }
Mike Stump11289f42009-09-09 15:08:12 +00006775
Steve Naroff8e6aee52009-07-23 01:01:38 +00006776 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6777 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6778
Mike Stump11289f42009-09-09 15:08:12 +00006779 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006780 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006781 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006782 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006783 bool match = false;
6784
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006785 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006786 // see if static class implements all of id's protocols, directly or
6787 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006788 // First, lhs protocols in the qualifier list must be found, direct
6789 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00006790 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006791 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6792 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6793 match = true;
6794 break;
6795 }
6796 }
6797 if (!match)
6798 return false;
6799 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006800
6801 // Static class's protocols, or its super class or category protocols
6802 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6803 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6804 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6805 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6806 // This is rather dubious but matches gcc's behavior. If lhs has
6807 // no type qualifier and its class has no static protocol(s)
6808 // assume that it is mismatch.
6809 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6810 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00006811 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006812 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006813 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006814 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6815 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6816 match = true;
6817 break;
6818 }
6819 }
6820 if (!match)
6821 return false;
6822 }
6823 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006824 return true;
6825 }
6826 return false;
6827}
6828
Eli Friedman47f77112008-08-22 00:56:42 +00006829/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006830/// compatible for assignment from RHS to LHS. This handles validation of any
6831/// protocol qualifiers on the LHS or RHS.
6832///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006833bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6834 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006835 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6836 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6837
Steve Naroff1329fa02009-07-15 18:40:39 +00006838 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006839 if (LHS->isObjCUnqualifiedIdOrClass() ||
6840 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006841 return true;
6842
Douglas Gregorab209d82015-07-07 03:58:42 +00006843 // Function object that propagates a successful result or handles
6844 // __kindof types.
6845 auto finish = [&](bool succeeded) -> bool {
6846 if (succeeded)
6847 return true;
6848
6849 if (!RHS->isKindOfType())
6850 return false;
6851
6852 // Strip off __kindof and protocol qualifiers, then check whether
6853 // we can assign the other way.
6854 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6855 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
6856 };
6857
6858 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
6859 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6860 QualType(RHSOPT,0),
6861 false));
6862 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006863
Douglas Gregorab209d82015-07-07 03:58:42 +00006864 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
6865 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6866 QualType(RHSOPT,0)));
6867 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006868
John McCall8b07ec22010-05-15 11:32:37 +00006869 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00006870 if (LHS->getInterface() && RHS->getInterface()) {
6871 return finish(canAssignObjCInterfaces(LHS, RHS));
6872 }
Mike Stump11289f42009-09-09 15:08:12 +00006873
Steve Naroff8e6aee52009-07-23 01:01:38 +00006874 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006875}
6876
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006877/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006878/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006879/// arguments in block literals. When passed as arguments, passing 'A*' where
6880/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6881/// not OK. For the return type, the opposite is not OK.
6882bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6883 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006884 const ObjCObjectPointerType *RHSOPT,
6885 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00006886
6887 // Function object that propagates a successful result or handles
6888 // __kindof types.
6889 auto finish = [&](bool succeeded) -> bool {
6890 if (succeeded)
6891 return true;
6892
6893 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
6894 if (!Expected->isKindOfType())
6895 return false;
6896
6897 // Strip off __kindof and protocol qualifiers, then check whether
6898 // we can assign the other way.
6899 return canAssignObjCInterfacesInBlockPointer(
6900 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6901 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
6902 BlockReturnType);
6903 };
6904
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006905 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006906 return true;
6907
6908 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00006909 return finish(RHSOPT->isObjCBuiltinType() ||
6910 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006911 }
6912
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006913 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00006914 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6915 QualType(RHSOPT,0),
6916 false));
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006917
6918 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6919 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6920 if (LHS && RHS) { // We have 2 user-defined types.
6921 if (LHS != RHS) {
6922 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00006923 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006924 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00006925 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006926 }
6927 else
6928 return true;
6929 }
6930 return false;
6931}
6932
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006933/// Comparison routine for Objective-C protocols to be used with
6934/// llvm::array_pod_sort.
6935static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
6936 ObjCProtocolDecl * const *rhs) {
6937 return (*lhs)->getName().compare((*rhs)->getName());
6938
6939}
6940
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006941/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006942/// of protocols inherited from two distinct objective-c pointer objects with
6943/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006944/// It is used to build composite qualifier list of the composite type of
6945/// the conditional expression involving two objective-c pointer objects.
6946static
6947void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006948 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006949 const ObjCObjectPointerType *LHSOPT,
6950 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006951 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006952
John McCall8b07ec22010-05-15 11:32:37 +00006953 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6954 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6955 assert(LHS->getInterface() && "LHS must have an interface base");
6956 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006957
6958 // Add all of the protocols for the LHS.
6959 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
6960
6961 // Start with the protocol qualifiers.
6962 for (auto proto : LHS->quals()) {
6963 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006964 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006965
6966 // Also add the protocols associated with the LHS interface.
6967 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
6968
6969 // Add all of the protocls for the RHS.
6970 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
6971
6972 // Start with the protocol qualifiers.
6973 for (auto proto : RHS->quals()) {
6974 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006975 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006976
6977 // Also add the protocols associated with the RHS interface.
6978 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
6979
6980 // Compute the intersection of the collected protocol sets.
6981 for (auto proto : LHSProtocolSet) {
6982 if (RHSProtocolSet.count(proto))
6983 IntersectionSet.push_back(proto);
6984 }
6985
6986 // Compute the set of protocols that is implied by either the common type or
6987 // the protocols within the intersection.
6988 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
6989 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
6990
6991 // Remove any implied protocols from the list of inherited protocols.
6992 if (!ImpliedProtocols.empty()) {
6993 IntersectionSet.erase(
6994 std::remove_if(IntersectionSet.begin(),
6995 IntersectionSet.end(),
6996 [&](ObjCProtocolDecl *proto) -> bool {
6997 return ImpliedProtocols.count(proto) > 0;
6998 }),
6999 IntersectionSet.end());
7000 }
7001
7002 // Sort the remaining protocols by name.
7003 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7004 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007005}
7006
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007007/// Determine whether the first type is a subtype of the second.
7008static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7009 QualType rhs) {
7010 // Common case: two object pointers.
7011 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7012 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7013 if (lhsOPT && rhsOPT)
7014 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7015
7016 // Two block pointers.
7017 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7018 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7019 if (lhsBlock && rhsBlock)
7020 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7021
7022 // If either is an unqualified 'id' and the other is a block, it's
7023 // acceptable.
7024 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7025 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7026 return true;
7027
7028 return false;
7029}
7030
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007031// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007032static bool sameObjCTypeArgs(ASTContext &ctx,
7033 const ObjCInterfaceDecl *iface,
7034 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00007035 ArrayRef<QualType> rhsArgs,
7036 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007037 if (lhsArgs.size() != rhsArgs.size())
7038 return false;
7039
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007040 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007041 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007042 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7043 continue;
7044
7045 switch (typeParams->begin()[i]->getVariance()) {
7046 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00007047 if (!stripKindOf ||
7048 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7049 rhsArgs[i].stripObjCKindOfType(ctx))) {
7050 return false;
7051 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007052 break;
7053
7054 case ObjCTypeParamVariance::Covariant:
7055 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7056 return false;
7057 break;
7058
7059 case ObjCTypeParamVariance::Contravariant:
7060 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7061 return false;
7062 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00007063 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007064 }
7065
7066 return true;
7067}
7068
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007069QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007070 const ObjCObjectPointerType *Lptr,
7071 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00007072 const ObjCObjectType *LHS = Lptr->getObjectType();
7073 const ObjCObjectType *RHS = Rptr->getObjectType();
7074 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7075 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007076
7077 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007078 return QualType();
Douglas Gregore83b9562015-07-07 03:57:53 +00007079
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007080 // Follow the left-hand side up the class hierarchy until we either hit a
7081 // root or find the RHS. Record the ancestors in case we don't find it.
7082 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7083 LHSAncestors;
7084 while (true) {
7085 // Record this ancestor. We'll need this if the common type isn't in the
7086 // path from the LHS to the root.
7087 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00007088
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007089 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7090 // Get the type arguments.
7091 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7092 bool anyChanges = false;
7093 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7094 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007095 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7096 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007097 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007098 return QualType();
7099 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7100 // If only one has type arguments, the result will not have type
7101 // arguments.
7102 LHSTypeArgs = { };
7103 anyChanges = true;
7104 }
7105
7106 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007107 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007108 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7109 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00007110 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007111 anyChanges = true;
7112
7113 // If anything in the LHS will have changed, build a new result type.
7114 if (anyChanges) {
7115 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007116 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
7117 LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007118 return getObjCObjectPointerType(Result);
7119 }
7120
7121 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007122 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007123
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007124 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00007125 QualType LHSSuperType = LHS->getSuperClassType();
7126 if (LHSSuperType.isNull())
7127 break;
7128
7129 LHS = LHSSuperType->castAs<ObjCObjectType>();
7130 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007131
7132 // We didn't find anything by following the LHS to its root; now check
7133 // the RHS against the cached set of ancestors.
7134 while (true) {
7135 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7136 if (KnownLHS != LHSAncestors.end()) {
7137 LHS = KnownLHS->second;
7138
7139 // Get the type arguments.
7140 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7141 bool anyChanges = false;
7142 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7143 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007144 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7145 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007146 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007147 return QualType();
7148 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7149 // If only one has type arguments, the result will not have type
7150 // arguments.
7151 RHSTypeArgs = { };
7152 anyChanges = true;
7153 }
7154
7155 // Compute the intersection of protocols.
7156 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7157 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7158 Protocols);
7159 if (!Protocols.empty())
7160 anyChanges = true;
7161
7162 if (anyChanges) {
7163 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007164 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
7165 RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007166 return getObjCObjectPointerType(Result);
7167 }
7168
7169 return getObjCObjectPointerType(QualType(RHS, 0));
7170 }
7171
7172 // Find the superclass of the RHS.
7173 QualType RHSSuperType = RHS->getSuperClassType();
7174 if (RHSSuperType.isNull())
7175 break;
7176
7177 RHS = RHSSuperType->castAs<ObjCObjectType>();
7178 }
7179
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007180 return QualType();
7181}
7182
John McCall8b07ec22010-05-15 11:32:37 +00007183bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7184 const ObjCObjectType *RHS) {
7185 assert(LHS->getInterface() && "LHS is not an interface type");
7186 assert(RHS->getInterface() && "RHS is not an interface type");
7187
Chris Lattner49af6a42008-04-07 06:51:04 +00007188 // Verify that the base decls are compatible: the RHS must be a subclass of
7189 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00007190 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7191 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7192 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00007193 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007194
Douglas Gregore83b9562015-07-07 03:57:53 +00007195 // If the LHS has protocol qualifiers, determine whether all of them are
7196 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7197 // LHS).
7198 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007199 // OK if conversion of LHS to SuperClass results in narrowing of types
7200 // ; i.e., SuperClass may implement at least one of the protocols
7201 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7202 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7203 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7204 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7205 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7206 // qualifiers.
7207 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007208 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007209 // If there is no protocols associated with RHS, it is not a match.
7210 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00007211 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007212
7213 for (const auto *LHSProto : LHS->quals()) {
7214 bool SuperImplementsProtocol = false;
7215 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7216 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7217 SuperImplementsProtocol = true;
7218 break;
7219 }
7220 if (!SuperImplementsProtocol)
7221 return false;
7222 }
Chris Lattner49af6a42008-04-07 06:51:04 +00007223 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007224
7225 // If the LHS is specialized, we may need to check type arguments.
7226 if (LHS->isSpecialized()) {
7227 // Follow the superclass chain until we've matched the LHS class in the
7228 // hierarchy. This substitutes type arguments through.
7229 const ObjCObjectType *RHSSuper = RHS;
7230 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7231 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7232
7233 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007234 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007235 !sameObjCTypeArgs(*this, LHS->getInterface(),
7236 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007237 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007238 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00007239 }
7240 }
7241
7242 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00007243}
7244
Steve Naroffb7605152009-02-12 17:52:19 +00007245bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7246 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00007247 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7248 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007249
Steve Naroff7cae42b2009-07-10 23:34:53 +00007250 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00007251 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007252
7253 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7254 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00007255}
7256
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007257bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7258 return canAssignObjCInterfaces(
7259 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7260 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7261}
7262
Mike Stump11289f42009-09-09 15:08:12 +00007263/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00007264/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00007265/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00007266/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007267bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7268 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007269 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00007270 return hasSameType(LHS, RHS);
7271
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007272 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00007273}
7274
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007275bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00007276 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007277}
7278
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007279bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7280 return !mergeTypes(LHS, RHS, true).isNull();
7281}
7282
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007283/// mergeTransparentUnionType - if T is a transparent union type and a member
7284/// of T is compatible with SubType, return the merged type, else return
7285/// QualType()
7286QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7287 bool OfBlockPointer,
7288 bool Unqualified) {
7289 if (const RecordType *UT = T->getAsUnionType()) {
7290 RecordDecl *UD = UT->getDecl();
7291 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007292 for (const auto *I : UD->fields()) {
7293 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007294 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7295 if (!MT.isNull())
7296 return MT;
7297 }
7298 }
7299 }
7300
7301 return QualType();
7302}
7303
Alp Toker9cacbab2014-01-20 20:26:09 +00007304/// mergeFunctionParameterTypes - merge two types which appear as function
7305/// parameter types
7306QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7307 bool OfBlockPointer,
7308 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007309 // GNU extension: two types are compatible if they appear as a function
7310 // argument, one of the types is a transparent union type and the other
7311 // type is compatible with a union member
7312 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7313 Unqualified);
7314 if (!lmerge.isNull())
7315 return lmerge;
7316
7317 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7318 Unqualified);
7319 if (!rmerge.isNull())
7320 return rmerge;
7321
7322 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7323}
7324
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007325QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007326 bool OfBlockPointer,
7327 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00007328 const FunctionType *lbase = lhs->getAs<FunctionType>();
7329 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007330 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7331 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00007332 bool allLTypes = true;
7333 bool allRTypes = true;
7334
7335 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007336 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00007337 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00007338 QualType RHS = rbase->getReturnType();
7339 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00007340 bool UnqualifiedResult = Unqualified;
7341 if (!UnqualifiedResult)
7342 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007343 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00007344 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007345 else
Alp Toker314cc812014-01-25 16:55:45 +00007346 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00007347 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007348 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007349
7350 if (Unqualified)
7351 retType = retType.getUnqualifiedType();
7352
Alp Toker314cc812014-01-25 16:55:45 +00007353 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7354 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007355 if (Unqualified) {
7356 LRetType = LRetType.getUnqualifiedType();
7357 RRetType = RRetType.getUnqualifiedType();
7358 }
7359
7360 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007361 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007362 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007363 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00007364
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00007365 // FIXME: double check this
7366 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7367 // rbase->getRegParmAttr() != 0 &&
7368 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00007369 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7370 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00007371
Douglas Gregor8c940862010-01-18 17:14:39 +00007372 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00007373 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00007374 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00007375
John McCall8c6b56f2010-12-15 01:06:38 +00007376 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00007377 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7378 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00007379 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7380 return QualType();
7381
John McCall31168b02011-06-15 23:02:42 +00007382 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7383 return QualType();
7384
John McCall8c6b56f2010-12-15 01:06:38 +00007385 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7386 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007387
Rafael Espindola8778c282012-11-29 16:09:03 +00007388 if (lbaseInfo.getNoReturn() != NoReturn)
7389 allLTypes = false;
7390 if (rbaseInfo.getNoReturn() != NoReturn)
7391 allRTypes = false;
7392
John McCall31168b02011-06-15 23:02:42 +00007393 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007394
Eli Friedman47f77112008-08-22 00:56:42 +00007395 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007396 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7397 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00007398 // Compatible functions must have the same number of parameters
7399 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00007400 return QualType();
7401
7402 // Variadic and non-variadic functions aren't compatible
7403 if (lproto->isVariadic() != rproto->isVariadic())
7404 return QualType();
7405
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007406 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7407 return QualType();
7408
Fariborz Jahanian97676972011-09-28 21:52:05 +00007409 if (LangOpts.ObjCAutoRefCount &&
7410 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
7411 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00007412
7413 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007414 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007415 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7416 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7417 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7418 QualType paramType = mergeFunctionParameterTypes(
7419 lParamType, rParamType, OfBlockPointer, Unqualified);
7420 if (paramType.isNull())
7421 return QualType();
7422
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007423 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007424 paramType = paramType.getUnqualifiedType();
7425
7426 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007427 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007428 lParamType = lParamType.getUnqualifiedType();
7429 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007430 }
Alp Toker601b22c2014-01-21 23:35:24 +00007431
7432 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007433 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007434 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007435 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007436 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007437
Eli Friedman47f77112008-08-22 00:56:42 +00007438 if (allLTypes) return lhs;
7439 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007440
7441 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7442 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007443 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007444 }
7445
7446 if (lproto) allRTypes = false;
7447 if (rproto) allLTypes = false;
7448
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007449 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007450 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007451 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007452 if (proto->isVariadic()) return QualType();
7453 // Check that the types are compatible with the types that
7454 // would result from default argument promotions (C99 6.7.5.3p15).
7455 // The only types actually affected are promotable integer
7456 // types and floats, which would be passed as a different
7457 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007458 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7459 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007460
Eli Friedman448ce402012-08-30 00:44:15 +00007461 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007462 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007463 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7464 paramTy = Enum->getDecl()->getIntegerType();
7465 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007466 return QualType();
7467 }
Alp Toker601b22c2014-01-21 23:35:24 +00007468
7469 if (paramTy->isPromotableIntegerType() ||
7470 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007471 return QualType();
7472 }
7473
7474 if (allLTypes) return lhs;
7475 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007476
7477 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7478 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007479 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007480 }
7481
7482 if (allLTypes) return lhs;
7483 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007484 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007485}
7486
John McCall433c2e62013-03-21 00:10:07 +00007487/// Given that we have an enum type and a non-enum type, try to merge them.
7488static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7489 QualType other, bool isBlockReturnType) {
7490 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7491 // a signed integer type, or an unsigned integer type.
7492 // Compatibility is based on the underlying type, not the promotion
7493 // type.
7494 QualType underlyingType = ET->getDecl()->getIntegerType();
7495 if (underlyingType.isNull()) return QualType();
7496 if (Context.hasSameType(underlyingType, other))
7497 return other;
7498
7499 // In block return types, we're more permissive and accept any
7500 // integral type of the same size.
7501 if (isBlockReturnType && other->isIntegerType() &&
7502 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7503 return other;
7504
7505 return QualType();
7506}
7507
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007508QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007509 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007510 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007511 // C++ [expr]: If an expression initially has the type "reference to T", the
7512 // type is adjusted to "T" prior to any further analysis, the expression
7513 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007514 // expression is an lvalue unless the reference is an rvalue reference and
7515 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007516 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7517 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007518
7519 if (Unqualified) {
7520 LHS = LHS.getUnqualifiedType();
7521 RHS = RHS.getUnqualifiedType();
7522 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007523
Eli Friedman47f77112008-08-22 00:56:42 +00007524 QualType LHSCan = getCanonicalType(LHS),
7525 RHSCan = getCanonicalType(RHS);
7526
7527 // If two types are identical, they are compatible.
7528 if (LHSCan == RHSCan)
7529 return LHS;
7530
John McCall8ccfcb52009-09-24 19:53:00 +00007531 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007532 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7533 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007534 if (LQuals != RQuals) {
7535 // If any of these qualifiers are different, we have a type
7536 // mismatch.
7537 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007538 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7539 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007540 return QualType();
7541
7542 // Exactly one GC qualifier difference is allowed: __strong is
7543 // okay if the other type has no GC qualifier but is an Objective
7544 // C object pointer (i.e. implicitly strong by default). We fix
7545 // this by pretending that the unqualified type was actually
7546 // qualified __strong.
7547 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7548 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7549 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7550
7551 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7552 return QualType();
7553
7554 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7555 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7556 }
7557 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7558 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7559 }
Eli Friedman47f77112008-08-22 00:56:42 +00007560 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007561 }
7562
7563 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007564
Eli Friedmandcca6332009-06-01 01:22:52 +00007565 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7566 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007567
Chris Lattnerfd652912008-01-14 05:45:46 +00007568 // We want to consider the two function types to be the same for these
7569 // comparisons, just force one to the other.
7570 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7571 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007572
7573 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007574 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7575 LHSClass = Type::ConstantArray;
7576 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7577 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007578
John McCall8b07ec22010-05-15 11:32:37 +00007579 // ObjCInterfaces are just specialized ObjCObjects.
7580 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7581 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7582
Nate Begemance4d7fc2008-04-18 23:10:10 +00007583 // Canonicalize ExtVector -> Vector.
7584 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7585 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007586
Chris Lattner95554662008-04-07 05:43:21 +00007587 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007588 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007589 // Note that we only have special rules for turning block enum
7590 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007591 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007592 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007593 }
John McCall9dd450b2009-09-21 23:43:11 +00007594 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007595 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007596 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007597 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007598 if (OfBlockPointer && !BlockReturnType) {
7599 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7600 return LHS;
7601 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7602 return RHS;
7603 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007604
Eli Friedman47f77112008-08-22 00:56:42 +00007605 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007606 }
Eli Friedman47f77112008-08-22 00:56:42 +00007607
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007608 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007609 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007610#define TYPE(Class, Base)
7611#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007612#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007613#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7614#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7615#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007616 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007617
Richard Smith27d807c2013-04-30 13:56:41 +00007618 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007619 case Type::LValueReference:
7620 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007621 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007622 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007623
John McCall8b07ec22010-05-15 11:32:37 +00007624 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007625 case Type::IncompleteArray:
7626 case Type::VariableArray:
7627 case Type::FunctionProto:
7628 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007629 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007630
Chris Lattnerfd652912008-01-14 05:45:46 +00007631 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007632 {
7633 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007634 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7635 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007636 if (Unqualified) {
7637 LHSPointee = LHSPointee.getUnqualifiedType();
7638 RHSPointee = RHSPointee.getUnqualifiedType();
7639 }
7640 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7641 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007642 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007643 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007644 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007645 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007646 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007647 return getPointerType(ResultType);
7648 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007649 case Type::BlockPointer:
7650 {
7651 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007652 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7653 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007654 if (Unqualified) {
7655 LHSPointee = LHSPointee.getUnqualifiedType();
7656 RHSPointee = RHSPointee.getUnqualifiedType();
7657 }
7658 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7659 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007660 if (ResultType.isNull()) return QualType();
7661 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7662 return LHS;
7663 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7664 return RHS;
7665 return getBlockPointerType(ResultType);
7666 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007667 case Type::Atomic:
7668 {
7669 // Merge two pointer types, while trying to preserve typedef info
7670 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7671 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7672 if (Unqualified) {
7673 LHSValue = LHSValue.getUnqualifiedType();
7674 RHSValue = RHSValue.getUnqualifiedType();
7675 }
7676 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7677 Unqualified);
7678 if (ResultType.isNull()) return QualType();
7679 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7680 return LHS;
7681 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7682 return RHS;
7683 return getAtomicType(ResultType);
7684 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007685 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007686 {
7687 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7688 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7689 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7690 return QualType();
7691
7692 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7693 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007694 if (Unqualified) {
7695 LHSElem = LHSElem.getUnqualifiedType();
7696 RHSElem = RHSElem.getUnqualifiedType();
7697 }
7698
7699 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007700 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007701 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7702 return LHS;
7703 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7704 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007705 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7706 ArrayType::ArraySizeModifier(), 0);
7707 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7708 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007709 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7710 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007711 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7712 return LHS;
7713 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7714 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007715 if (LVAT) {
7716 // FIXME: This isn't correct! But tricky to implement because
7717 // the array's size has to be the size of LHS, but the type
7718 // has to be different.
7719 return LHS;
7720 }
7721 if (RVAT) {
7722 // FIXME: This isn't correct! But tricky to implement because
7723 // the array's size has to be the size of RHS, but the type
7724 // has to be different.
7725 return RHS;
7726 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007727 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7728 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007729 return getIncompleteArrayType(ResultType,
7730 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007731 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007732 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007733 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007734 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007735 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007736 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007737 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007738 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007739 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007740 case Type::Complex:
7741 // Distinct complex types are incompatible.
7742 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007743 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007744 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007745 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7746 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007747 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007748 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007749 case Type::ObjCObject: {
7750 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007751 // FIXME: This should be type compatibility, e.g. whether
7752 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007753 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7754 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7755 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007756 return LHS;
7757
Eli Friedman47f77112008-08-22 00:56:42 +00007758 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007759 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007760 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007761 if (OfBlockPointer) {
7762 if (canAssignObjCInterfacesInBlockPointer(
7763 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007764 RHS->getAs<ObjCObjectPointerType>(),
7765 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007766 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007767 return QualType();
7768 }
John McCall9dd450b2009-09-21 23:43:11 +00007769 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7770 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007771 return LHS;
7772
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007773 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007774 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007775 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007776
David Blaikie8a40f702012-01-17 06:56:22 +00007777 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007778}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007779
Fariborz Jahanian97676972011-09-28 21:52:05 +00007780bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7781 const FunctionProtoType *FromFunctionType,
7782 const FunctionProtoType *ToFunctionType) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007783 if (FromFunctionType->hasAnyConsumedParams() !=
7784 ToFunctionType->hasAnyConsumedParams())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007785 return false;
7786 FunctionProtoType::ExtProtoInfo FromEPI =
7787 FromFunctionType->getExtProtoInfo();
7788 FunctionProtoType::ExtProtoInfo ToEPI =
7789 ToFunctionType->getExtProtoInfo();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007790 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
Alp Toker601b22c2014-01-21 23:35:24 +00007791 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7792 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
Fariborz Jahanian97676972011-09-28 21:52:05 +00007793 return false;
7794 }
7795 return true;
7796}
7797
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007798/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7799/// 'RHS' attributes and returns the merged version; including for function
7800/// return types.
7801QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7802 QualType LHSCan = getCanonicalType(LHS),
7803 RHSCan = getCanonicalType(RHS);
7804 // If two types are identical, they are compatible.
7805 if (LHSCan == RHSCan)
7806 return LHS;
7807 if (RHSCan->isFunctionType()) {
7808 if (!LHSCan->isFunctionType())
7809 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007810 QualType OldReturnType =
7811 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007812 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007813 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007814 QualType ResReturnType =
7815 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7816 if (ResReturnType.isNull())
7817 return QualType();
7818 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7819 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7820 // In either case, use OldReturnType to build the new function type.
7821 const FunctionType *F = LHS->getAs<FunctionType>();
7822 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007823 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7824 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007825 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007826 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007827 return ResultType;
7828 }
7829 }
7830 return QualType();
7831 }
7832
7833 // If the qualifiers are different, the types can still be merged.
7834 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7835 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7836 if (LQuals != RQuals) {
7837 // If any of these qualifiers are different, we have a type mismatch.
7838 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7839 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7840 return QualType();
7841
7842 // Exactly one GC qualifier difference is allowed: __strong is
7843 // okay if the other type has no GC qualifier but is an Objective
7844 // C object pointer (i.e. implicitly strong by default). We fix
7845 // this by pretending that the unqualified type was actually
7846 // qualified __strong.
7847 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7848 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7849 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7850
7851 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7852 return QualType();
7853
7854 if (GC_L == Qualifiers::Strong)
7855 return LHS;
7856 if (GC_R == Qualifiers::Strong)
7857 return RHS;
7858 return QualType();
7859 }
7860
7861 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7862 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7863 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7864 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7865 if (ResQT == LHSBaseQT)
7866 return LHS;
7867 if (ResQT == RHSBaseQT)
7868 return RHS;
7869 }
7870 return QualType();
7871}
7872
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007873//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007874// Integer Predicates
7875//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007876
Jay Foad39c79802011-01-12 09:06:06 +00007877unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007878 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007879 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007880 if (T->isBooleanType())
7881 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007882 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007883 return (unsigned)getTypeSize(T);
7884}
7885
Abramo Bagnara13640492012-09-09 10:21:24 +00007886QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007887 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007888
7889 // Turn <4 x signed int> -> <4 x unsigned int>
7890 if (const VectorType *VTy = T->getAs<VectorType>())
7891 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007892 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007893
7894 // For enums, we return the unsigned version of the base type.
7895 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007896 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007897
7898 const BuiltinType *BTy = T->getAs<BuiltinType>();
7899 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007900 switch (BTy->getKind()) {
7901 case BuiltinType::Char_S:
7902 case BuiltinType::SChar:
7903 return UnsignedCharTy;
7904 case BuiltinType::Short:
7905 return UnsignedShortTy;
7906 case BuiltinType::Int:
7907 return UnsignedIntTy;
7908 case BuiltinType::Long:
7909 return UnsignedLongTy;
7910 case BuiltinType::LongLong:
7911 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007912 case BuiltinType::Int128:
7913 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007914 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007915 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007916 }
7917}
7918
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00007919ASTMutationListener::~ASTMutationListener() { }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007920
Richard Smith1fa5d642013-05-11 05:45:24 +00007921void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7922 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007923
7924//===----------------------------------------------------------------------===//
7925// Builtin Type Computation
7926//===----------------------------------------------------------------------===//
7927
7928/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007929/// pointer over the consumed characters. This returns the resultant type. If
7930/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7931/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7932/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007933///
7934/// RequiresICE is filled in on return to indicate whether the value is required
7935/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007936static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007937 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007938 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007939 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007940 // Modifiers.
7941 int HowLong = 0;
7942 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007943 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007944
Chris Lattnerdc226c22010-10-01 22:42:38 +00007945 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007946 bool Done = false;
7947 while (!Done) {
7948 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007949 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007950 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007951 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007952 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007953 case 'S':
7954 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7955 assert(!Signed && "Can't use 'S' modifier multiple times!");
7956 Signed = true;
7957 break;
7958 case 'U':
7959 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00007960 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007961 Unsigned = true;
7962 break;
7963 case 'L':
7964 assert(HowLong <= 2 && "Can't have LLLL modifier");
7965 ++HowLong;
7966 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00007967 case 'W':
7968 // This modifier represents int64 type.
7969 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7970 switch (Context.getTargetInfo().getInt64Type()) {
7971 default:
7972 llvm_unreachable("Unexpected integer type");
7973 case TargetInfo::SignedLong:
7974 HowLong = 1;
7975 break;
7976 case TargetInfo::SignedLongLong:
7977 HowLong = 2;
7978 break;
7979 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00007980 }
7981 }
7982
7983 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007984
Chris Lattnerecd79c62009-06-14 00:45:47 +00007985 // Read the base type.
7986 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007987 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007988 case 'v':
7989 assert(HowLong == 0 && !Signed && !Unsigned &&
7990 "Bad modifiers used with 'v'!");
7991 Type = Context.VoidTy;
7992 break;
Jack Carter24bef982013-08-15 15:16:57 +00007993 case 'h':
7994 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00007995 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00007996 Type = Context.HalfTy;
7997 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007998 case 'f':
7999 assert(HowLong == 0 && !Signed && !Unsigned &&
8000 "Bad modifiers used with 'f'!");
8001 Type = Context.FloatTy;
8002 break;
8003 case 'd':
8004 assert(HowLong < 2 && !Signed && !Unsigned &&
8005 "Bad modifiers used with 'd'!");
8006 if (HowLong)
8007 Type = Context.LongDoubleTy;
8008 else
8009 Type = Context.DoubleTy;
8010 break;
8011 case 's':
8012 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8013 if (Unsigned)
8014 Type = Context.UnsignedShortTy;
8015 else
8016 Type = Context.ShortTy;
8017 break;
8018 case 'i':
8019 if (HowLong == 3)
8020 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8021 else if (HowLong == 2)
8022 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8023 else if (HowLong == 1)
8024 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8025 else
8026 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8027 break;
8028 case 'c':
8029 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8030 if (Signed)
8031 Type = Context.SignedCharTy;
8032 else if (Unsigned)
8033 Type = Context.UnsignedCharTy;
8034 else
8035 Type = Context.CharTy;
8036 break;
8037 case 'b': // boolean
8038 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8039 Type = Context.BoolTy;
8040 break;
8041 case 'z': // size_t.
8042 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8043 Type = Context.getSizeType();
8044 break;
8045 case 'F':
8046 Type = Context.getCFConstantStringType();
8047 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00008048 case 'G':
8049 Type = Context.getObjCIdType();
8050 break;
8051 case 'H':
8052 Type = Context.getObjCSelType();
8053 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00008054 case 'M':
8055 Type = Context.getObjCSuperType();
8056 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008057 case 'a':
8058 Type = Context.getBuiltinVaListType();
8059 assert(!Type.isNull() && "builtin va list type not initialized!");
8060 break;
8061 case 'A':
8062 // This is a "reference" to a va_list; however, what exactly
8063 // this means depends on how va_list is defined. There are two
8064 // different kinds of va_list: ones passed by value, and ones
8065 // passed by reference. An example of a by-value va_list is
8066 // x86, where va_list is a char*. An example of by-ref va_list
8067 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8068 // we want this argument to be a char*&; for x86-64, we want
8069 // it to be a __va_list_tag*.
8070 Type = Context.getBuiltinVaListType();
8071 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008072 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00008073 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008074 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00008075 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008076 break;
8077 case 'V': {
8078 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008079 unsigned NumElements = strtoul(Str, &End, 10);
8080 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008081 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00008082
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008083 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8084 RequiresICE, false);
8085 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00008086
8087 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00008088 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00008089 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008090 break;
8091 }
Douglas Gregorfed66992012-06-07 18:08:25 +00008092 case 'E': {
8093 char *End;
8094
8095 unsigned NumElements = strtoul(Str, &End, 10);
8096 assert(End != Str && "Missing vector size");
8097
8098 Str = End;
8099
8100 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8101 false);
8102 Type = Context.getExtVectorType(ElementType, NumElements);
8103 break;
8104 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008105 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008106 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8107 false);
8108 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008109 Type = Context.getComplexType(ElementType);
8110 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00008111 }
8112 case 'Y' : {
8113 Type = Context.getPointerDiffType();
8114 break;
8115 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00008116 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00008117 Type = Context.getFILEType();
8118 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008119 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008120 return QualType();
8121 }
Mike Stump2adb4da2009-07-28 23:47:15 +00008122 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00008123 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00008124 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00008125 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00008126 else
8127 Type = Context.getjmp_bufType();
8128
Mike Stump2adb4da2009-07-28 23:47:15 +00008129 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008130 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00008131 return QualType();
8132 }
8133 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00008134 case 'K':
8135 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8136 Type = Context.getucontext_tType();
8137
8138 if (Type.isNull()) {
8139 Error = ASTContext::GE_Missing_ucontext;
8140 return QualType();
8141 }
8142 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00008143 case 'p':
8144 Type = Context.getProcessIDType();
8145 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00008146 }
Mike Stump11289f42009-09-09 15:08:12 +00008147
Chris Lattnerdc226c22010-10-01 22:42:38 +00008148 // If there are modifiers and if we're allowed to parse them, go for it.
8149 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008150 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00008151 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00008152 default: Done = true; --Str; break;
8153 case '*':
8154 case '&': {
8155 // Both pointers and references can have their pointee types
8156 // qualified with an address space.
8157 char *End;
8158 unsigned AddrSpace = strtoul(Str, &End, 10);
8159 if (End != Str && AddrSpace != 0) {
8160 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
8161 Str = End;
8162 }
8163 if (c == '*')
8164 Type = Context.getPointerType(Type);
8165 else
8166 Type = Context.getLValueReferenceType(Type);
8167 break;
8168 }
8169 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8170 case 'C':
8171 Type = Type.withConst();
8172 break;
8173 case 'D':
8174 Type = Context.getVolatileType(Type);
8175 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00008176 case 'R':
8177 Type = Type.withRestrict();
8178 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008179 }
8180 }
Chris Lattner84733392010-10-01 07:13:18 +00008181
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008182 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00008183 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00008184
Chris Lattnerecd79c62009-06-14 00:45:47 +00008185 return Type;
8186}
8187
8188/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00008189QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008190 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00008191 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00008192 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00008193
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008194 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00008195
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008196 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008197 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008198 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8199 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008200 if (Error != GE_None)
8201 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008202
8203 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8204
Chris Lattnerecd79c62009-06-14 00:45:47 +00008205 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008206 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008207 if (Error != GE_None)
8208 return QualType();
8209
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008210 // If this argument is required to be an IntegerConstantExpression and the
8211 // caller cares, fill in the bitmask we return.
8212 if (RequiresICE && IntegerConstantArgs)
8213 *IntegerConstantArgs |= 1 << ArgTypes.size();
8214
Chris Lattnerecd79c62009-06-14 00:45:47 +00008215 // Do array -> pointer decay. The builtin should use the decayed type.
8216 if (Ty->isArrayType())
8217 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00008218
Chris Lattnerecd79c62009-06-14 00:45:47 +00008219 ArgTypes.push_back(Ty);
8220 }
8221
David Majnemerba3e5ec2015-03-13 18:26:17 +00008222 if (Id == Builtin::BI__GetExceptionInfo)
8223 return QualType();
8224
Chris Lattnerecd79c62009-06-14 00:45:47 +00008225 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8226 "'.' should only occur at end of builtin type list!");
8227
Reid Kleckner78af0702013-08-27 23:08:25 +00008228 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00008229 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8230
8231 bool Variadic = (TypeStr[0] == '.');
8232
8233 // We really shouldn't be making a no-proto type here, especially in C++.
8234 if (ArgTypes.empty() && Variadic)
8235 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00008236
John McCalldb40c7f2010-12-14 08:05:40 +00008237 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00008238 EPI.ExtInfo = EI;
8239 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00008240
Jordan Rose5c382722013-03-08 21:51:21 +00008241 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008242}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00008243
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008244static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8245 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008246 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008247 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008248
Rafael Espindola3ae00052013-05-13 00:12:11 +00008249 GVALinkage External = GVA_StrongExternal;
8250 switch (FD->getTemplateSpecializationKind()) {
8251 case TSK_Undeclared:
8252 case TSK_ExplicitSpecialization:
8253 External = GVA_StrongExternal;
8254 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008255
Rafael Espindola3ae00052013-05-13 00:12:11 +00008256 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008257 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008258
David Majnemerc3d07332014-05-15 06:25:57 +00008259 // C++11 [temp.explicit]p10:
8260 // [ Note: The intent is that an inline function that is the subject of
8261 // an explicit instantiation declaration will still be implicitly
8262 // instantiated when used so that the body can be considered for
8263 // inlining, but that no out-of-line copy of the inline function would be
8264 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00008265 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00008266 return GVA_AvailableExternally;
8267
Rafael Espindola3ae00052013-05-13 00:12:11 +00008268 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008269 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008270 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008271 }
8272
8273 if (!FD->isInlined())
8274 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00008275
David Majnemer3f021502015-10-08 04:53:31 +00008276 if ((!Context.getLangOpts().CPlusPlus &&
8277 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008278 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00008279 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008280 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8281
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008282 // GNU or C99 inline semantics. Determine whether this symbol should be
8283 // externally visible.
8284 if (FD->isInlineDefinitionExternallyVisible())
8285 return External;
8286
8287 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00008288 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008289 }
8290
David Majnemer54e3ba52014-04-02 23:17:29 +00008291 // Functions specified with extern and inline in -fms-compatibility mode
8292 // forcibly get emitted. While the body of the function cannot be later
8293 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00008294 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00008295 return GVA_StrongODR;
8296
David Majnemer27d69db2014-04-28 22:17:59 +00008297 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008298}
8299
Artem Belevich7b41f702015-09-23 17:44:53 +00008300static GVALinkage adjustGVALinkageForAttributes(GVALinkage L, const Decl *D) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008301 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8302 // dllexport/dllimport on inline functions.
8303 if (D->hasAttr<DLLImportAttr>()) {
8304 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8305 return GVA_AvailableExternally;
Artem Belevich7b41f702015-09-23 17:44:53 +00008306 } else if (D->hasAttr<DLLExportAttr>() || D->hasAttr<CUDAGlobalAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008307 if (L == GVA_DiscardableODR)
8308 return GVA_StrongODR;
8309 }
8310 return L;
8311}
8312
8313GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
Artem Belevich7b41f702015-09-23 17:44:53 +00008314 return adjustGVALinkageForAttributes(basicGVALinkageForFunction(*this, FD),
8315 FD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008316}
8317
8318static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8319 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008320 if (!VD->isExternallyVisible())
8321 return GVA_Internal;
8322
David Majnemer27d69db2014-04-28 22:17:59 +00008323 if (VD->isStaticLocal()) {
8324 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
8325 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8326 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8327 LexicalContext = LexicalContext->getLexicalParent();
8328
Richard Smith9e2341d2015-03-23 03:25:59 +00008329 // Let the static local variable inherit its linkage from the nearest
David Majnemer27d69db2014-04-28 22:17:59 +00008330 // enclosing function.
8331 if (LexicalContext)
8332 StaticLocalLinkage =
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008333 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
David Majnemer27d69db2014-04-28 22:17:59 +00008334
8335 // GVA_StrongODR function linkage is stronger than what we need,
8336 // downgrade to GVA_DiscardableODR.
8337 // This allows us to discard the variable if we never end up needing it.
8338 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
8339 : StaticLocalLinkage;
8340 }
8341
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008342 // MSVC treats in-class initialized static data members as definitions.
8343 // By giving them non-strong linkage, out-of-line definitions won't
8344 // cause link errors.
8345 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8346 return GVA_DiscardableODR;
8347
Richard Smith8809a0c2013-09-27 20:14:12 +00008348 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008349 case TSK_Undeclared:
Rafael Espindola3ae00052013-05-13 00:12:11 +00008350 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008351
David Majnemer6d1780c2015-07-17 23:36:49 +00008352 case TSK_ExplicitSpecialization:
David Majnemer3f021502015-10-08 04:53:31 +00008353 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8354 VD->isStaticDataMember()
David Majnemer6d1780c2015-07-17 23:36:49 +00008355 ? GVA_StrongODR
8356 : GVA_StrongExternal;
8357
Rafael Espindola3ae00052013-05-13 00:12:11 +00008358 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008359 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008360
David Majnemer27d69db2014-04-28 22:17:59 +00008361 case TSK_ExplicitInstantiationDeclaration:
8362 return GVA_AvailableExternally;
8363
Rafael Espindola3ae00052013-05-13 00:12:11 +00008364 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008365 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008366 }
Rafael Espindola27699c82013-05-13 14:05:53 +00008367
8368 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008369}
8370
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008371GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Artem Belevich7b41f702015-09-23 17:44:53 +00008372 return adjustGVALinkageForAttributes(basicGVALinkageForVariable(*this, VD),
8373 VD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008374}
8375
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00008376bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008377 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8378 if (!VD->isFileVarDecl())
8379 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00008380 // Global named register variables (GNU extension) are never emitted.
8381 if (VD->getStorageClass() == SC_Register)
8382 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00008383 if (VD->getDescribedVarTemplate() ||
8384 isa<VarTemplatePartialSpecializationDecl>(VD))
8385 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00008386 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8387 // We never need to emit an uninstantiated function template.
8388 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8389 return false;
Alexey Bataev97720002014-11-11 04:05:39 +00008390 } else if (isa<OMPThreadPrivateDecl>(D))
8391 return true;
8392 else
Richard Smith5205a8c2013-04-01 20:22:16 +00008393 return false;
8394
8395 // If this is a member of a class template, we do not need to emit it.
8396 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008397 return false;
8398
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008399 // Weak references don't produce any output by themselves.
8400 if (D->hasAttr<WeakRefAttr>())
8401 return false;
8402
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008403 // Aliases and used decls are required.
8404 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8405 return true;
8406
8407 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8408 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00008409 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00008410 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008411
8412 // Constructors and destructors are required.
8413 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8414 return true;
8415
John McCall6bd2a892013-01-25 22:31:03 +00008416 // The key function for a class is required. This rule only comes
8417 // into play when inline functions can be key functions, though.
8418 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8419 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8420 const CXXRecordDecl *RD = MD->getParent();
8421 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8422 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8423 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8424 return true;
8425 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008426 }
8427 }
8428
8429 GVALinkage Linkage = GetGVALinkageForFunction(FD);
8430
8431 // static, static inline, always_inline, and extern inline functions can
8432 // always be deferred. Normal inline functions can be deferred in C99/C++.
8433 // Implicit template instantiations can also be deferred in C++.
David Majnemer27d69db2014-04-28 22:17:59 +00008434 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8435 Linkage == GVA_DiscardableODR)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008436 return false;
8437 return true;
8438 }
Douglas Gregor87d81242011-09-10 00:22:34 +00008439
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008440 const VarDecl *VD = cast<VarDecl>(D);
8441 assert(VD->isFileVarDecl() && "Expected file scoped var");
8442
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008443 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8444 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008445 return false;
8446
Richard Smitha0e5e542012-11-12 21:38:00 +00008447 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008448 GVALinkage L = GetGVALinkageForVariable(VD);
David Majnemerc3d07332014-05-15 06:25:57 +00008449 if (L != GVA_Internal && L != GVA_AvailableExternally &&
8450 L != GVA_DiscardableODR)
Richard Smitha0e5e542012-11-12 21:38:00 +00008451 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008452
Richard Smitha0e5e542012-11-12 21:38:00 +00008453 // Variables that have destruction with side-effects are required.
8454 if (VD->getType().isDestructedType())
8455 return true;
8456
8457 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00008458 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
8459 !VD->evaluateValue())
Richard Smitha0e5e542012-11-12 21:38:00 +00008460 return true;
8461
8462 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008463}
Charles Davis53c59df2010-08-16 03:33:14 +00008464
Reid Kleckner78af0702013-08-27 23:08:25 +00008465CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8466 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00008467 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00008468 if (IsCXXMethod)
8469 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00008470
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00008471 if (LangOpts.MRTD && !IsVariadic) return CC_X86StdCall;
8472
8473 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00008474}
8475
Jay Foad39c79802011-01-12 09:06:06 +00008476bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00008477 // Pass through to the C++ ABI object
8478 return ABI->isNearlyEmpty(RD);
8479}
8480
Reid Kleckner96f8f932014-02-05 17:27:08 +00008481VTableContextBase *ASTContext::getVTableContext() {
8482 if (!VTContext.get()) {
8483 if (Target->getCXXABI().isMicrosoft())
8484 VTContext.reset(new MicrosoftVTableContext(*this));
8485 else
8486 VTContext.reset(new ItaniumVTableContext(*this));
8487 }
8488 return VTContext.get();
8489}
8490
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008491MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00008492 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00008493 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00008494 case TargetCXXABI::GenericItanium:
8495 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00008496 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00008497 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00008498 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00008499 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +00008500 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008501 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00008502 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008503 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008504 }
David Blaikie83d382b2011-09-23 05:06:16 +00008505 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008506}
8507
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00008508CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008509
8510size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00008511 return ASTRecordLayouts.getMemorySize() +
8512 llvm::capacity_in_bytes(ObjCLayouts) +
8513 llvm::capacity_in_bytes(KeyFunctions) +
8514 llvm::capacity_in_bytes(ObjCImpls) +
8515 llvm::capacity_in_bytes(BlockVarCopyInits) +
8516 llvm::capacity_in_bytes(DeclAttrs) +
8517 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8518 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8519 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8520 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8521 llvm::capacity_in_bytes(OverriddenMethods) +
8522 llvm::capacity_in_bytes(Types) +
8523 llvm::capacity_in_bytes(VariableArrayTypes) +
8524 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008525}
Ted Kremenek540017e2011-10-06 05:00:56 +00008526
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008527/// getIntTypeForBitwidth -
8528/// sets integer QualTy according to specified details:
8529/// bitwidth, signed/unsigned.
8530/// Returns empty type if there is no appropriate target types.
8531QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8532 unsigned Signed) const {
8533 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8534 CanQualType QualTy = getFromTargetType(Ty);
8535 if (!QualTy && DestWidth == 128)
8536 return Signed ? Int128Ty : UnsignedInt128Ty;
8537 return QualTy;
8538}
8539
8540/// getRealTypeForBitwidth -
8541/// sets floating point QualTy according to specified bitwidth.
8542/// Returns empty type if there is no appropriate target types.
8543QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8544 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8545 switch (Ty) {
8546 case TargetInfo::Float:
8547 return FloatTy;
8548 case TargetInfo::Double:
8549 return DoubleTy;
8550 case TargetInfo::LongDouble:
8551 return LongDoubleTy;
8552 case TargetInfo::NoFloat:
8553 return QualType();
8554 }
8555
8556 llvm_unreachable("Unhandled TargetInfo::RealType value");
8557}
8558
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008559void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8560 if (Number > 1)
8561 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008562}
8563
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008564unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8565 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8566 MangleNumbers.find(ND);
8567 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008568}
8569
David Majnemer2206bf52014-03-05 08:57:59 +00008570void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8571 if (Number > 1)
8572 StaticLocalNumbers[VD] = Number;
8573}
8574
8575unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8576 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8577 StaticLocalNumbers.find(VD);
8578 return I != StaticLocalNumbers.end() ? I->second : 1;
8579}
8580
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008581MangleNumberingContext &
8582ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008583 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8584 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8585 if (!MCtx)
8586 MCtx = createMangleNumberingContext();
8587 return *MCtx;
8588}
8589
8590MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8591 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008592}
8593
David Majnemere7a818f2015-03-06 18:53:55 +00008594const CXXConstructorDecl *
8595ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
8596 return ABI->getCopyConstructorForExceptionObject(
8597 cast<CXXRecordDecl>(RD->getFirstDecl()));
8598}
8599
8600void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
8601 CXXConstructorDecl *CD) {
8602 return ABI->addCopyConstructorForExceptionObject(
8603 cast<CXXRecordDecl>(RD->getFirstDecl()),
8604 cast<CXXConstructorDecl>(CD->getFirstDecl()));
8605}
8606
David Majnemerdfa6d202015-03-11 18:36:39 +00008607void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8608 unsigned ParmIdx, Expr *DAE) {
8609 ABI->addDefaultArgExprForConstructor(
8610 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE);
8611}
8612
8613Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8614 unsigned ParmIdx) {
8615 return ABI->getDefaultArgExprForConstructor(
8616 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx);
8617}
8618
David Majnemer00350522015-08-31 18:48:39 +00008619void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
8620 TypedefNameDecl *DD) {
8621 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
8622}
8623
8624TypedefNameDecl *
8625ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
8626 return ABI->getTypedefNameForUnnamedTagDecl(TD);
8627}
8628
8629void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
8630 DeclaratorDecl *DD) {
8631 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
8632}
8633
8634DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
8635 return ABI->getDeclaratorForUnnamedTagDecl(TD);
8636}
8637
Ted Kremenek540017e2011-10-06 05:00:56 +00008638void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8639 ParamIndices[D] = index;
8640}
8641
8642unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8643 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8644 assert(I != ParamIndices.end() &&
8645 "ParmIndices lacks entry set by ParmVarDecl");
8646 return I->second;
8647}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008648
Richard Smithe6c01442013-06-05 00:46:14 +00008649APValue *
8650ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8651 bool MayCreate) {
8652 assert(E && E->getStorageDuration() == SD_Static &&
8653 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +00008654 if (MayCreate) {
8655 APValue *&MTVI = MaterializedTemporaryValues[E];
8656 if (!MTVI)
8657 MTVI = new (*this) APValue;
8658 return MTVI;
8659 }
Richard Smithe6c01442013-06-05 00:46:14 +00008660
David Majnemer2dcef9e2015-08-13 23:50:15 +00008661 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +00008662}
8663
Fariborz Jahanian615de762013-05-28 17:37:39 +00008664bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8665 const llvm::Triple &T = getTargetInfo().getTriple();
8666 if (!T.isOSDarwin())
8667 return false;
8668
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008669 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8670 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8671 return false;
8672
Fariborz Jahanian615de762013-05-28 17:37:39 +00008673 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8674 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8675 uint64_t Size = sizeChars.getQuantity();
8676 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8677 unsigned Align = alignChars.getQuantity();
8678 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8679 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8680}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008681
8682namespace {
8683
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008684ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
8685 ASTContext::ParentMapPointers::mapped_type U) {
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00008686 if (const auto *D = U.dyn_cast<const Decl *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008687 return ast_type_traits::DynTypedNode::create(*D);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00008688 if (const auto *S = U.dyn_cast<const Stmt *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008689 return ast_type_traits::DynTypedNode::create(*S);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00008690 return *U.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008691}
8692
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008693/// Template specializations to abstract away from pointers and TypeLocs.
8694/// @{
8695template <typename T>
8696ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
8697 return ast_type_traits::DynTypedNode::create(*Node);
8698}
8699template <>
8700ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
8701 return ast_type_traits::DynTypedNode::create(Node);
8702}
8703template <>
8704ast_type_traits::DynTypedNode
8705createDynTypedNode(const NestedNameSpecifierLoc &Node) {
8706 return ast_type_traits::DynTypedNode::create(Node);
8707}
8708/// @}
8709
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008710 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8711 /// parents as defined by the \c RecursiveASTVisitor.
8712 ///
8713 /// Note that the relationship described here is purely in terms of AST
8714 /// traversal - there are other relationships (for example declaration context)
8715 /// in the AST that are better modeled by special matchers.
8716 ///
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00008717 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008718 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8719
8720 public:
8721 /// \brief Builds and returns the translation unit's parent map.
8722 ///
8723 /// The caller takes ownership of the returned \c ParentMap.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008724 static std::pair<ASTContext::ParentMapPointers *,
8725 ASTContext::ParentMapOtherNodes *>
8726 buildMap(TranslationUnitDecl &TU) {
8727 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
8728 new ASTContext::ParentMapOtherNodes);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008729 Visitor.TraverseDecl(&TU);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008730 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008731 }
8732
8733 private:
8734 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8735
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008736 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
8737 ASTContext::ParentMapOtherNodes *OtherParents)
8738 : Parents(Parents), OtherParents(OtherParents) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008739
8740 bool shouldVisitTemplateInstantiations() const {
8741 return true;
8742 }
8743 bool shouldVisitImplicitCode() const {
8744 return true;
8745 }
8746 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8747 // are not triggered during data recursion.
8748 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8749 return false;
8750 }
8751
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008752 template <typename T, typename MapNodeTy, typename MapTy>
8753 bool TraverseNode(T Node, MapNodeTy MapNode,
8754 bool (VisitorBase::*traverse)(T), MapTy *Parents) {
Craig Topper36250ad2014-05-12 05:36:57 +00008755 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008756 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00008757 if (ParentStack.size() > 0) {
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00008758 // FIXME: Currently we add the same parent multiple times, but only
8759 // when no memoization data is available for the type.
8760 // For example when we visit all subexpressions of template
8761 // instantiations; this is suboptimal, but benign: the only way to
8762 // visit those is with hasAncestor / hasParent, and those do not create
8763 // new matches.
8764 // The plan is to enable DynTypedNode to be storable in a map or hash
8765 // map. The main problem there is to implement hash functions /
8766 // comparison operators for all types that DynTypedNode supports that
8767 // do not have pointer identity.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008768 auto &NodeOrVector = (*Parents)[MapNode];
Manuel Klimek95403e62014-05-21 13:28:59 +00008769 if (NodeOrVector.isNull()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008770 if (const auto *D = ParentStack.back().get<Decl>())
8771 NodeOrVector = D;
8772 else if (const auto *S = ParentStack.back().get<Stmt>())
8773 NodeOrVector = S;
8774 else
8775 NodeOrVector =
8776 new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008777 } else {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008778 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
8779 auto *Vector = new ASTContext::ParentVector(
8780 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008781 if (auto *Node =
8782 NodeOrVector
8783 .template dyn_cast<ast_type_traits::DynTypedNode *>())
8784 delete Node;
Benjamin Kramer422b3ff2015-10-23 13:24:18 +00008785 NodeOrVector = Vector;
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008786 }
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008787
8788 auto *Vector =
8789 NodeOrVector.template get<ASTContext::ParentVector *>();
8790 // Skip duplicates for types that have memoization data.
8791 // We must check that the type has memoization data before calling
8792 // std::find() because DynTypedNode::operator== can't compare all
8793 // types.
8794 bool Found = ParentStack.back().getMemoizationData() &&
8795 std::find(Vector->begin(), Vector->end(),
8796 ParentStack.back()) != Vector->end();
8797 if (!Found)
8798 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008799 }
8800 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008801 ParentStack.push_back(createDynTypedNode(Node));
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008802 bool Result = (this ->* traverse) (Node);
8803 ParentStack.pop_back();
8804 return Result;
8805 }
8806
8807 bool TraverseDecl(Decl *DeclNode) {
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008808 return TraverseNode(DeclNode, DeclNode, &VisitorBase::TraverseDecl,
8809 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008810 }
8811
8812 bool TraverseStmt(Stmt *StmtNode) {
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008813 return TraverseNode(StmtNode, StmtNode, &VisitorBase::TraverseStmt,
8814 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008815 }
8816
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008817 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
8818 return TraverseNode(TypeLocNode,
8819 ast_type_traits::DynTypedNode::create(TypeLocNode),
8820 &VisitorBase::TraverseTypeLoc, OtherParents);
8821 }
8822
8823 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
8824 return TraverseNode(
8825 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
8826 &VisitorBase::TraverseNestedNameSpecifierLoc, OtherParents);
8827 }
8828
8829 ASTContext::ParentMapPointers *Parents;
8830 ASTContext::ParentMapOtherNodes *OtherParents;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008831 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8832
8833 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8834 };
8835
8836} // end namespace
8837
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008838template <typename NodeTy, typename MapTy>
8839static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
8840 const MapTy &Map) {
8841 auto I = Map.find(Node);
8842 if (I == Map.end()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008843 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008844 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008845 if (auto *V = I->second.template dyn_cast<ASTContext::ParentVector *>()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008846 return llvm::makeArrayRef(*V);
Manuel Klimek95403e62014-05-21 13:28:59 +00008847 }
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008848 return getSingleDynTypedNodeFromParentMap(I->second);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008849}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008850
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008851ASTContext::DynTypedNodeList
8852ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8853 if (!PointerParents) {
8854 // We always need to run over the whole translation unit, as
8855 // hasAncestor can escape any subtree.
8856 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
8857 PointerParents.reset(Maps.first);
8858 OtherParents.reset(Maps.second);
8859 }
8860 if (Node.getNodeKind().hasPointerIdentity())
8861 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
8862 return getDynNodeFromMap(Node, *OtherParents);
8863}
8864
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008865bool
8866ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8867 const ObjCMethodDecl *MethodImpl) {
8868 // No point trying to match an unavailable/deprecated mothod.
8869 if (MethodDecl->hasAttr<UnavailableAttr>()
8870 || MethodDecl->hasAttr<DeprecatedAttr>())
8871 return false;
8872 if (MethodDecl->getObjCDeclQualifier() !=
8873 MethodImpl->getObjCDeclQualifier())
8874 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008875 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008876 return false;
8877
8878 if (MethodDecl->param_size() != MethodImpl->param_size())
8879 return false;
8880
8881 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8882 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8883 EF = MethodDecl->param_end();
8884 IM != EM && IF != EF; ++IM, ++IF) {
8885 const ParmVarDecl *DeclVar = (*IF);
8886 const ParmVarDecl *ImplVar = (*IM);
8887 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8888 return false;
8889 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8890 return false;
8891 }
8892 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8893
8894}
Richard Smith053f6c62014-05-16 23:01:30 +00008895
8896// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
8897// doesn't include ASTContext.h
8898template
8899clang::LazyGenerationalUpdatePtr<
8900 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
8901clang::LazyGenerationalUpdatePtr<
8902 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
8903 const clang::ASTContext &Ctx, Decl *Value);