blob: fadcda0c4b00e4bba8bee8cf28eff341a36dc3ae [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"
Chandler Carruthaa36b892015-12-30 03:40:23 +000022#include "clang/AST/DeclContextInternals.h"
Steve Naroff67391b82007-10-01 19:00:59 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000024#include "clang/AST/DeclTemplate.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000025#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000026#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000027#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000028#include "clang/AST/Mangle.h"
Reid Klecknerd8110b62013-09-10 20:14:30 +000029#include "clang/AST/MangleNumberingContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000030#include "clang/AST/RecordLayout.h"
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000031#include "clang/AST/RecursiveASTVisitor.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000032#include "clang/AST/TypeLoc.h"
Reid Kleckner96f8f932014-02-05 17:27:08 +000033#include "clang/AST/VTableBuilder.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000034#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000035#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000036#include "clang/Basic/TargetInfo.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 {
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +000060 HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
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}
Eugene Zelenkod4304d22015-11-04 21:37:17 +0000330} // anonymous namespace
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000331
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;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000433}
434
Richard Smithb39b9d52013-05-21 05:24:00 +0000435comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
436 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000437 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000438}
439
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000440comments::FullComment *ASTContext::getCommentForDecl(
441 const Decl *D,
442 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000443 if (D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000444 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000445 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000446
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000447 const Decl *Canonical = D->getCanonicalDecl();
448 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
449 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000450
451 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000452 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000453 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000454 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000455 return CFC;
456 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000457 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000458 }
459
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000460 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000461
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000462 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000463 if (!RC) {
464 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000465 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000466 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000467 if (OMD && OMD->isPropertyAccessor())
468 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
469 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
470 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000471 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000472 addRedeclaredMethods(OMD, Overridden);
473 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000474 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
475 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
476 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000477 }
Fariborz Jahanian6384fbb2013-05-02 15:44:16 +0000478 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000479 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000480 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000481 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000482 if (const TagType *TT = QT->getAs<TagType>())
483 if (const Decl *TD = TT->getDecl())
484 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000485 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000486 }
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000487 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
488 while (IC->getSuperClass()) {
489 IC = IC->getSuperClass();
490 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
491 return cloneFullComment(FC, D);
492 }
493 }
494 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
495 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
496 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
497 return cloneFullComment(FC, D);
498 }
499 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
500 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000501 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000502 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000503 for (const auto &I : RD->bases()) {
504 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000505 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000506 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000507 if (Ty.isNull())
508 continue;
509 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
510 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
511 continue;
512
513 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
514 return cloneFullComment(FC, D);
515 }
516 }
517 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000518 for (const auto &I : RD->vbases()) {
519 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000520 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000521 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000522 if (Ty.isNull())
523 continue;
524 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
525 if (!(VirtualBase= VirtualBase->getDefinition()))
526 continue;
527 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
528 return cloneFullComment(FC, D);
529 }
530 }
531 }
Craig Topper36250ad2014-05-12 05:36:57 +0000532 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000533 }
534
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000535 // If the RawComment was attached to other redeclaration of this Decl, we
536 // should parse the comment in context of that other Decl. This is important
537 // because comments can contain references to parameter names which can be
538 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000539 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000540 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000541
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000542 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000543 ParsedComments[Canonical] = FC;
544 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000545}
546
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000547void
548ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
549 TemplateTemplateParmDecl *Parm) {
550 ID.AddInteger(Parm->getDepth());
551 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000552 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000553
554 TemplateParameterList *Params = Parm->getTemplateParameters();
555 ID.AddInteger(Params->size());
556 for (TemplateParameterList::const_iterator P = Params->begin(),
557 PEnd = Params->end();
558 P != PEnd; ++P) {
559 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
560 ID.AddInteger(0);
561 ID.AddBoolean(TTP->isParameterPack());
562 continue;
563 }
564
565 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
566 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000567 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000568 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000569 if (NTTP->isExpandedParameterPack()) {
570 ID.AddBoolean(true);
571 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000572 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
573 QualType T = NTTP->getExpansionType(I);
574 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
575 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000576 } else
577 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000578 continue;
579 }
580
581 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
582 ID.AddInteger(2);
583 Profile(ID, TTP);
584 }
585}
586
587TemplateTemplateParmDecl *
588ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000589 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000590 // Check if we already have a canonical template template parameter.
591 llvm::FoldingSetNodeID ID;
592 CanonicalTemplateTemplateParm::Profile(ID, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000593 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000594 CanonicalTemplateTemplateParm *Canonical
595 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
596 if (Canonical)
597 return Canonical->getParam();
598
599 // Build a canonical template parameter list.
600 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000601 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000602 CanonParams.reserve(Params->size());
603 for (TemplateParameterList::const_iterator P = Params->begin(),
604 PEnd = Params->end();
605 P != PEnd; ++P) {
606 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
607 CanonParams.push_back(
608 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000609 SourceLocation(),
610 SourceLocation(),
611 TTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000612 TTP->getIndex(), nullptr, false,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000613 TTP->isParameterPack()));
614 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000615 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
616 QualType T = getCanonicalType(NTTP->getType());
617 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
618 NonTypeTemplateParmDecl *Param;
619 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000620 SmallVector<QualType, 2> ExpandedTypes;
621 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000622 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
623 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
624 ExpandedTInfos.push_back(
625 getTrivialTypeSourceInfo(ExpandedTypes.back()));
626 }
627
628 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000629 SourceLocation(),
630 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000631 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000632 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000633 T,
634 TInfo,
David Majnemerdfecf1a2016-07-06 04:19:16 +0000635 ExpandedTypes,
636 ExpandedTInfos);
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000637 } else {
638 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000639 SourceLocation(),
640 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000641 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000642 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000643 T,
644 NTTP->isParameterPack(),
645 TInfo);
646 }
647 CanonParams.push_back(Param);
648
649 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000650 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
651 cast<TemplateTemplateParmDecl>(*P)));
652 }
653
654 TemplateTemplateParmDecl *CanonTTP
655 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
656 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000657 TTP->getPosition(),
658 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000659 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000660 TemplateParameterList::Create(*this, SourceLocation(),
661 SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +0000662 CanonParams,
Hubert Tong286547a2016-07-20 01:05:31 +0000663 SourceLocation()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000664
665 // Get the new insert position for the node we care about.
666 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000667 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000668 (void)Canonical;
669
670 // Create the canonical template template parameter entry.
671 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
672 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
673 return CanonTTP;
674}
675
Charles Davis53c59df2010-08-16 03:33:14 +0000676CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000677 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000678
John McCall359b8852013-01-25 22:30:49 +0000679 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000680 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000681 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000682 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +0000683 case TargetCXXABI::WatchOS:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000684 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000685 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000686 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000687 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000688 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000689 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000690 return CreateMicrosoftCXXABI(*this);
691 }
David Blaikie8a40f702012-01-17 06:56:22 +0000692 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000693}
694
Douglas Gregore8bbc122011-09-02 00:18:52 +0000695static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000696 const LangOptions &LOpts) {
697 if (LOpts.FakeAddressSpaceMap) {
698 // The fake address space map must have a distinct entry for each
699 // language-specific address space.
700 static const unsigned FakeAddrSpaceMap[] = {
701 1, // opencl_global
702 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000703 3, // opencl_constant
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000704 4, // opencl_generic
705 5, // cuda_device
706 6, // cuda_constant
707 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000708 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000709 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000710 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000711 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000712 }
713}
714
David Tweed31d09b02013-09-13 12:04:22 +0000715static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
716 const LangOptions &LangOpts) {
717 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000718 case LangOptions::ASMM_Target:
719 return TI.useAddressSpaceMapMangling();
720 case LangOptions::ASMM_On:
721 return true;
722 case LangOptions::ASMM_Off:
723 return false;
724 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000725 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000726}
727
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000728ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000729 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000730 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000731 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
732 DependentTemplateSpecializationTypes(this_()),
733 SubstTemplateTemplateParmPacks(this_()),
734 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +0000735 UInt128Decl(nullptr), BuiltinVaListDecl(nullptr),
736 BuiltinMSVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr),
737 ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
Ben Langmuirf5416742016-02-04 00:55:24 +0000738 CFConstantStringTagDecl(nullptr), CFConstantStringTypeDecl(nullptr),
739 ObjCInstanceTypeDecl(nullptr), FILEDecl(nullptr), jmp_bufDecl(nullptr),
740 sigjmp_bufDecl(nullptr), ucontext_tDecl(nullptr),
741 BlockDescriptorType(nullptr), BlockDescriptorExtendedType(nullptr),
742 cudaConfigureCallDecl(nullptr), FirstLocalImport(), LastLocalImport(),
Eric Fiselier6ad68552016-07-01 01:24:09 +0000743 ExternCContext(nullptr), MakeIntegerSeqDecl(nullptr),
744 TypePackElementDecl(nullptr), SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000745 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000746 AddrSpaceMap(nullptr), Target(nullptr), AuxTarget(nullptr),
747 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
748 BuiltinInfo(builtins), DeclarationNames(*this), ExternalSource(nullptr),
749 Listener(nullptr), Comments(SM), CommentsLoaded(false),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000750 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000751 TUDecl = TranslationUnitDecl::Create(*this);
752}
753
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000754ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000755 ReleaseParentMapEntries();
756
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000757 // Release the DenseMaps associated with DeclContext objects.
758 // FIXME: Is this the ideal solution?
759 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000760
Manuel Klimeka7328992013-06-03 13:51:33 +0000761 // Call all of the deallocation functions on all of their targets.
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000762 for (auto &Pair : Deallocations)
763 (Pair.first)(Pair.second);
Manuel Klimeka7328992013-06-03 13:51:33 +0000764
Ted Kremenek076baeb2010-06-08 23:00:58 +0000765 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000766 // because they can contain DenseMaps.
767 for (llvm::DenseMap<const ObjCContainerDecl*,
768 const ASTRecordLayout*>::iterator
769 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
770 // Increment in loop to prevent using deallocated memory.
771 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
772 R->Destroy(*this);
773
Ted Kremenek076baeb2010-06-08 23:00:58 +0000774 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
775 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
776 // Increment in loop to prevent using deallocated memory.
777 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
778 R->Destroy(*this);
779 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000780
781 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
782 AEnd = DeclAttrs.end();
783 A != AEnd; ++A)
784 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000785
David Majnemere694f3e2015-08-14 14:43:50 +0000786 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
787 MaterializedTemporaryValues)
788 MTVPair.second->~APValue();
789
Reid Kleckner588c9372014-02-19 23:44:52 +0000790 llvm::DeleteContainerSeconds(MangleNumberingContexts);
Douglas Gregor561eceb2010-08-30 16:49:28 +0000791}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000792
Manuel Klimek95403e62014-05-21 13:28:59 +0000793void ASTContext::ReleaseParentMapEntries() {
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000794 if (!PointerParents) return;
795 for (const auto &Entry : *PointerParents) {
796 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
797 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
798 } else if (Entry.second.is<ParentVector *>()) {
799 delete Entry.second.get<ParentVector *>();
800 }
801 }
802 for (const auto &Entry : *OtherParents) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000803 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
804 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +0000805 } else if (Entry.second.is<ParentVector *>()) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000806 delete Entry.second.get<ParentVector *>();
807 }
808 }
809}
810
Douglas Gregor1a809332010-05-23 18:26:36 +0000811void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000812 Deallocations.push_back({Callback, Data});
Douglas Gregor1a809332010-05-23 18:26:36 +0000813}
814
Mike Stump11289f42009-09-09 15:08:12 +0000815void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000816ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000817 ExternalSource = std::move(Source);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000818}
819
Chris Lattner4eb445d2007-01-26 01:27:23 +0000820void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000821 llvm::errs() << "\n*** AST Context Stats:\n";
822 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000823
Douglas Gregora30d0462009-05-26 14:40:08 +0000824 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000825#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000826#define ABSTRACT_TYPE(Name, Parent)
827#include "clang/AST/TypeNodes.def"
828 0 // Extra
829 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000830
Chris Lattner4eb445d2007-01-26 01:27:23 +0000831 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
832 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000833 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000834 }
835
Douglas Gregora30d0462009-05-26 14:40:08 +0000836 unsigned Idx = 0;
837 unsigned TotalBytes = 0;
838#define TYPE(Name, Parent) \
839 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000840 llvm::errs() << " " << counts[Idx] << " " << #Name \
841 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000842 TotalBytes += counts[Idx] * sizeof(Name##Type); \
843 ++Idx;
844#define ABSTRACT_TYPE(Name, Parent)
845#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000846
Chandler Carruth3c147a72011-07-04 05:32:14 +0000847 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
848
Douglas Gregor7454c562010-07-02 20:37:36 +0000849 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000850 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
851 << NumImplicitDefaultConstructors
852 << " implicit default constructors created\n";
853 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
854 << NumImplicitCopyConstructors
855 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000856 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000857 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
858 << NumImplicitMoveConstructors
859 << " implicit move constructors created\n";
860 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
861 << NumImplicitCopyAssignmentOperators
862 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000863 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000864 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
865 << NumImplicitMoveAssignmentOperators
866 << " implicit move assignment operators created\n";
867 llvm::errs() << NumImplicitDestructorsDeclared << "/"
868 << NumImplicitDestructors
869 << " implicit destructors created\n";
870
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000871 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000872 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000873 ExternalSource->PrintStats();
874 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000875
Douglas Gregor5b11d492010-07-25 17:53:33 +0000876 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000877}
878
Richard Smith42413142015-05-15 20:05:43 +0000879void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
880 bool NotifyListeners) {
881 if (NotifyListeners)
882 if (auto *Listener = getASTMutationListener())
883 Listener->RedefinedHiddenDefinition(ND, M);
884
885 if (getLangOpts().ModulesLocalVisibility)
886 MergedDefModules[ND].push_back(M);
887 else
888 ND->setHidden(false);
889}
890
891void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
892 auto It = MergedDefModules.find(ND);
893 if (It == MergedDefModules.end())
894 return;
895
896 auto &Merged = It->second;
897 llvm::DenseSet<Module*> Found;
898 for (Module *&M : Merged)
899 if (!Found.insert(M).second)
900 M = nullptr;
901 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
902}
903
Richard Smithdc1f0422016-07-20 19:10:16 +0000904void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
905 if (LazyInitializers.empty())
906 return;
907
908 auto *Source = Ctx.getExternalSource();
909 assert(Source && "lazy initializers but no external source");
910
911 auto LazyInits = std::move(LazyInitializers);
912 LazyInitializers.clear();
913
914 for (auto ID : LazyInits)
915 Initializers.push_back(Source->GetExternalDecl(ID));
916
917 assert(LazyInitializers.empty() &&
918 "GetExternalDecl for lazy module initializer added more inits");
919}
920
921void ASTContext::addModuleInitializer(Module *M, Decl *D) {
922 // One special case: if we add a module initializer that imports another
923 // module, and that module's only initializer is an ImportDecl, simplify.
924 if (auto *ID = dyn_cast<ImportDecl>(D)) {
925 auto It = ModuleInitializers.find(ID->getImportedModule());
926
927 // Maybe the ImportDecl does nothing at all. (Common case.)
928 if (It == ModuleInitializers.end())
929 return;
930
931 // Maybe the ImportDecl only imports another ImportDecl.
932 auto &Imported = *It->second;
933 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
934 Imported.resolve(*this);
935 auto *OnlyDecl = Imported.Initializers.front();
936 if (isa<ImportDecl>(OnlyDecl))
937 D = OnlyDecl;
938 }
939 }
940
941 auto *&Inits = ModuleInitializers[M];
942 if (!Inits)
943 Inits = new (*this) PerModuleInitializers;
944 Inits->Initializers.push_back(D);
945}
946
947void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
948 auto *&Inits = ModuleInitializers[M];
949 if (!Inits)
950 Inits = new (*this) PerModuleInitializers;
951 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
952 IDs.begin(), IDs.end());
953}
954
955ArrayRef<Decl*> ASTContext::getModuleInitializers(Module *M) {
956 auto It = ModuleInitializers.find(M);
957 if (It == ModuleInitializers.end())
958 return None;
959
960 auto *Inits = It->second;
961 Inits->resolve(*this);
962 return Inits->Initializers;
963}
964
Richard Smithf19e1272015-03-07 00:04:49 +0000965ExternCContextDecl *ASTContext::getExternCContextDecl() const {
966 if (!ExternCContext)
967 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
968
969 return ExternCContext;
970}
971
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000972BuiltinTemplateDecl *
973ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
974 const IdentifierInfo *II) const {
975 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
976 BuiltinTemplate->setImplicit();
977 TUDecl->addDecl(BuiltinTemplate);
978
979 return BuiltinTemplate;
980}
981
982BuiltinTemplateDecl *
983ASTContext::getMakeIntegerSeqDecl() const {
984 if (!MakeIntegerSeqDecl)
985 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
986 getMakeIntegerSeqName());
987 return MakeIntegerSeqDecl;
988}
989
Eric Fiselier6ad68552016-07-01 01:24:09 +0000990BuiltinTemplateDecl *
991ASTContext::getTypePackElementDecl() const {
992 if (!TypePackElementDecl)
993 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
994 getTypePackElementName());
995 return TypePackElementDecl;
996}
997
Alp Toker2dea15b2013-12-17 01:22:38 +0000998RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
999 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001000 SourceLocation Loc;
1001 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00001002 if (getLangOpts().CPlusPlus)
1003 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1004 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001005 else
Alp Toker2dea15b2013-12-17 01:22:38 +00001006 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1007 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001008 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +00001009 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1010 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +00001011 return NewDecl;
1012}
1013
1014TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1015 StringRef Name) const {
1016 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1017 TypedefDecl *NewDecl = TypedefDecl::Create(
1018 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1019 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1020 NewDecl->setImplicit();
1021 return NewDecl;
1022}
1023
Douglas Gregor801c99d2011-08-12 06:49:56 +00001024TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001025 if (!Int128Decl)
1026 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001027 return Int128Decl;
1028}
1029
1030TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001031 if (!UInt128Decl)
1032 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001033 return UInt128Decl;
1034}
Chris Lattner4eb445d2007-01-26 01:27:23 +00001035
John McCall48f2d582009-10-23 23:03:21 +00001036void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +00001037 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +00001038 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +00001039 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001040}
1041
Artem Belevichb5bc9232015-09-22 17:23:22 +00001042void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1043 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001044 assert((!this->Target || this->Target == &Target) &&
1045 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +00001046 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +00001047
Douglas Gregore8bbc122011-09-02 00:18:52 +00001048 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +00001049 this->AuxTarget = AuxTarget;
1050
Douglas Gregore8bbc122011-09-02 00:18:52 +00001051 ABI.reset(createCXXABI(Target));
1052 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +00001053 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +00001054
Chris Lattner970e54e2006-11-12 00:37:36 +00001055 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +00001056 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +00001057
Chris Lattner970e54e2006-11-12 00:37:36 +00001058 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001059 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001060 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001061 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001062 InitBuiltinType(CharTy, BuiltinType::Char_S);
1063 else
1064 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001065 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001066 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1067 InitBuiltinType(ShortTy, BuiltinType::Short);
1068 InitBuiltinType(IntTy, BuiltinType::Int);
1069 InitBuiltinType(LongTy, BuiltinType::Long);
1070 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001071
Chris Lattner970e54e2006-11-12 00:37:36 +00001072 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001073 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1074 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1075 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1076 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1077 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001078
Chris Lattner970e54e2006-11-12 00:37:36 +00001079 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001080 InitBuiltinType(FloatTy, BuiltinType::Float);
1081 InitBuiltinType(DoubleTy, BuiltinType::Double);
1082 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001083
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001084 // GNU extension, __float128 for IEEE quadruple precision
1085 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1086
Chris Lattnerf122cef2009-04-30 02:43:43 +00001087 // GNU extension, 128-bit integers.
1088 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1089 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1090
Hans Wennborg0d81e012013-05-10 10:08:40 +00001091 // C++ 3.9.1p5
1092 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1093 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1094 else // -fshort-wchar makes wchar_t be unsigned.
1095 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1096 if (LangOpts.CPlusPlus && LangOpts.WChar)
1097 WideCharTy = WCharTy;
1098 else {
1099 // C99 (or C++ using -fno-wchar).
1100 WideCharTy = getFromTargetType(Target.getWCharType());
1101 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001102
James Molloy36365542012-05-04 10:55:22 +00001103 WIntTy = getFromTargetType(Target.getWIntType());
1104
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001105 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1106 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1107 else // C99
1108 Char16Ty = getFromTargetType(Target.getChar16Type());
1109
1110 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1111 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1112 else // C99
1113 Char32Ty = getFromTargetType(Target.getChar32Type());
1114
Douglas Gregor4619e432008-12-05 23:32:09 +00001115 // Placeholder type for type-dependent expressions whose type is
1116 // completely unknown. No code should ever check a type against
1117 // DependentTy and users should never see it; however, it is here to
1118 // help diagnose failures to properly check for type-dependent
1119 // expressions.
1120 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001121
John McCall36e7fe32010-10-12 00:20:44 +00001122 // Placeholder type for functions.
1123 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1124
John McCall0009fcc2011-04-26 20:42:42 +00001125 // Placeholder type for bound members.
1126 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1127
John McCall526ab472011-10-25 17:37:35 +00001128 // Placeholder type for pseudo-objects.
1129 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1130
John McCall31996342011-04-07 08:22:57 +00001131 // "any" type; useful for debugger-like clients.
1132 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1133
John McCall8a6b59a2011-10-17 18:09:15 +00001134 // Placeholder type for unbridged ARC casts.
1135 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1136
Eli Friedman34866c72012-08-31 00:14:07 +00001137 // Placeholder type for builtin functions.
1138 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1139
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001140 // Placeholder type for OMP array sections.
1141 if (LangOpts.OpenMP)
1142 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1143
Chris Lattner970e54e2006-11-12 00:37:36 +00001144 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001145 FloatComplexTy = getComplexType(FloatTy);
1146 DoubleComplexTy = getComplexType(DoubleTy);
1147 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001148 Float128ComplexTy = getComplexType(Float128Ty);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001149
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001150 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001151 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1152 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001153 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001154
Alexey Bader954ba212016-04-08 13:40:33 +00001155 if (LangOpts.OpenCL) {
1156#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1157 InitBuiltinType(SingletonId, BuiltinType::Id);
Alexey Baderb62f1442016-04-13 08:33:41 +00001158#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001159
Guy Benyei61054192013-02-07 10:55:47 +00001160 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001161 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001162 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1163 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1164 InitBuiltinType(OCLNDRangeTy, BuiltinType::OCLNDRange);
1165 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001166 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001167
1168 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001169 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1170 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001171
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001172 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001173
1174 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001175
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001176 // void * type
1177 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001178
1179 // nullptr type (C++0x 2.14.7)
1180 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001181
1182 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1183 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001184
1185 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001186 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001187}
1188
David Blaikie9c902b52011-09-25 23:23:43 +00001189DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001190 return SourceMgr.getDiagnostics();
1191}
1192
Douglas Gregor561eceb2010-08-30 16:49:28 +00001193AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1194 AttrVec *&Result = DeclAttrs[D];
1195 if (!Result) {
1196 void *Mem = Allocate(sizeof(AttrVec));
1197 Result = new (Mem) AttrVec;
1198 }
1199
1200 return *Result;
1201}
1202
1203/// \brief Erase the attributes corresponding to the given declaration.
1204void ASTContext::eraseDeclAttrs(const Decl *D) {
1205 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1206 if (Pos != DeclAttrs.end()) {
1207 Pos->second->~AttrVec();
1208 DeclAttrs.erase(Pos);
1209 }
1210}
1211
Larisse Voufo39a1e502013-08-06 01:03:05 +00001212// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001213MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001214ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001215 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001216 return getTemplateOrSpecializationInfo(Var)
1217 .dyn_cast<MemberSpecializationInfo *>();
1218}
1219
1220ASTContext::TemplateOrSpecializationInfo
1221ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1222 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1223 TemplateOrInstantiation.find(Var);
1224 if (Pos == TemplateOrInstantiation.end())
1225 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001226
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001227 return Pos->second;
1228}
1229
Mike Stump11289f42009-09-09 15:08:12 +00001230void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001231ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001232 TemplateSpecializationKind TSK,
1233 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001234 assert(Inst->isStaticDataMember() && "Not a static data member");
1235 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001236 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1237 Tmpl, TSK, PointOfInstantiation));
1238}
1239
1240void
1241ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1242 TemplateOrSpecializationInfo TSI) {
1243 assert(!TemplateOrInstantiation[Inst] &&
1244 "Already noted what the variable was instantiated from");
1245 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001246}
1247
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001248FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1249 const FunctionDecl *FD){
1250 assert(FD && "Specialization is 0");
1251 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001252 = ClassScopeSpecializationPattern.find(FD);
1253 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001254 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001255
1256 return Pos->second;
1257}
1258
1259void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1260 FunctionDecl *Pattern) {
1261 assert(FD && "Specialization is 0");
1262 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001263 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001264}
1265
John McCalle61f2ba2009-11-18 02:36:19 +00001266NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001267ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001268 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001269 = InstantiatedFromUsingDecl.find(UUD);
1270 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001271 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001272
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001273 return Pos->second;
1274}
1275
1276void
John McCallb96ec562009-12-04 22:46:56 +00001277ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1278 assert((isa<UsingDecl>(Pattern) ||
1279 isa<UnresolvedUsingValueDecl>(Pattern) ||
1280 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1281 "pattern decl is not a using decl");
1282 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1283 InstantiatedFromUsingDecl[Inst] = Pattern;
1284}
1285
1286UsingShadowDecl *
1287ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1288 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1289 = InstantiatedFromUsingShadowDecl.find(Inst);
1290 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001291 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001292
1293 return Pos->second;
1294}
1295
1296void
1297ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1298 UsingShadowDecl *Pattern) {
1299 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1300 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001301}
1302
Anders Carlsson5da84842009-09-01 04:26:58 +00001303FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1304 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1305 = InstantiatedFromUnnamedFieldDecl.find(Field);
1306 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001307 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001308
Anders Carlsson5da84842009-09-01 04:26:58 +00001309 return Pos->second;
1310}
1311
1312void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1313 FieldDecl *Tmpl) {
1314 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1315 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1316 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1317 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001318
Anders Carlsson5da84842009-09-01 04:26:58 +00001319 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1320}
1321
Douglas Gregor832940b2010-03-02 23:58:15 +00001322ASTContext::overridden_cxx_method_iterator
1323ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001324 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1325 OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001326 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001327 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001328 return Pos->second.begin();
1329}
1330
1331ASTContext::overridden_cxx_method_iterator
1332ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001333 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1334 OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001335 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001336 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001337 return Pos->second.end();
1338}
1339
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001340unsigned
1341ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001342 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1343 OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001344 if (Pos == OverriddenMethods.end())
1345 return 0;
Chandler Carruthb1bcd5d2016-06-11 04:45:38 +00001346 return Pos->second.size();
Clement Courbet8251ebf2016-06-10 11:54:43 +00001347}
1348
Clement Courbet6ecaec82016-07-05 07:49:31 +00001349ASTContext::overridden_method_range
1350ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1351 return overridden_method_range(overridden_methods_begin(Method),
1352 overridden_methods_end(Method));
1353}
1354
Douglas Gregor832940b2010-03-02 23:58:15 +00001355void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1356 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001357 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001358 OverriddenMethods[Method].push_back(Overridden);
1359}
1360
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001361void ASTContext::getOverriddenMethods(
1362 const NamedDecl *D,
1363 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001364 assert(D);
1365
1366 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001367 Overridden.append(overridden_methods_begin(CXXMethod),
1368 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001369 return;
1370 }
1371
1372 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1373 if (!Method)
1374 return;
1375
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001376 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1377 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001378 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001379}
1380
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001381void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1382 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1383 assert(!Import->isFromASTFile() && "Non-local import declaration");
1384 if (!FirstLocalImport) {
1385 FirstLocalImport = Import;
1386 LastLocalImport = Import;
1387 return;
1388 }
1389
1390 LastLocalImport->NextLocalImport = Import;
1391 LastLocalImport = Import;
1392}
1393
Chris Lattner53cfe802007-07-18 17:52:12 +00001394//===----------------------------------------------------------------------===//
1395// Type Sizing and Analysis
1396//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001397
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001398/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1399/// scalar floating point type.
1400const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001401 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001402 assert(BT && "Not a floating point type!");
1403 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001404 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001405 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001406 case BuiltinType::Float: return Target->getFloatFormat();
1407 case BuiltinType::Double: return Target->getDoubleFormat();
1408 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001409 case BuiltinType::Float128: return Target->getFloat128Format();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001410 }
1411}
1412
Rafael Espindola71eccb32013-08-08 19:53:46 +00001413CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001414 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001415
John McCall94268702010-10-08 18:24:19 +00001416 bool UseAlignAttrOnly = false;
1417 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1418 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001419
John McCall94268702010-10-08 18:24:19 +00001420 // __attribute__((aligned)) can increase or decrease alignment
1421 // *except* on a struct or struct member, where it only increases
1422 // alignment unless 'packed' is also specified.
1423 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001424 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001425 // ignore that possibility; Sema should diagnose it.
1426 if (isa<FieldDecl>(D)) {
1427 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1428 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1429 } else {
1430 UseAlignAttrOnly = true;
1431 }
1432 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001433 else if (isa<FieldDecl>(D))
1434 UseAlignAttrOnly =
1435 D->hasAttr<PackedAttr>() ||
1436 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001437
John McCall4e819612011-01-20 07:57:12 +00001438 // If we're using the align attribute only, just ignore everything
1439 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001440 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001441 // do nothing
1442
John McCall94268702010-10-08 18:24:19 +00001443 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001444 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001445 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001446 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001447 T = RT->getPointeeType();
1448 else
1449 T = getPointerType(RT->getPointeeType());
1450 }
Richard Smithf6d70302014-06-10 23:34:28 +00001451 QualType BaseT = getBaseElementType(T);
1452 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001453 // Adjust alignments of declarations with array type by the
1454 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001455 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001456 unsigned MinWidth = Target->getLargeArrayMinWidth();
1457 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001458 if (isa<VariableArrayType>(arrayType))
1459 Align = std::max(Align, Target->getLargeArrayAlign());
1460 else if (isa<ConstantArrayType>(arrayType) &&
1461 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1462 Align = std::max(Align, Target->getLargeArrayAlign());
1463 }
John McCall33ddac02011-01-19 10:06:00 +00001464 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001465 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001466 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001467 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001468 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1469 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001470 }
John McCall4e819612011-01-20 07:57:12 +00001471
1472 // Fields can be subject to extra alignment constraints, like if
1473 // the field is packed, the struct is packed, or the struct has a
1474 // a max-field-alignment constraint (#pragma pack). So calculate
1475 // the actual alignment of the field within the struct, and then
1476 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001477 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1478 const RecordDecl *Parent = Field->getParent();
1479 // We can only produce a sensible answer if the record is valid.
1480 if (!Parent->isInvalidDecl()) {
1481 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001482
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001483 // Start with the record's overall alignment.
1484 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001485
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001486 // Use the GCD of that and the offset within the record.
1487 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1488 if (Offset > 0) {
1489 // Alignment is always a power of 2, so the GCD will be a power of 2,
1490 // which means we get to do this crazy thing instead of Euclid's.
1491 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1492 if (LowBitOfOffset < FieldAlign)
1493 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1494 }
1495
1496 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001497 }
Charles Davis3fc51072010-02-23 04:52:00 +00001498 }
Chris Lattner68061312009-01-24 21:53:27 +00001499 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001500
Ken Dyckcc56c542011-01-15 18:38:59 +00001501 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001502}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001503
John McCallf1249922012-08-21 04:10:00 +00001504// getTypeInfoDataSizeInChars - Return the size of a type, in
1505// chars. If the type is a record, its data size is returned. This is
1506// the size of the memcpy that's performed when assigning this type
1507// using a trivial copy/move assignment operator.
1508std::pair<CharUnits, CharUnits>
1509ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1510 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1511
1512 // In C++, objects can sometimes be allocated into the tail padding
1513 // of a base-class subobject. We decide whether that's possible
1514 // during class layout, so here we can just trust the layout results.
1515 if (getLangOpts().CPlusPlus) {
1516 if (const RecordType *RT = T->getAs<RecordType>()) {
1517 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1518 sizeAndAlign.first = layout.getDataSize();
1519 }
1520 }
1521
1522 return sizeAndAlign;
1523}
1524
Richard Trieu04d2d942013-05-14 21:59:17 +00001525/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1526/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1527std::pair<CharUnits, CharUnits>
1528static getConstantArrayInfoInChars(const ASTContext &Context,
1529 const ConstantArrayType *CAT) {
1530 std::pair<CharUnits, CharUnits> EltInfo =
1531 Context.getTypeInfoInChars(CAT->getElementType());
1532 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001533 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1534 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001535 "Overflow in array type char size evaluation");
1536 uint64_t Width = EltInfo.first.getQuantity() * Size;
1537 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001538 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1539 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001540 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001541 return std::make_pair(CharUnits::fromQuantity(Width),
1542 CharUnits::fromQuantity(Align));
1543}
1544
John McCall87fe5d52010-05-20 01:18:31 +00001545std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001546ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001547 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1548 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001549 TypeInfo Info = getTypeInfo(T);
1550 return std::make_pair(toCharUnitsFromBits(Info.Width),
1551 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001552}
1553
1554std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001555ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001556 return getTypeInfoInChars(T.getTypePtr());
1557}
1558
David Majnemer34b57492014-07-30 01:30:47 +00001559bool ASTContext::isAlignmentRequired(const Type *T) const {
1560 return getTypeInfo(T).AlignIsRequired;
1561}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001562
David Majnemer34b57492014-07-30 01:30:47 +00001563bool ASTContext::isAlignmentRequired(QualType T) const {
1564 return isAlignmentRequired(T.getTypePtr());
1565}
1566
1567TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001568 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1569 if (I != MemoizedTypeInfo.end())
1570 return I->second;
1571
1572 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1573 TypeInfo TI = getTypeInfoImpl(T);
1574 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001575 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001576}
1577
1578/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1579/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001580///
1581/// FIXME: Pointers into different addr spaces could have different sizes and
1582/// alignment requirements: getPointerInfo should take an AddrSpace, this
1583/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001584TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1585 uint64_t Width = 0;
1586 unsigned Align = 8;
1587 bool AlignIsRequired = false;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001588 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001589#define TYPE(Class, Base)
1590#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001591#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001592#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001593#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1594 case Type::Class: \
1595 assert(!T->isDependentType() && "should not see dependent types here"); \
1596 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001597#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001598 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001599
Chris Lattner355332d2007-07-13 22:27:08 +00001600 case Type::FunctionNoProto:
1601 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001602 // GCC extension: alignof(function) = 32 bits
1603 Width = 0;
1604 Align = 32;
1605 break;
1606
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001607 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001608 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001609 Width = 0;
1610 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1611 break;
1612
Steve Naroff5c131802007-08-30 01:06:46 +00001613 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001614 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001615
David Majnemer34b57492014-07-30 01:30:47 +00001616 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001617 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001618 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001619 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001620 Width = EltInfo.Width * Size;
1621 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001622 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1623 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001624 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001625 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001626 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001627 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001628 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001629 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001630 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1631 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001632 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001633 // If the alignment is not a power of 2, round up to the next power of 2.
1634 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001635 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001636 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001637 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001638 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001639 // Adjust the alignment based on the target max.
1640 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1641 if (TargetVectorAlign && TargetVectorAlign < Align)
1642 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001643 break;
1644 }
Chris Lattner647fb222007-07-18 18:26:58 +00001645
Chris Lattner7570e9c2008-03-08 08:52:55 +00001646 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001647 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001648 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001649 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001650 // GCC extension: alignof(void) = 8 bits.
1651 Width = 0;
1652 Align = 8;
1653 break;
1654
Chris Lattner6a4f7452007-12-19 19:23:28 +00001655 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001656 Width = Target->getBoolWidth();
1657 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001658 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001659 case BuiltinType::Char_S:
1660 case BuiltinType::Char_U:
1661 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001662 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001663 Width = Target->getCharWidth();
1664 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001665 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001666 case BuiltinType::WChar_S:
1667 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001668 Width = Target->getWCharWidth();
1669 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001670 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001671 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001672 Width = Target->getChar16Width();
1673 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001674 break;
1675 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001676 Width = Target->getChar32Width();
1677 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001678 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001679 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001680 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001681 Width = Target->getShortWidth();
1682 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001683 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001684 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001685 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001686 Width = Target->getIntWidth();
1687 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001688 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001689 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001690 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001691 Width = Target->getLongWidth();
1692 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001693 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001694 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001695 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001696 Width = Target->getLongLongWidth();
1697 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001698 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001699 case BuiltinType::Int128:
1700 case BuiltinType::UInt128:
1701 Width = 128;
1702 Align = 128; // int128_t is 128-bit aligned on all targets.
1703 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001704 case BuiltinType::Half:
1705 Width = Target->getHalfWidth();
1706 Align = Target->getHalfAlign();
1707 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001708 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001709 Width = Target->getFloatWidth();
1710 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001711 break;
1712 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001713 Width = Target->getDoubleWidth();
1714 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001715 break;
1716 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001717 Width = Target->getLongDoubleWidth();
1718 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001719 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001720 case BuiltinType::Float128:
1721 Width = Target->getFloat128Width();
1722 Align = Target->getFloat128Align();
1723 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001724 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001725 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1726 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001727 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001728 case BuiltinType::ObjCId:
1729 case BuiltinType::ObjCClass:
1730 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001731 Width = Target->getPointerWidth(0);
1732 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001733 break;
Guy Benyei61054192013-02-07 10:55:47 +00001734 case BuiltinType::OCLSampler:
1735 // Samplers are modeled as integers.
1736 Width = Target->getIntWidth();
1737 Align = Target->getIntAlign();
1738 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001739 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001740 case BuiltinType::OCLClkEvent:
1741 case BuiltinType::OCLQueue:
1742 case BuiltinType::OCLNDRange:
1743 case BuiltinType::OCLReserveID:
Alexey Bader954ba212016-04-08 13:40:33 +00001744#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1745 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00001746#include "clang/Basic/OpenCLImageTypes.def"
Alexey Bader954ba212016-04-08 13:40:33 +00001747
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001748 // Currently these types are pointers to opaque types.
1749 Width = Target->getPointerWidth(0);
1750 Align = Target->getPointerAlign(0);
1751 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001752 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001753 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001754 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001755 Width = Target->getPointerWidth(0);
1756 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001757 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001758 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001759 unsigned AS = getTargetAddressSpace(
1760 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001761 Width = Target->getPointerWidth(AS);
1762 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001763 break;
1764 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001765 case Type::LValueReference:
1766 case Type::RValueReference: {
1767 // alignof and sizeof should never enter this code path here, so we go
1768 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001769 unsigned AS = getTargetAddressSpace(
1770 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001771 Width = Target->getPointerWidth(AS);
1772 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001773 break;
1774 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001775 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001776 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001777 Width = Target->getPointerWidth(AS);
1778 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001779 break;
1780 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001781 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001782 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001783 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001784 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001785 }
Chris Lattner647fb222007-07-18 18:26:58 +00001786 case Type::Complex: {
1787 // Complex types have the same alignment as their elements, but twice the
1788 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001789 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1790 Width = EltInfo.Width * 2;
1791 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001792 break;
1793 }
John McCall8b07ec22010-05-15 11:32:37 +00001794 case Type::ObjCObject:
1795 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001796 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001797 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001798 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001799 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001800 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001801 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001802 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001803 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001804 break;
1805 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001806 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001807 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001808 const TagType *TT = cast<TagType>(T);
1809
1810 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001811 Width = 8;
1812 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001813 break;
1814 }
Mike Stump11289f42009-09-09 15:08:12 +00001815
David Majnemer475b25e2015-01-21 10:54:38 +00001816 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1817 const EnumDecl *ED = ET->getDecl();
1818 TypeInfo Info =
1819 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1820 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1821 Info.Align = AttrAlign;
1822 Info.AlignIsRequired = true;
1823 }
1824 return Info;
1825 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001826
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001827 const RecordType *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001828 const RecordDecl *RD = RT->getDecl();
1829 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001830 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001831 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001832 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001833 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001834 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001835
Chris Lattner63d2b362009-10-22 05:17:15 +00001836 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001837 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1838 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001839
Richard Smith30482bc2011-02-20 03:19:35 +00001840 case Type::Auto: {
1841 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001842 assert(!A->getDeducedType().isNull() &&
1843 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001844 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001845 }
1846
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001847 case Type::Paren:
1848 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1849
Douglas Gregoref462e62009-04-30 17:32:17 +00001850 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001851 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001852 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001853 // If the typedef has an aligned attribute on it, it overrides any computed
1854 // alignment we have. This violates the GCC documentation (which says that
1855 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001856 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001857 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001858 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001859 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001860 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001861 AlignIsRequired = Info.AlignIsRequired;
1862 }
David Majnemer34b57492014-07-30 01:30:47 +00001863 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001864 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001865 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001866
Abramo Bagnara6150c882010-05-11 21:36:43 +00001867 case Type::Elaborated:
1868 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001869
John McCall81904512011-01-06 01:58:22 +00001870 case Type::Attributed:
1871 return getTypeInfo(
1872 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1873
Eli Friedman0dfb8892011-10-06 23:00:33 +00001874 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001875 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001876 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1877 Width = Info.Width;
1878 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001879
1880 // If the size of the type doesn't exceed the platform's max
1881 // atomic promotion width, make the size and alignment more
1882 // favorable to atomic operations:
1883 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1884 // Round the size up to a power of 2.
1885 if (!llvm::isPowerOf2_64(Width))
1886 Width = llvm::NextPowerOf2(Width);
1887
1888 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001889 Align = static_cast<unsigned>(Width);
1890 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001891 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00001892 break;
1893
1894 case Type::Pipe: {
1895 TypeInfo Info = getTypeInfo(cast<PipeType>(T)->getElementType());
1896 Width = Info.Width;
1897 Align = Info.Align;
1898 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001899
Douglas Gregoref462e62009-04-30 17:32:17 +00001900 }
Mike Stump11289f42009-09-09 15:08:12 +00001901
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001902 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001903 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001904}
1905
Alexey Bataev00396512015-07-02 03:40:19 +00001906unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1907 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1908 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1909 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1910 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1911 getTargetInfo().getABI() == "elfv1-qpx" &&
1912 T->isSpecificBuiltinType(BuiltinType::Double))
1913 SimdAlign = 256;
1914 return SimdAlign;
1915}
1916
Ken Dyckcc56c542011-01-15 18:38:59 +00001917/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1918CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1919 return CharUnits::fromQuantity(BitSize / getCharWidth());
1920}
1921
Ken Dyckb0fcc592011-02-11 01:54:29 +00001922/// toBits - Convert a size in characters to a size in characters.
1923int64_t ASTContext::toBits(CharUnits CharSize) const {
1924 return CharSize.getQuantity() * getCharWidth();
1925}
1926
Ken Dyck8c89d592009-12-22 14:23:30 +00001927/// getTypeSizeInChars - Return the size of the specified type, in characters.
1928/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001929CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001930 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001931}
Jay Foad39c79802011-01-12 09:06:06 +00001932CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001933 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001934}
1935
Ken Dycka6046ab2010-01-26 17:25:18 +00001936/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001937/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001938CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001939 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001940}
Jay Foad39c79802011-01-12 09:06:06 +00001941CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001942 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001943}
1944
Chris Lattnera3402cd2009-01-27 18:08:34 +00001945/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1946/// type for the current target in bits. This can be different than the ABI
1947/// alignment in cases where it is beneficial for performance to overalign
1948/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001949unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00001950 TypeInfo TI = getTypeInfo(T);
1951 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00001952
David Majnemere1544562015-04-24 01:25:05 +00001953 T = T->getBaseElementTypeUnsafe();
1954
1955 // The preferred alignment of member pointers is that of a pointer.
1956 if (T->isMemberPointerType())
1957 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
1958
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00001959 if (!Target->allowsLargerPreferedTypeAlignment())
1960 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001961
Eli Friedman7ab09572009-05-25 21:27:19 +00001962 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00001963 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001964 T = CT->getElementType().getTypePtr();
David Majnemer475b25e2015-01-21 10:54:38 +00001965 if (const EnumType *ET = T->getAs<EnumType>())
1966 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00001967 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001968 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1969 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00001970 // Don't increase the alignment if an alignment attribute was specified on a
1971 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00001972 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00001973 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00001974
Chris Lattnera3402cd2009-01-27 18:08:34 +00001975 return ABIAlign;
1976}
1977
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00001978/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
1979/// for __attribute__((aligned)) on this target, to be used if no alignment
1980/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00001981unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00001982 return getTargetInfo().getDefaultAlignForAttributeAligned();
1983}
1984
Ulrich Weigandfa806422013-05-06 16:23:57 +00001985/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1986/// to a global variable of the specified type.
1987unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1988 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1989}
1990
1991/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1992/// should be given to a global variable of the specified type.
1993CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1994 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1995}
1996
David Majnemer08ef2ba2015-06-23 20:34:18 +00001997CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
1998 CharUnits Offset = CharUnits::Zero();
1999 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2000 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2001 Offset += Layout->getBaseClassOffset(Base);
2002 Layout = &getASTRecordLayout(Base);
2003 }
2004 return Offset;
2005}
2006
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002007/// DeepCollectObjCIvars -
2008/// This routine first collects all declared, but not synthesized, ivars in
2009/// super class and then collects all ivars, including those synthesized for
2010/// current class. This routine is used for implementation of current class
2011/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002012///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002013void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2014 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00002015 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002016 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2017 DeepCollectObjCIvars(SuperClass, false, Ivars);
2018 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00002019 for (const auto *I : OI->ivars())
2020 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002021 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002022 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00002023 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002024 Iv= Iv->getNextIvar())
2025 Ivars.push_back(Iv);
2026 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002027}
2028
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002029/// CollectInheritedProtocols - Collect all protocols in current class and
2030/// those inherited by it.
2031void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00002032 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002033 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002034 // We can use protocol_iterator here instead of
2035 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002036 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002037 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00002038 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002039
2040 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00002041 for (const auto *Cat : OI->visible_categories())
2042 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002043
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002044 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2045 while (SD) {
2046 CollectInheritedProtocols(SD, Protocols);
2047 SD = SD->getSuperClass();
2048 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002049 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002050 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002051 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002052 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002053 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002054 // Insert the protocol.
2055 if (!Protocols.insert(
2056 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2057 return;
2058
2059 for (auto *Proto : OP->protocols())
2060 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002061 }
2062}
2063
Jay Foad39c79802011-01-12 09:06:06 +00002064unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002065 unsigned count = 0;
2066 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002067 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002068 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002069
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002070 // Count ivar defined in this class's implementation. This
2071 // includes synthesized ivars.
2072 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002073 count += ImplDecl->ivar_size();
2074
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002075 return count;
2076}
2077
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002078bool ASTContext::isSentinelNullExpr(const Expr *E) {
2079 if (!E)
2080 return false;
2081
2082 // nullptr_t is always treated as null.
2083 if (E->getType()->isNullPtrType()) return true;
2084
2085 if (E->getType()->isAnyPointerType() &&
2086 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2087 Expr::NPC_ValueDependentIsNull))
2088 return true;
2089
2090 // Unfortunately, __null has type 'int'.
2091 if (isa<GNUNullExpr>(E)) return true;
2092
2093 return false;
2094}
2095
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002096/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
2097ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2098 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2099 I = ObjCImpls.find(D);
2100 if (I != ObjCImpls.end())
2101 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002102 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002103}
2104/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
2105ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2106 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2107 I = ObjCImpls.find(D);
2108 if (I != ObjCImpls.end())
2109 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002110 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002111}
2112
2113/// \brief Set the implementation of ObjCInterfaceDecl.
2114void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2115 ObjCImplementationDecl *ImplD) {
2116 assert(IFaceD && ImplD && "Passed null params");
2117 ObjCImpls[IFaceD] = ImplD;
2118}
2119/// \brief Set the implementation of ObjCCategoryDecl.
2120void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2121 ObjCCategoryImplDecl *ImplD) {
2122 assert(CatD && ImplD && "Passed null params");
2123 ObjCImpls[CatD] = ImplD;
2124}
2125
Chandler Carruth21c90602015-12-30 03:24:14 +00002126const ObjCMethodDecl *
2127ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2128 return ObjCMethodRedecls.lookup(MD);
2129}
2130
2131void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2132 const ObjCMethodDecl *Redecl) {
2133 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2134 ObjCMethodRedecls[MD] = Redecl;
2135}
2136
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002137const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2138 const NamedDecl *ND) const {
2139 if (const ObjCInterfaceDecl *ID =
2140 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002141 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002142 if (const ObjCCategoryDecl *CD =
2143 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002144 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002145 if (const ObjCImplDecl *IMD =
2146 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002147 return IMD->getClassInterface();
2148
Craig Topper36250ad2014-05-12 05:36:57 +00002149 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002150}
2151
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002152/// \brief Get the copy initialization expression of VarDecl,or NULL if
2153/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00002154Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002155 assert(VD && "Passed null params");
2156 assert(VD->hasAttr<BlocksAttr>() &&
2157 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00002158 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002159 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00002160 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002161}
2162
2163/// \brief Set the copy inialization expression of a block var decl.
2164void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2165 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002166 assert(VD->hasAttr<BlocksAttr>() &&
2167 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002168 BlockVarCopyInits[VD] = Init;
2169}
2170
John McCallbcd03502009-12-07 02:54:59 +00002171TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002172 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002173 if (!DataSize)
2174 DataSize = TypeLoc::getFullDataSizeForType(T);
2175 else
2176 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002177 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002178
John McCallbcd03502009-12-07 02:54:59 +00002179 TypeSourceInfo *TInfo =
2180 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2181 new (TInfo) TypeSourceInfo(T);
2182 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002183}
2184
John McCallbcd03502009-12-07 02:54:59 +00002185TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002186 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002187 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002188 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002189 return DI;
2190}
2191
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002192const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002193ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002194 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002195}
2196
2197const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002198ASTContext::getASTObjCImplementationLayout(
2199 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002200 return getObjCLayout(D->getClassInterface(), D);
2201}
2202
Chris Lattner983a8bb2007-07-13 22:13:22 +00002203//===----------------------------------------------------------------------===//
2204// Type creation/memoization methods
2205//===----------------------------------------------------------------------===//
2206
Jay Foad39c79802011-01-12 09:06:06 +00002207QualType
John McCall33ddac02011-01-19 10:06:00 +00002208ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2209 unsigned fastQuals = quals.getFastQualifiers();
2210 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002211
2212 // Check if we've already instantiated this type.
2213 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002214 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002215 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002216 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2217 assert(eq->getQualifiers() == quals);
2218 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002219 }
2220
John McCall33ddac02011-01-19 10:06:00 +00002221 // If the base type is not canonical, make the appropriate canonical type.
2222 QualType canon;
2223 if (!baseType->isCanonicalUnqualified()) {
2224 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002225 canonSplit.Quals.addConsistentQualifiers(quals);
2226 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002227
2228 // Re-find the insert position.
2229 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2230 }
2231
2232 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2233 ExtQualNodes.InsertNode(eq, insertPos);
2234 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002235}
2236
Jay Foad39c79802011-01-12 09:06:06 +00002237QualType
2238ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002239 QualType CanT = getCanonicalType(T);
2240 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002241 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002242
John McCall8ccfcb52009-09-24 19:53:00 +00002243 // If we are composing extended qualifiers together, merge together
2244 // into one ExtQuals node.
2245 QualifierCollector Quals;
2246 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002247
John McCall8ccfcb52009-09-24 19:53:00 +00002248 // If this type already has an address space specified, it cannot get
2249 // another one.
2250 assert(!Quals.hasAddressSpace() &&
2251 "Type cannot be in multiple addr spaces!");
2252 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002253
John McCall8ccfcb52009-09-24 19:53:00 +00002254 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002255}
2256
Chris Lattnerd60183d2009-02-18 22:53:11 +00002257QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002258 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002259 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002260 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002261 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002262
John McCall53fa7142010-12-24 02:08:15 +00002263 if (const PointerType *ptr = T->getAs<PointerType>()) {
2264 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002265 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002266 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2267 return getPointerType(ResultType);
2268 }
2269 }
Mike Stump11289f42009-09-09 15:08:12 +00002270
John McCall8ccfcb52009-09-24 19:53:00 +00002271 // If we are composing extended qualifiers together, merge together
2272 // into one ExtQuals node.
2273 QualifierCollector Quals;
2274 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002275
John McCall8ccfcb52009-09-24 19:53:00 +00002276 // If this type already has an ObjCGC specified, it cannot get
2277 // another one.
2278 assert(!Quals.hasObjCGCAttr() &&
2279 "Type cannot have multiple ObjCGCs!");
2280 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002281
John McCall8ccfcb52009-09-24 19:53:00 +00002282 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002283}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002284
John McCall4f5019e2010-12-19 02:44:49 +00002285const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2286 FunctionType::ExtInfo Info) {
2287 if (T->getExtInfo() == Info)
2288 return T;
2289
2290 QualType Result;
2291 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002292 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002293 } else {
2294 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2295 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2296 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002297 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002298 }
2299
2300 return cast<FunctionType>(Result.getTypePtr());
2301}
2302
Richard Smith2a7d4812013-05-04 07:00:32 +00002303void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2304 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002305 FD = FD->getMostRecentDecl();
2306 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002307 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2308 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002309 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002310 if (FunctionDecl *Next = FD->getPreviousDecl())
2311 FD = Next;
2312 else
2313 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002314 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002315 if (ASTMutationListener *L = getASTMutationListener())
2316 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002317}
2318
Richard Smith0b3a4622014-11-13 20:01:57 +00002319/// Get a function type and produce the equivalent function type with the
2320/// specified exception specification. Type sugar that can be present on a
2321/// declaration of a function with an exception specification is permitted
2322/// and preserved. Other type sugar (for instance, typedefs) is not.
2323static QualType getFunctionTypeWithExceptionSpec(
2324 ASTContext &Context, QualType Orig,
2325 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2326 // Might have some parens.
2327 if (auto *PT = dyn_cast<ParenType>(Orig))
2328 return Context.getParenType(
2329 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2330
2331 // Might have a calling-convention attribute.
2332 if (auto *AT = dyn_cast<AttributedType>(Orig))
2333 return Context.getAttributedType(
2334 AT->getAttrKind(),
2335 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2336 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2337 ESI));
2338
2339 // Anything else must be a function type. Rebuild it with the new exception
2340 // specification.
2341 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2342 return Context.getFunctionType(
2343 Proto->getReturnType(), Proto->getParamTypes(),
2344 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2345}
2346
2347void ASTContext::adjustExceptionSpec(
2348 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2349 bool AsWritten) {
2350 // Update the type.
2351 QualType Updated =
2352 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2353 FD->setType(Updated);
2354
2355 if (!AsWritten)
2356 return;
2357
2358 // Update the type in the type source information too.
2359 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2360 // If the type and the type-as-written differ, we may need to update
2361 // the type-as-written too.
2362 if (TSInfo->getType() != FD->getType())
2363 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2364
2365 // FIXME: When we get proper type location information for exceptions,
2366 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2367 // up the TypeSourceInfo;
2368 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2369 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2370 "TypeLoc size mismatch from updating exception specification");
2371 TSInfo->overrideType(Updated);
2372 }
2373}
2374
Chris Lattnerc6395932007-06-22 20:56:16 +00002375/// getComplexType - Return the uniqued reference to the type for a complex
2376/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002377QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002378 // Unique pointers, to guarantee there is only one pointer of a particular
2379 // structure.
2380 llvm::FoldingSetNodeID ID;
2381 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002382
Craig Topper36250ad2014-05-12 05:36:57 +00002383 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002384 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2385 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002386
Chris Lattnerc6395932007-06-22 20:56:16 +00002387 // If the pointee type isn't canonical, this won't be a canonical type either,
2388 // so fill in the canonical type field.
2389 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002390 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002391 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002392
Chris Lattnerc6395932007-06-22 20:56:16 +00002393 // Get the new insert position for the node we care about.
2394 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002395 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002396 }
John McCall90d1c2d2009-09-24 23:30:46 +00002397 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002398 Types.push_back(New);
2399 ComplexTypes.InsertNode(New, InsertPos);
2400 return QualType(New, 0);
2401}
2402
Chris Lattner970e54e2006-11-12 00:37:36 +00002403/// getPointerType - Return the uniqued reference to the type for a pointer to
2404/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002405QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002406 // Unique pointers, to guarantee there is only one pointer of a particular
2407 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002408 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002409 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002410
Craig Topper36250ad2014-05-12 05:36:57 +00002411 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002412 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002413 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002414
Chris Lattner7ccecb92006-11-12 08:50:50 +00002415 // If the pointee type isn't canonical, this won't be a canonical type either,
2416 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002417 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002418 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002419 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002420
Bob Wilsonc8541f22013-03-15 17:12:43 +00002421 // Get the new insert position for the node we care about.
2422 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002423 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002424 }
John McCall90d1c2d2009-09-24 23:30:46 +00002425 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002426 Types.push_back(New);
2427 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002428 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002429}
2430
Reid Kleckner0503a872013-12-05 01:23:43 +00002431QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2432 llvm::FoldingSetNodeID ID;
2433 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002434 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002435 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2436 if (AT)
2437 return QualType(AT, 0);
2438
2439 QualType Canonical = getCanonicalType(New);
2440
2441 // Get the new insert position for the node we care about.
2442 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002443 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002444
2445 AT = new (*this, TypeAlignment)
2446 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2447 Types.push_back(AT);
2448 AdjustedTypes.InsertNode(AT, InsertPos);
2449 return QualType(AT, 0);
2450}
2451
Reid Kleckner8a365022013-06-24 17:51:48 +00002452QualType ASTContext::getDecayedType(QualType T) const {
2453 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2454
Reid Kleckner8a365022013-06-24 17:51:48 +00002455 QualType Decayed;
2456
2457 // C99 6.7.5.3p7:
2458 // A declaration of a parameter as "array of type" shall be
2459 // adjusted to "qualified pointer to type", where the type
2460 // qualifiers (if any) are those specified within the [ and ] of
2461 // the array type derivation.
2462 if (T->isArrayType())
2463 Decayed = getArrayDecayedType(T);
2464
2465 // C99 6.7.5.3p8:
2466 // A declaration of a parameter as "function returning type"
2467 // shall be adjusted to "pointer to function returning type", as
2468 // in 6.3.2.1.
2469 if (T->isFunctionType())
2470 Decayed = getPointerType(T);
2471
Reid Kleckner0503a872013-12-05 01:23:43 +00002472 llvm::FoldingSetNodeID ID;
2473 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002474 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002475 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2476 if (AT)
2477 return QualType(AT, 0);
2478
Reid Kleckner8a365022013-06-24 17:51:48 +00002479 QualType Canonical = getCanonicalType(Decayed);
2480
2481 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002482 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002483 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002484
Reid Kleckner0503a872013-12-05 01:23:43 +00002485 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2486 Types.push_back(AT);
2487 AdjustedTypes.InsertNode(AT, InsertPos);
2488 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002489}
2490
Mike Stump11289f42009-09-09 15:08:12 +00002491/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002492/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002493QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002494 assert(T->isFunctionType() && "block of function types only");
2495 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002496 // structure.
2497 llvm::FoldingSetNodeID ID;
2498 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002499
Craig Topper36250ad2014-05-12 05:36:57 +00002500 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002501 if (BlockPointerType *PT =
2502 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2503 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002504
2505 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002506 // type either so fill in the canonical type field.
2507 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002508 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002509 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002510
Steve Naroffec33ed92008-08-27 16:04:49 +00002511 // Get the new insert position for the node we care about.
2512 BlockPointerType *NewIP =
2513 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002514 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002515 }
John McCall90d1c2d2009-09-24 23:30:46 +00002516 BlockPointerType *New
2517 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002518 Types.push_back(New);
2519 BlockPointerTypes.InsertNode(New, InsertPos);
2520 return QualType(New, 0);
2521}
2522
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002523/// getLValueReferenceType - Return the uniqued reference to the type for an
2524/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002525QualType
2526ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002527 assert(getCanonicalType(T) != OverloadTy &&
2528 "Unresolved overloaded function type");
2529
Bill Wendling3708c182007-05-27 10:15:43 +00002530 // Unique pointers, to guarantee there is only one pointer of a particular
2531 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002532 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002533 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002534
Craig Topper36250ad2014-05-12 05:36:57 +00002535 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002536 if (LValueReferenceType *RT =
2537 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002538 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002539
John McCallfc93cf92009-10-22 22:37:11 +00002540 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2541
Bill Wendling3708c182007-05-27 10:15:43 +00002542 // If the referencee type isn't canonical, this won't be a canonical type
2543 // either, so fill in the canonical type field.
2544 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002545 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2546 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2547 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002548
Bill Wendling3708c182007-05-27 10:15:43 +00002549 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002550 LValueReferenceType *NewIP =
2551 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002552 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002553 }
2554
John McCall90d1c2d2009-09-24 23:30:46 +00002555 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002556 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2557 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002558 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002559 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002560
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002561 return QualType(New, 0);
2562}
2563
2564/// getRValueReferenceType - Return the uniqued reference to the type for an
2565/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002566QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002567 // Unique pointers, to guarantee there is only one pointer of a particular
2568 // structure.
2569 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002570 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002571
Craig Topper36250ad2014-05-12 05:36:57 +00002572 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002573 if (RValueReferenceType *RT =
2574 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2575 return QualType(RT, 0);
2576
John McCallfc93cf92009-10-22 22:37:11 +00002577 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2578
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002579 // If the referencee type isn't canonical, this won't be a canonical type
2580 // either, so fill in the canonical type field.
2581 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002582 if (InnerRef || !T.isCanonical()) {
2583 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2584 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002585
2586 // Get the new insert position for the node we care about.
2587 RValueReferenceType *NewIP =
2588 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002589 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002590 }
2591
John McCall90d1c2d2009-09-24 23:30:46 +00002592 RValueReferenceType *New
2593 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002594 Types.push_back(New);
2595 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002596 return QualType(New, 0);
2597}
2598
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002599/// getMemberPointerType - Return the uniqued reference to the type for a
2600/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002601QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002602 // Unique pointers, to guarantee there is only one pointer of a particular
2603 // structure.
2604 llvm::FoldingSetNodeID ID;
2605 MemberPointerType::Profile(ID, T, Cls);
2606
Craig Topper36250ad2014-05-12 05:36:57 +00002607 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002608 if (MemberPointerType *PT =
2609 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2610 return QualType(PT, 0);
2611
2612 // If the pointee or class type isn't canonical, this won't be a canonical
2613 // type either, so fill in the canonical type field.
2614 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002615 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002616 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2617
2618 // Get the new insert position for the node we care about.
2619 MemberPointerType *NewIP =
2620 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002621 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002622 }
John McCall90d1c2d2009-09-24 23:30:46 +00002623 MemberPointerType *New
2624 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002625 Types.push_back(New);
2626 MemberPointerTypes.InsertNode(New, InsertPos);
2627 return QualType(New, 0);
2628}
2629
Mike Stump11289f42009-09-09 15:08:12 +00002630/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002631/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002632QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002633 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002634 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002635 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002636 assert((EltTy->isDependentType() ||
2637 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002638 "Constant array of VLAs is illegal!");
2639
Chris Lattnere2df3f92009-05-13 04:12:56 +00002640 // Convert the array size into a canonical width matching the pointer size for
2641 // the target.
2642 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002643 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002644 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002645
Chris Lattner23b7eb62007-06-15 23:05:46 +00002646 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002647 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002648
Craig Topper36250ad2014-05-12 05:36:57 +00002649 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002650 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002651 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002652 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002653
John McCall33ddac02011-01-19 10:06:00 +00002654 // If the element type isn't canonical or has qualifiers, this won't
2655 // be a canonical type either, so fill in the canonical type field.
2656 QualType Canon;
2657 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2658 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002659 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002660 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002661 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002662
Chris Lattner36f8e652007-01-27 08:31:04 +00002663 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002664 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002665 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002666 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002667 }
Mike Stump11289f42009-09-09 15:08:12 +00002668
John McCall90d1c2d2009-09-24 23:30:46 +00002669 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002670 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002671 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002672 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002673 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002674}
2675
John McCall06549462011-01-18 08:40:38 +00002676/// getVariableArrayDecayedType - Turns the given type, which may be
2677/// variably-modified, into the corresponding type with all the known
2678/// sizes replaced with [*].
2679QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2680 // Vastly most common case.
2681 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002682
John McCall06549462011-01-18 08:40:38 +00002683 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002684
John McCall06549462011-01-18 08:40:38 +00002685 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002686 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002687 switch (ty->getTypeClass()) {
2688#define TYPE(Class, Base)
2689#define ABSTRACT_TYPE(Class, Base)
2690#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2691#include "clang/AST/TypeNodes.def"
2692 llvm_unreachable("didn't desugar past all non-canonical types?");
2693
2694 // These types should never be variably-modified.
2695 case Type::Builtin:
2696 case Type::Complex:
2697 case Type::Vector:
2698 case Type::ExtVector:
2699 case Type::DependentSizedExtVector:
2700 case Type::ObjCObject:
2701 case Type::ObjCInterface:
2702 case Type::ObjCObjectPointer:
2703 case Type::Record:
2704 case Type::Enum:
2705 case Type::UnresolvedUsing:
2706 case Type::TypeOfExpr:
2707 case Type::TypeOf:
2708 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002709 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002710 case Type::DependentName:
2711 case Type::InjectedClassName:
2712 case Type::TemplateSpecialization:
2713 case Type::DependentTemplateSpecialization:
2714 case Type::TemplateTypeParm:
2715 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002716 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002717 case Type::PackExpansion:
2718 llvm_unreachable("type should never be variably-modified");
2719
2720 // These types can be variably-modified but should never need to
2721 // further decay.
2722 case Type::FunctionNoProto:
2723 case Type::FunctionProto:
2724 case Type::BlockPointer:
2725 case Type::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00002726 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00002727 return type;
2728
2729 // These types can be variably-modified. All these modifications
2730 // preserve structure except as noted by comments.
2731 // TODO: if we ever care about optimizing VLAs, there are no-op
2732 // optimizations available here.
2733 case Type::Pointer:
2734 result = getPointerType(getVariableArrayDecayedType(
2735 cast<PointerType>(ty)->getPointeeType()));
2736 break;
2737
2738 case Type::LValueReference: {
2739 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2740 result = getLValueReferenceType(
2741 getVariableArrayDecayedType(lv->getPointeeType()),
2742 lv->isSpelledAsLValue());
2743 break;
2744 }
2745
2746 case Type::RValueReference: {
2747 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2748 result = getRValueReferenceType(
2749 getVariableArrayDecayedType(lv->getPointeeType()));
2750 break;
2751 }
2752
Eli Friedman0dfb8892011-10-06 23:00:33 +00002753 case Type::Atomic: {
2754 const AtomicType *at = cast<AtomicType>(ty);
2755 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2756 break;
2757 }
2758
John McCall06549462011-01-18 08:40:38 +00002759 case Type::ConstantArray: {
2760 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2761 result = getConstantArrayType(
2762 getVariableArrayDecayedType(cat->getElementType()),
2763 cat->getSize(),
2764 cat->getSizeModifier(),
2765 cat->getIndexTypeCVRQualifiers());
2766 break;
2767 }
2768
2769 case Type::DependentSizedArray: {
2770 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2771 result = getDependentSizedArrayType(
2772 getVariableArrayDecayedType(dat->getElementType()),
2773 dat->getSizeExpr(),
2774 dat->getSizeModifier(),
2775 dat->getIndexTypeCVRQualifiers(),
2776 dat->getBracketsRange());
2777 break;
2778 }
2779
2780 // Turn incomplete types into [*] types.
2781 case Type::IncompleteArray: {
2782 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2783 result = getVariableArrayType(
2784 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002785 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002786 ArrayType::Normal,
2787 iat->getIndexTypeCVRQualifiers(),
2788 SourceRange());
2789 break;
2790 }
2791
2792 // Turn VLA types into [*] types.
2793 case Type::VariableArray: {
2794 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2795 result = getVariableArrayType(
2796 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002797 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002798 ArrayType::Star,
2799 vat->getIndexTypeCVRQualifiers(),
2800 vat->getBracketsRange());
2801 break;
2802 }
2803 }
2804
2805 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002806 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002807}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002808
Steve Naroffcadebd02007-08-30 18:14:25 +00002809/// getVariableArrayType - Returns a non-unique reference to the type for a
2810/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002811QualType ASTContext::getVariableArrayType(QualType EltTy,
2812 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002813 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002814 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002815 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002816 // Since we don't unique expressions, it isn't possible to unique VLA's
2817 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002818 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002819
John McCall33ddac02011-01-19 10:06:00 +00002820 // Be sure to pull qualifiers off the element type.
2821 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2822 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002823 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002824 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002825 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002826 }
2827
John McCall90d1c2d2009-09-24 23:30:46 +00002828 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002829 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002830
2831 VariableArrayTypes.push_back(New);
2832 Types.push_back(New);
2833 return QualType(New, 0);
2834}
2835
Douglas Gregor4619e432008-12-05 23:32:09 +00002836/// getDependentSizedArrayType - Returns a non-unique reference to
2837/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002838/// type.
John McCall33ddac02011-01-19 10:06:00 +00002839QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2840 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002841 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002842 unsigned elementTypeQuals,
2843 SourceRange brackets) const {
2844 assert((!numElements || numElements->isTypeDependent() ||
2845 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002846 "Size must be type- or value-dependent!");
2847
John McCall33ddac02011-01-19 10:06:00 +00002848 // Dependently-sized array types that do not have a specified number
2849 // of elements will have their sizes deduced from a dependent
2850 // initializer. We do no canonicalization here at all, which is okay
2851 // because they can't be used in most locations.
2852 if (!numElements) {
2853 DependentSizedArrayType *newType
2854 = new (*this, TypeAlignment)
2855 DependentSizedArrayType(*this, elementType, QualType(),
2856 numElements, ASM, elementTypeQuals,
2857 brackets);
2858 Types.push_back(newType);
2859 return QualType(newType, 0);
2860 }
2861
2862 // Otherwise, we actually build a new type every time, but we
2863 // also build a canonical type.
2864
2865 SplitQualType canonElementType = getCanonicalType(elementType).split();
2866
Craig Topper36250ad2014-05-12 05:36:57 +00002867 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002868 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002869 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002870 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002871 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002872
John McCall33ddac02011-01-19 10:06:00 +00002873 // Look for an existing type with these properties.
2874 DependentSizedArrayType *canonTy =
2875 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002876
John McCall33ddac02011-01-19 10:06:00 +00002877 // If we don't have one, build one.
2878 if (!canonTy) {
2879 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002880 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002881 QualType(), numElements, ASM, elementTypeQuals,
2882 brackets);
2883 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2884 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002885 }
2886
John McCall33ddac02011-01-19 10:06:00 +00002887 // Apply qualifiers from the element type to the array.
2888 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002889 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002890
David Majnemer16a74702015-07-24 05:54:19 +00002891 // If we didn't need extra canonicalization for the element type or the size
2892 // expression, then just use that as our result.
2893 if (QualType(canonElementType.Ty, 0) == elementType &&
2894 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00002895 return canon;
2896
2897 // Otherwise, we need to build a type which follows the spelling
2898 // of the element type.
2899 DependentSizedArrayType *sugaredType
2900 = new (*this, TypeAlignment)
2901 DependentSizedArrayType(*this, elementType, canon, numElements,
2902 ASM, elementTypeQuals, brackets);
2903 Types.push_back(sugaredType);
2904 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002905}
2906
John McCall33ddac02011-01-19 10:06:00 +00002907QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002908 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002909 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002910 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002911 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002912
Craig Topper36250ad2014-05-12 05:36:57 +00002913 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002914 if (IncompleteArrayType *iat =
2915 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2916 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002917
2918 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002919 // either, so fill in the canonical type field. We also have to pull
2920 // qualifiers off the element type.
2921 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002922
John McCall33ddac02011-01-19 10:06:00 +00002923 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2924 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002925 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002926 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002927 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002928
2929 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002930 IncompleteArrayType *existing =
2931 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2932 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002933 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002934
John McCall33ddac02011-01-19 10:06:00 +00002935 IncompleteArrayType *newType = new (*this, TypeAlignment)
2936 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002937
John McCall33ddac02011-01-19 10:06:00 +00002938 IncompleteArrayTypes.InsertNode(newType, insertPos);
2939 Types.push_back(newType);
2940 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002941}
2942
Steve Naroff91fcddb2007-07-18 18:00:27 +00002943/// getVectorType - Return the unique reference to a vector type of
2944/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002945QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002946 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002947 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002948
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002949 // Check if we've already instantiated a vector of this type.
2950 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002951 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002952
Craig Topper36250ad2014-05-12 05:36:57 +00002953 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002954 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2955 return QualType(VTP, 0);
2956
2957 // If the element type isn't canonical, this won't be a canonical type either,
2958 // so fill in the canonical type field.
2959 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002960 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002961 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002962
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002963 // Get the new insert position for the node we care about.
2964 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002965 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002966 }
John McCall90d1c2d2009-09-24 23:30:46 +00002967 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002968 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002969 VectorTypes.InsertNode(New, InsertPos);
2970 Types.push_back(New);
2971 return QualType(New, 0);
2972}
2973
Nate Begemance4d7fc2008-04-18 23:10:10 +00002974/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002975/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002976QualType
2977ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002978 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002979
Steve Naroff91fcddb2007-07-18 18:00:27 +00002980 // Check if we've already instantiated a vector of this type.
2981 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002982 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002983 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00002984 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002985 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2986 return QualType(VTP, 0);
2987
2988 // If the element type isn't canonical, this won't be a canonical type either,
2989 // so fill in the canonical type field.
2990 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002991 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002992 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002993
Steve Naroff91fcddb2007-07-18 18:00:27 +00002994 // Get the new insert position for the node we care about.
2995 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002996 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002997 }
John McCall90d1c2d2009-09-24 23:30:46 +00002998 ExtVectorType *New = new (*this, TypeAlignment)
2999 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00003000 VectorTypes.InsertNode(New, InsertPos);
3001 Types.push_back(New);
3002 return QualType(New, 0);
3003}
3004
Jay Foad39c79802011-01-12 09:06:06 +00003005QualType
3006ASTContext::getDependentSizedExtVectorType(QualType vecType,
3007 Expr *SizeExpr,
3008 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00003009 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003010 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00003011 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003012
Craig Topper36250ad2014-05-12 05:36:57 +00003013 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00003014 DependentSizedExtVectorType *Canon
3015 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3016 DependentSizedExtVectorType *New;
3017 if (Canon) {
3018 // We already have a canonical version of this array type; use it as
3019 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00003020 New = new (*this, TypeAlignment)
3021 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3022 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003023 } else {
3024 QualType CanonVecTy = getCanonicalType(vecType);
3025 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00003026 New = new (*this, TypeAlignment)
3027 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3028 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003029
3030 DependentSizedExtVectorType *CanonCheck
3031 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3032 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3033 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00003034 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3035 } else {
3036 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3037 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00003038 New = new (*this, TypeAlignment)
3039 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003040 }
3041 }
Mike Stump11289f42009-09-09 15:08:12 +00003042
Douglas Gregor758a8692009-06-17 21:51:59 +00003043 Types.push_back(New);
3044 return QualType(New, 0);
3045}
3046
John McCall18afab72016-03-01 00:49:02 +00003047/// \brief Determine whether \p T is canonical as the result type of a function.
3048static bool isCanonicalResultType(QualType T) {
3049 return T.isCanonical() &&
3050 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3051 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3052}
3053
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003054/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003055///
Jay Foad39c79802011-01-12 09:06:06 +00003056QualType
3057ASTContext::getFunctionNoProtoType(QualType ResultTy,
3058 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003059 // Unique functions, to guarantee there is only one function of a particular
3060 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003061 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003062 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00003063
Craig Topper36250ad2014-05-12 05:36:57 +00003064 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003065 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003066 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003067 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003068
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003069 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003070 if (!isCanonicalResultType(ResultTy)) {
3071 Canonical =
3072 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003073
Chris Lattner47955de2007-01-27 08:37:20 +00003074 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003075 FunctionNoProtoType *NewIP =
3076 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003077 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003078 }
Mike Stump11289f42009-09-09 15:08:12 +00003079
John McCall90d1c2d2009-09-24 23:30:46 +00003080 FunctionNoProtoType *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003081 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003082 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003083 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003084 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003085}
3086
Douglas Gregora602a152015-10-01 20:20:47 +00003087CanQualType
3088ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3089 CanQualType CanResultType = getCanonicalType(ResultType);
3090
3091 // Canonical result types do not have ARC lifetime qualifiers.
3092 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3093 Qualifiers Qs = CanResultType.getQualifiers();
3094 Qs.removeObjCLifetime();
3095 return CanQualType::CreateUnsafe(
3096 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3097 }
3098
3099 return CanResultType;
3100}
3101
Jay Foad39c79802011-01-12 09:06:06 +00003102QualType
Jordan Rose5c382722013-03-08 21:51:21 +00003103ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00003104 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003105 size_t NumArgs = ArgArray.size();
3106
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003107 // Unique functions, to guarantee there is only one function of a particular
3108 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003109 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00003110 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3111 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00003112
Craig Topper36250ad2014-05-12 05:36:57 +00003113 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003114 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003115 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003116 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003117
3118 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00003119 bool isCanonical =
Richard Smith8acb4282014-07-31 21:57:55 +00003120 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00003121 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003122 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003123 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003124 isCanonical = false;
3125
3126 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003127 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003128 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00003129 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003130 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003131 CanonicalArgs.reserve(NumArgs);
3132 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003133 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003134
John McCalldb40c7f2010-12-14 08:05:40 +00003135 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003136 CanonicalEPI.HasTrailingReturn = false;
Richard Smith8acb4282014-07-31 21:57:55 +00003137 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00003138
Douglas Gregora602a152015-10-01 20:20:47 +00003139 // Adjust the canonical function result type.
3140 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Jordan Rose5c382722013-03-08 21:51:21 +00003141 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003142
Chris Lattnerfd4de792007-01-27 01:15:32 +00003143 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003144 FunctionProtoType *NewIP =
3145 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003146 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003147 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003148
John McCall31168b02011-06-15 23:02:42 +00003149 // FunctionProtoType objects are allocated with extra bytes after
3150 // them for three variable size arrays at the end:
3151 // - parameter types
3152 // - exception types
John McCall18afab72016-03-01 00:49:02 +00003153 // - extended parameter information
John McCall31168b02011-06-15 23:02:42 +00003154 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003155 // expression, or information used to resolve the exception
3156 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00003157 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003158 NumArgs * sizeof(QualType);
John McCall18afab72016-03-01 00:49:02 +00003159
Richard Smith8acb4282014-07-31 21:57:55 +00003160 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3161 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3162 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00003163 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00003164 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00003165 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00003166 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003167 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003168 }
John McCall18afab72016-03-01 00:49:02 +00003169
3170 // Put the ExtParameterInfos last. If all were equal, it would make
3171 // more sense to put these before the exception specification, because
3172 // it's much easier to skip past them compared to the elaborate switch
3173 // required to skip the exception specification. However, all is not
3174 // equal; ExtParameterInfos are used to model very uncommon features,
3175 // and it's better not to burden the more common paths.
3176 if (EPI.ExtParameterInfos) {
3177 Size += NumArgs * sizeof(FunctionProtoType::ExtParameterInfo);
3178 }
John McCall31168b02011-06-15 23:02:42 +00003179
John McCalldb40c7f2010-12-14 08:05:40 +00003180 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003181 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003182 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003183 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003184 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003185 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003186}
Chris Lattneref51c202006-11-10 07:17:23 +00003187
Xiuli Pan9c14e282016-01-09 12:53:17 +00003188/// Return pipe type for the specified type.
3189QualType ASTContext::getPipeType(QualType T) const {
3190 llvm::FoldingSetNodeID ID;
3191 PipeType::Profile(ID, T);
3192
3193 void *InsertPos = 0;
3194 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
3195 return QualType(PT, 0);
3196
3197 // If the pipe element type isn't canonical, this won't be a canonical type
3198 // either, so fill in the canonical type field.
3199 QualType Canonical;
3200 if (!T.isCanonical()) {
3201 Canonical = getPipeType(getCanonicalType(T));
3202
3203 // Get the new insert position for the node we care about.
3204 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
3205 assert(!NewIP && "Shouldn't be in the map!");
3206 (void)NewIP;
3207 }
3208 PipeType *New = new (*this, TypeAlignment) PipeType(T, Canonical);
3209 Types.push_back(New);
3210 PipeTypes.InsertNode(New, InsertPos);
3211 return QualType(New, 0);
3212}
3213
John McCalle78aac42010-03-10 03:28:59 +00003214#ifndef NDEBUG
3215static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3216 if (!isa<CXXRecordDecl>(D)) return false;
3217 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3218 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3219 return true;
3220 if (RD->getDescribedClassTemplate() &&
3221 !isa<ClassTemplateSpecializationDecl>(RD))
3222 return true;
3223 return false;
3224}
3225#endif
3226
3227/// getInjectedClassNameType - Return the unique reference to the
3228/// injected class name type for the specified templated declaration.
3229QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003230 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003231 assert(NeedsInjectedClassNameType(Decl));
3232 if (Decl->TypeForDecl) {
3233 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003234 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003235 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3236 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3237 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3238 } else {
John McCall424cec92011-01-19 06:33:43 +00003239 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003240 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003241 Decl->TypeForDecl = newType;
3242 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003243 }
3244 return QualType(Decl->TypeForDecl, 0);
3245}
3246
Douglas Gregor83a586e2008-04-13 21:07:44 +00003247/// getTypeDeclType - Return the unique reference to the type for the
3248/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003249QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003250 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003251 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003252
Richard Smithdda56e42011-04-15 14:24:37 +00003253 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003254 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003255
John McCall96f0b5f2010-03-10 06:48:02 +00003256 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3257 "Template type parameter types are always available.");
3258
John McCall81e38502010-02-16 03:57:14 +00003259 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003260 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003261 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003262 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003263 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003264 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003265 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003266 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003267 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003268 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3269 Decl->TypeForDecl = newType;
3270 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003271 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003272 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003273
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003274 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003275}
3276
Chris Lattner32d920b2007-01-26 02:01:53 +00003277/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003278/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003279QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003280ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3281 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003282 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003283
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003284 if (Canonical.isNull())
3285 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003286 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003287 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003288 Decl->TypeForDecl = newType;
3289 Types.push_back(newType);
3290 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003291}
3292
Jay Foad39c79802011-01-12 09:06:06 +00003293QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003294 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3295
Douglas Gregorec9fd132012-01-14 16:38:05 +00003296 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003297 if (PrevDecl->TypeForDecl)
3298 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3299
John McCall424cec92011-01-19 06:33:43 +00003300 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3301 Decl->TypeForDecl = newType;
3302 Types.push_back(newType);
3303 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003304}
3305
Jay Foad39c79802011-01-12 09:06:06 +00003306QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003307 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3308
Douglas Gregorec9fd132012-01-14 16:38:05 +00003309 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003310 if (PrevDecl->TypeForDecl)
3311 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3312
John McCall424cec92011-01-19 06:33:43 +00003313 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3314 Decl->TypeForDecl = newType;
3315 Types.push_back(newType);
3316 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003317}
3318
John McCall81904512011-01-06 01:58:22 +00003319QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3320 QualType modifiedType,
3321 QualType equivalentType) {
3322 llvm::FoldingSetNodeID id;
3323 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3324
Craig Topper36250ad2014-05-12 05:36:57 +00003325 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003326 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3327 if (type) return QualType(type, 0);
3328
3329 QualType canon = getCanonicalType(equivalentType);
3330 type = new (*this, TypeAlignment)
3331 AttributedType(canon, attrKind, modifiedType, equivalentType);
3332
3333 Types.push_back(type);
3334 AttributedTypes.InsertNode(type, insertPos);
3335
3336 return QualType(type, 0);
3337}
3338
John McCallcebee162009-10-18 09:09:24 +00003339/// \brief Retrieve a substitution-result type.
3340QualType
3341ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003342 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003343 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003344 && "replacement types must always be canonical");
3345
3346 llvm::FoldingSetNodeID ID;
3347 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003348 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003349 SubstTemplateTypeParmType *SubstParm
3350 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3351
3352 if (!SubstParm) {
3353 SubstParm = new (*this, TypeAlignment)
3354 SubstTemplateTypeParmType(Parm, Replacement);
3355 Types.push_back(SubstParm);
3356 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3357 }
3358
3359 return QualType(SubstParm, 0);
3360}
3361
Douglas Gregorada4b792011-01-14 02:55:32 +00003362/// \brief Retrieve a
3363QualType ASTContext::getSubstTemplateTypeParmPackType(
3364 const TemplateTypeParmType *Parm,
3365 const TemplateArgument &ArgPack) {
3366#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003367 for (const auto &P : ArgPack.pack_elements()) {
3368 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3369 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003370 }
3371#endif
3372
3373 llvm::FoldingSetNodeID ID;
3374 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003375 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003376 if (SubstTemplateTypeParmPackType *SubstParm
3377 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3378 return QualType(SubstParm, 0);
3379
3380 QualType Canon;
3381 if (!Parm->isCanonicalUnqualified()) {
3382 Canon = getCanonicalType(QualType(Parm, 0));
3383 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3384 ArgPack);
3385 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3386 }
3387
3388 SubstTemplateTypeParmPackType *SubstParm
3389 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3390 ArgPack);
3391 Types.push_back(SubstParm);
3392 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3393 return QualType(SubstParm, 0);
3394}
3395
Douglas Gregoreff93e02009-02-05 23:33:38 +00003396/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003397/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003398/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003399QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003400 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003401 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003402 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003403 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003404 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003405 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003406 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3407
3408 if (TypeParm)
3409 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003410
Chandler Carruth08836322011-05-01 00:51:33 +00003411 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003412 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003413 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003414
3415 TemplateTypeParmType *TypeCheck
3416 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3417 assert(!TypeCheck && "Template type parameter canonical type broken");
3418 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003419 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003420 TypeParm = new (*this, TypeAlignment)
3421 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003422
3423 Types.push_back(TypeParm);
3424 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3425
3426 return QualType(TypeParm, 0);
3427}
3428
John McCalle78aac42010-03-10 03:28:59 +00003429TypeSourceInfo *
3430ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3431 SourceLocation NameLoc,
3432 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003433 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003434 assert(!Name.getAsDependentTemplateName() &&
3435 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003436 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003437
3438 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003439 TemplateSpecializationTypeLoc TL =
3440 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003441 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003442 TL.setTemplateNameLoc(NameLoc);
3443 TL.setLAngleLoc(Args.getLAngleLoc());
3444 TL.setRAngleLoc(Args.getRAngleLoc());
3445 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3446 TL.setArgLocInfo(i, Args[i].getLocInfo());
3447 return DI;
3448}
3449
Mike Stump11289f42009-09-09 15:08:12 +00003450QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003451ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003452 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003453 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003454 assert(!Template.getAsDependentTemplateName() &&
3455 "No dependent template names here!");
John McCall6b51f282009-11-23 01:53:49 +00003456
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003457 SmallVector<TemplateArgument, 4> ArgVec;
David Majnemer6fbeee32016-07-07 04:43:07 +00003458 ArgVec.reserve(Args.size());
3459 for (const TemplateArgumentLoc &Arg : Args.arguments())
3460 ArgVec.push_back(Arg.getArgument());
John McCall0ad16662009-10-29 08:12:44 +00003461
David Majnemer6fbeee32016-07-07 04:43:07 +00003462 return getTemplateSpecializationType(Template, ArgVec, Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003463}
3464
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003465#ifndef NDEBUG
David Majnemer6fbeee32016-07-07 04:43:07 +00003466static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
3467 for (const TemplateArgument &Arg : Args)
3468 if (Arg.isPackExpansion())
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003469 return true;
3470
3471 return true;
3472}
3473#endif
3474
John McCall0ad16662009-10-29 08:12:44 +00003475QualType
3476ASTContext::getTemplateSpecializationType(TemplateName Template,
David Majnemer6fbeee32016-07-07 04:43:07 +00003477 ArrayRef<TemplateArgument> Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003478 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003479 assert(!Template.getAsDependentTemplateName() &&
3480 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003481 // Look through qualified template names.
3482 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3483 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003484
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003485 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003486 Template.getAsTemplateDecl() &&
3487 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003488 QualType CanonType;
3489 if (!Underlying.isNull())
3490 CanonType = getCanonicalType(Underlying);
3491 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003492 // We can get here with an alias template when the specialization contains
3493 // a pack expansion that does not match up with a parameter pack.
David Majnemer6fbeee32016-07-07 04:43:07 +00003494 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003495 "Caller must compute aliased type");
3496 IsTypeAlias = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00003497 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003498 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003499
Douglas Gregora8e02e72009-07-28 23:00:59 +00003500 // Allocate the (non-canonical) template specialization type, but don't
3501 // try to unique it: these types typically have location information that
3502 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003503 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
David Majnemer6fbeee32016-07-07 04:43:07 +00003504 sizeof(TemplateArgument) * Args.size() +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003505 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003506 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003507 TemplateSpecializationType *Spec
David Majnemer6fbeee32016-07-07 04:43:07 +00003508 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003509 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003510
Douglas Gregor8bf42052009-02-09 18:46:07 +00003511 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003512 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003513}
3514
David Majnemer6fbeee32016-07-07 04:43:07 +00003515QualType ASTContext::getCanonicalTemplateSpecializationType(
3516 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003517 assert(!Template.getAsDependentTemplateName() &&
3518 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003519
Douglas Gregore29139c2011-03-03 17:04:51 +00003520 // Look through qualified template names.
3521 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3522 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003523
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003524 // Build the canonical template specialization type.
3525 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003526 SmallVector<TemplateArgument, 4> CanonArgs;
David Majnemer6fbeee32016-07-07 04:43:07 +00003527 unsigned NumArgs = Args.size();
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003528 CanonArgs.reserve(NumArgs);
David Majnemer6fbeee32016-07-07 04:43:07 +00003529 for (const TemplateArgument &Arg : Args)
3530 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003531
3532 // Determine whether this canonical template specialization type already
3533 // exists.
3534 llvm::FoldingSetNodeID ID;
3535 TemplateSpecializationType::Profile(ID, CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00003536 CanonArgs, *this);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003537
Craig Topper36250ad2014-05-12 05:36:57 +00003538 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003539 TemplateSpecializationType *Spec
3540 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3541
3542 if (!Spec) {
3543 // Allocate a new canonical template specialization type.
3544 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3545 sizeof(TemplateArgument) * NumArgs),
3546 TypeAlignment);
3547 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00003548 CanonArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003549 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003550 Types.push_back(Spec);
3551 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3552 }
3553
3554 assert(Spec->isDependentType() &&
3555 "Non-dependent template-id type must have a canonical type");
3556 return QualType(Spec, 0);
3557}
3558
3559QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003560ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3561 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003562 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003563 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003564 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003565
Craig Topper36250ad2014-05-12 05:36:57 +00003566 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003567 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003568 if (T)
3569 return QualType(T, 0);
3570
Douglas Gregorc42075a2010-02-04 18:10:26 +00003571 QualType Canon = NamedType;
3572 if (!Canon.isCanonical()) {
3573 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003574 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3575 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003576 (void)CheckT;
3577 }
3578
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003579 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003580 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003581 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003582 return QualType(T, 0);
3583}
3584
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003585QualType
Jay Foad39c79802011-01-12 09:06:06 +00003586ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003587 llvm::FoldingSetNodeID ID;
3588 ParenType::Profile(ID, InnerType);
3589
Craig Topper36250ad2014-05-12 05:36:57 +00003590 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003591 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3592 if (T)
3593 return QualType(T, 0);
3594
3595 QualType Canon = InnerType;
3596 if (!Canon.isCanonical()) {
3597 Canon = getCanonicalType(InnerType);
3598 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3599 assert(!CheckT && "Paren canonical type broken");
3600 (void)CheckT;
3601 }
3602
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003603 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003604 Types.push_back(T);
3605 ParenTypes.InsertNode(T, InsertPos);
3606 return QualType(T, 0);
3607}
3608
Douglas Gregor02085352010-03-31 20:19:30 +00003609QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3610 NestedNameSpecifier *NNS,
3611 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003612 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003613 if (Canon.isNull()) {
3614 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003615 ElaboratedTypeKeyword CanonKeyword = Keyword;
3616 if (Keyword == ETK_None)
3617 CanonKeyword = ETK_Typename;
3618
3619 if (CanonNNS != NNS || CanonKeyword != Keyword)
3620 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003621 }
3622
3623 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003624 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003625
Craig Topper36250ad2014-05-12 05:36:57 +00003626 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003627 DependentNameType *T
3628 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003629 if (T)
3630 return QualType(T, 0);
3631
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003632 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003633 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003634 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003635 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003636}
3637
Mike Stump11289f42009-09-09 15:08:12 +00003638QualType
John McCallc392f372010-06-11 00:33:02 +00003639ASTContext::getDependentTemplateSpecializationType(
3640 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003641 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003642 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003643 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003644 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003645 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003646 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3647 ArgCopy.push_back(Args[I].getArgument());
David Majnemer6fbeee32016-07-07 04:43:07 +00003648 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
John McCallc392f372010-06-11 00:33:02 +00003649}
3650
3651QualType
3652ASTContext::getDependentTemplateSpecializationType(
3653 ElaboratedTypeKeyword Keyword,
3654 NestedNameSpecifier *NNS,
3655 const IdentifierInfo *Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00003656 ArrayRef<TemplateArgument> Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003657 assert((!NNS || NNS->isDependent()) &&
3658 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003659
Douglas Gregorc42075a2010-02-04 18:10:26 +00003660 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003661 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003662 Name, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003663
Craig Topper36250ad2014-05-12 05:36:57 +00003664 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003665 DependentTemplateSpecializationType *T
3666 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003667 if (T)
3668 return QualType(T, 0);
3669
John McCallc392f372010-06-11 00:33:02 +00003670 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003671
John McCallc392f372010-06-11 00:33:02 +00003672 ElaboratedTypeKeyword CanonKeyword = Keyword;
3673 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3674
3675 bool AnyNonCanonArgs = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00003676 unsigned NumArgs = Args.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003677 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003678 for (unsigned I = 0; I != NumArgs; ++I) {
3679 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3680 if (!CanonArgs[I].structurallyEquals(Args[I]))
3681 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003682 }
3683
John McCallc392f372010-06-11 00:33:02 +00003684 QualType Canon;
3685 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3686 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003687 Name,
3688 CanonArgs);
John McCallc392f372010-06-11 00:33:02 +00003689
3690 // Find the insert position again.
3691 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3692 }
3693
3694 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3695 sizeof(TemplateArgument) * NumArgs),
3696 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003697 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003698 Name, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003699 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003700 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003701 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003702}
3703
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003704QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003705 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003706 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003707 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003708
3709 assert(Pattern->containsUnexpandedParameterPack() &&
3710 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003711 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003712 PackExpansionType *T
3713 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3714 if (T)
3715 return QualType(T, 0);
3716
3717 QualType Canon;
3718 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003719 Canon = getCanonicalType(Pattern);
3720 // The canonical type might not contain an unexpanded parameter pack, if it
3721 // contains an alias template specialization which ignores one of its
3722 // parameters.
3723 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003724 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003725
Richard Smith68eea502012-07-16 00:20:35 +00003726 // Find the insert position again, in case we inserted an element into
3727 // PackExpansionTypes and invalidated our insert position.
3728 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3729 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003730 }
3731
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003732 T = new (*this, TypeAlignment)
3733 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003734 Types.push_back(T);
3735 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003736 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003737}
3738
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003739/// CmpProtocolNames - Comparison predicate for sorting protocols
3740/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003741static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3742 ObjCProtocolDecl *const *RHS) {
3743 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003744}
3745
Craig Topper1f26d5b2016-01-03 19:43:23 +00003746static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
3747 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00003748
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003749 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3750 return false;
3751
Craig Topper1f26d5b2016-01-03 19:43:23 +00003752 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003753 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003754 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003755 return false;
3756 return true;
3757}
3758
Craig Topper6a8c1512015-10-22 01:56:18 +00003759static void
3760SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003761 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00003762 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003763
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003764 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00003765 for (ObjCProtocolDecl *&P : Protocols)
3766 P = P->getCanonicalDecl();
3767
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003768 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00003769 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
3770 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003771}
3772
John McCall8b07ec22010-05-15 11:32:37 +00003773QualType ASTContext::getObjCObjectType(QualType BaseType,
3774 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003775 unsigned NumProtocols) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003776 return getObjCObjectType(BaseType, { },
Douglas Gregorab209d82015-07-07 03:58:42 +00003777 llvm::makeArrayRef(Protocols, NumProtocols),
3778 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003779}
3780
3781QualType ASTContext::getObjCObjectType(
3782 QualType baseType,
3783 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003784 ArrayRef<ObjCProtocolDecl *> protocols,
3785 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003786 // If the base type is an interface and there aren't any protocols or
3787 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00003788 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
3789 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00003790 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00003791
3792 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003793 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00003794 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00003795 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003796 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3797 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003798
Douglas Gregore9d95f12015-07-07 03:57:35 +00003799 // Determine the type arguments to be used for canonicalization,
3800 // which may be explicitly specified here or written on the base
3801 // type.
3802 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
3803 if (effectiveTypeArgs.empty()) {
3804 if (auto baseObject = baseType->getAs<ObjCObjectType>())
3805 effectiveTypeArgs = baseObject->getTypeArgs();
3806 }
John McCallfc93cf92009-10-22 22:37:11 +00003807
Douglas Gregore9d95f12015-07-07 03:57:35 +00003808 // Build the canonical type, which has the canonical base type and a
3809 // sorted-and-uniqued list of protocols and the type arguments
3810 // canonicalized.
3811 QualType canonical;
3812 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
3813 effectiveTypeArgs.end(),
3814 [&](QualType type) {
3815 return type.isCanonical();
3816 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00003817 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003818 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
3819 // Determine the canonical type arguments.
3820 ArrayRef<QualType> canonTypeArgs;
3821 SmallVector<QualType, 4> canonTypeArgsVec;
3822 if (!typeArgsAreCanonical) {
3823 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
3824 for (auto typeArg : effectiveTypeArgs)
3825 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
3826 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00003827 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003828 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00003829 }
3830
Douglas Gregore9d95f12015-07-07 03:57:35 +00003831 ArrayRef<ObjCProtocolDecl *> canonProtocols;
3832 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
3833 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00003834 canonProtocolsVec.append(protocols.begin(), protocols.end());
3835 SortAndUniqueProtocols(canonProtocolsVec);
3836 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00003837 } else {
3838 canonProtocols = protocols;
3839 }
3840
3841 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003842 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003843
John McCallfc93cf92009-10-22 22:37:11 +00003844 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003845 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3846 }
3847
Douglas Gregore9d95f12015-07-07 03:57:35 +00003848 unsigned size = sizeof(ObjCObjectTypeImpl);
3849 size += typeArgs.size() * sizeof(QualType);
3850 size += protocols.size() * sizeof(ObjCProtocolDecl *);
3851 void *mem = Allocate(size, TypeAlignment);
John McCall8b07ec22010-05-15 11:32:37 +00003852 ObjCObjectTypeImpl *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00003853 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
3854 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00003855
3856 Types.push_back(T);
3857 ObjCObjectTypes.InsertNode(T, InsertPos);
3858 return QualType(T, 0);
3859}
3860
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003861/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3862/// protocol list adopt all protocols in QT's qualified-id protocol
3863/// list.
3864bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3865 ObjCInterfaceDecl *IC) {
3866 if (!QT->isObjCQualifiedIdType())
3867 return false;
3868
3869 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3870 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00003871 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003872 if (!IC->ClassImplementsProtocol(Proto, false))
3873 return false;
3874 }
3875 return true;
3876 }
3877 return false;
3878}
3879
3880/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3881/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3882/// of protocols.
3883bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3884 ObjCInterfaceDecl *IDecl) {
3885 if (!QT->isObjCQualifiedIdType())
3886 return false;
3887 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3888 if (!OPT)
3889 return false;
3890 if (!IDecl->hasDefinition())
3891 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003892 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3893 CollectInheritedProtocols(IDecl, InheritedProtocols);
3894 if (InheritedProtocols.empty())
3895 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003896 // Check that if every protocol in list of id<plist> conforms to a protcol
3897 // of IDecl's, then bridge casting is ok.
3898 bool Conforms = false;
3899 for (auto *Proto : OPT->quals()) {
3900 Conforms = false;
3901 for (auto *PI : InheritedProtocols) {
3902 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3903 Conforms = true;
3904 break;
3905 }
3906 }
3907 if (!Conforms)
3908 break;
3909 }
3910 if (Conforms)
3911 return true;
3912
Aaron Ballman83731462014-03-17 16:14:00 +00003913 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003914 // If both the right and left sides have qualifiers.
3915 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00003916 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003917 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00003918 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003919 break;
3920 }
3921 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003922 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003923 }
3924 return true;
3925}
3926
John McCall8b07ec22010-05-15 11:32:37 +00003927/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3928/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003929QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003930 llvm::FoldingSetNodeID ID;
3931 ObjCObjectPointerType::Profile(ID, ObjectT);
3932
Craig Topper36250ad2014-05-12 05:36:57 +00003933 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003934 if (ObjCObjectPointerType *QT =
3935 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3936 return QualType(QT, 0);
3937
3938 // Find the canonical object type.
3939 QualType Canonical;
3940 if (!ObjectT.isCanonical()) {
3941 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3942
3943 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003944 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3945 }
3946
Douglas Gregorf85bee62010-02-08 22:59:26 +00003947 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003948 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3949 ObjCObjectPointerType *QType =
3950 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003951
Steve Narofffb4330f2009-06-17 22:40:22 +00003952 Types.push_back(QType);
3953 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003954 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003955}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003956
Douglas Gregor1c283312010-08-11 12:19:30 +00003957/// getObjCInterfaceType - Return the unique reference to the type for the
3958/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003959QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3960 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003961 if (Decl->TypeForDecl)
3962 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003963
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003964 if (PrevDecl) {
3965 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3966 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3967 return QualType(PrevDecl->TypeForDecl, 0);
3968 }
3969
Douglas Gregor7671e532011-12-16 16:34:57 +00003970 // Prefer the definition, if there is one.
3971 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3972 Decl = Def;
3973
Douglas Gregor1c283312010-08-11 12:19:30 +00003974 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3975 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3976 Decl->TypeForDecl = T;
3977 Types.push_back(T);
3978 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003979}
3980
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003981/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3982/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003983/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003984/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003985/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003986QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003987 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003988 if (tofExpr->isTypeDependent()) {
3989 llvm::FoldingSetNodeID ID;
3990 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003991
Craig Topper36250ad2014-05-12 05:36:57 +00003992 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003993 DependentTypeOfExprType *Canon
3994 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3995 if (Canon) {
3996 // We already have a "canonical" version of an identical, dependent
3997 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003998 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003999 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00004000 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004001 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004002 Canon
4003 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004004 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4005 toe = Canon;
4006 }
4007 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00004008 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00004009 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00004010 }
Steve Naroffa773cd52007-08-01 18:02:17 +00004011 Types.push_back(toe);
4012 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004013}
4014
Steve Naroffa773cd52007-08-01 18:02:17 +00004015/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00004016/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00004017/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00004018/// an issue. This doesn't affect the type checker, since it operates
4019/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004020QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00004021 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00004022 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00004023 Types.push_back(tot);
4024 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004025}
4026
Richard Smith8eb1d322014-06-05 20:13:13 +00004027/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
4028/// nodes. This would never be helpful, since each such type has its own
4029/// expression, and would not give a significant memory saving, since there
4030/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00004031QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004032 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00004033
4034 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00004035 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00004036 // unique dependent type. Two such decltype-specifiers refer to the same
4037 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00004038 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004039 llvm::FoldingSetNodeID ID;
4040 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00004041
Craig Topper36250ad2014-05-12 05:36:57 +00004042 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00004043 DependentDecltypeType *Canon
4044 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00004045 if (!Canon) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004046 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004047 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004048 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004049 }
Richard Smith8eb1d322014-06-05 20:13:13 +00004050 dt = new (*this, TypeAlignment)
4051 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00004052 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00004053 dt = new (*this, TypeAlignment)
4054 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00004055 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00004056 Types.push_back(dt);
4057 return QualType(dt, 0);
4058}
4059
Alexis Hunte852b102011-05-24 22:41:36 +00004060/// getUnaryTransformationType - We don't unique these, since the memory
4061/// savings are minimal and these are rare.
4062QualType ASTContext::getUnaryTransformType(QualType BaseType,
4063 QualType UnderlyingType,
4064 UnaryTransformType::UTTKind Kind)
4065 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00004066 UnaryTransformType *ut = nullptr;
4067
4068 if (BaseType->isDependentType()) {
4069 // Look in the folding set for an existing type.
4070 llvm::FoldingSetNodeID ID;
4071 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4072
4073 void *InsertPos = nullptr;
4074 DependentUnaryTransformType *Canon
4075 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4076
4077 if (!Canon) {
4078 // Build a new, canonical __underlying_type(type) type.
4079 Canon = new (*this, TypeAlignment)
4080 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4081 Kind);
4082 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4083 }
4084 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4085 QualType(), Kind,
4086 QualType(Canon, 0));
4087 } else {
4088 QualType CanonType = getCanonicalType(UnderlyingType);
4089 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4090 UnderlyingType, Kind,
4091 CanonType);
4092 }
4093 Types.push_back(ut);
4094 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00004095}
4096
Richard Smith2a7d4812013-05-04 07:00:32 +00004097/// getAutoType - Return the uniqued reference to the 'auto' type which has been
4098/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4099/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00004100QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004101 bool IsDependent) const {
Richard Smithe301ba22015-11-11 02:02:15 +00004102 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00004103 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004104
Richard Smith2a7d4812013-05-04 07:00:32 +00004105 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00004106 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00004107 llvm::FoldingSetNodeID ID;
Richard Smithe301ba22015-11-11 02:02:15 +00004108 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00004109 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4110 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004111
Richard Smith74aeef52013-04-26 16:15:35 +00004112 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithe301ba22015-11-11 02:02:15 +00004113 Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004114 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004115 Types.push_back(AT);
4116 if (InsertPos)
4117 AutoTypes.InsertNode(AT, InsertPos);
4118 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004119}
4120
Eli Friedman0dfb8892011-10-06 23:00:33 +00004121/// getAtomicType - Return the uniqued reference to the atomic type for
4122/// the given value type.
4123QualType ASTContext::getAtomicType(QualType T) const {
4124 // Unique pointers, to guarantee there is only one pointer of a particular
4125 // structure.
4126 llvm::FoldingSetNodeID ID;
4127 AtomicType::Profile(ID, T);
4128
Craig Topper36250ad2014-05-12 05:36:57 +00004129 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004130 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4131 return QualType(AT, 0);
4132
4133 // If the atomic value type isn't canonical, this won't be a canonical type
4134 // either, so fill in the canonical type field.
4135 QualType Canonical;
4136 if (!T.isCanonical()) {
4137 Canonical = getAtomicType(getCanonicalType(T));
4138
4139 // Get the new insert position for the node we care about.
4140 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004141 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004142 }
4143 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4144 Types.push_back(New);
4145 AtomicTypes.InsertNode(New, InsertPos);
4146 return QualType(New, 0);
4147}
4148
Richard Smith02e85f32011-04-14 22:09:26 +00004149/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4150QualType ASTContext::getAutoDeductType() const {
4151 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004152 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00004153 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004154 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004155 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004156 return AutoDeductTy;
4157}
4158
4159/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4160QualType ASTContext::getAutoRRefDeductType() const {
4161 if (AutoRRefDeductTy.isNull())
4162 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4163 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4164 return AutoRRefDeductTy;
4165}
4166
Chris Lattnerfb072462007-01-23 05:45:31 +00004167/// getTagDeclType - Return the unique reference to the type for the
4168/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004169QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00004170 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004171 // FIXME: What is the design on getTagDeclType when it requires casting
4172 // away const? mutable?
4173 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004174}
4175
Mike Stump11289f42009-09-09 15:08:12 +00004176/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4177/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4178/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004179CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004180 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004181}
Chris Lattnerfb072462007-01-23 05:45:31 +00004182
Hans Wennborg27541db2011-10-27 08:29:09 +00004183/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4184CanQualType ASTContext::getIntMaxType() const {
4185 return getFromTargetType(Target->getIntMaxType());
4186}
4187
4188/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4189CanQualType ASTContext::getUIntMaxType() const {
4190 return getFromTargetType(Target->getUIntMaxType());
4191}
4192
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004193/// getSignedWCharType - Return the type of "signed wchar_t".
4194/// Used when in C++, as a GCC extension.
4195QualType ASTContext::getSignedWCharType() const {
4196 // FIXME: derive from "Target" ?
4197 return WCharTy;
4198}
4199
4200/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4201/// Used when in C++, as a GCC extension.
4202QualType ASTContext::getUnsignedWCharType() const {
4203 // FIXME: derive from "Target" ?
4204 return UnsignedIntTy;
4205}
4206
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004207QualType ASTContext::getIntPtrType() const {
4208 return getFromTargetType(Target->getIntPtrType());
4209}
4210
4211QualType ASTContext::getUIntPtrType() const {
4212 return getCorrespondingUnsignedType(getIntPtrType());
4213}
4214
Hans Wennborg27541db2011-10-27 08:29:09 +00004215/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004216/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4217QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004218 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004219}
4220
Eli Friedman4e91899e2012-11-27 02:58:24 +00004221/// \brief Return the unique type for "pid_t" defined in
4222/// <sys/types.h>. We need this to compute the correct type for vfork().
4223QualType ASTContext::getProcessIDType() const {
4224 return getFromTargetType(Target->getProcessIDType());
4225}
4226
Chris Lattnera21ad802008-04-02 05:18:44 +00004227//===----------------------------------------------------------------------===//
4228// Type Operators
4229//===----------------------------------------------------------------------===//
4230
Jay Foad39c79802011-01-12 09:06:06 +00004231CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004232 // Push qualifiers into arrays, and then discard any remaining
4233 // qualifiers.
4234 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004235 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004236 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004237 QualType Result;
4238 if (isa<ArrayType>(Ty)) {
4239 Result = getArrayDecayedType(QualType(Ty,0));
4240 } else if (isa<FunctionType>(Ty)) {
4241 Result = getPointerType(QualType(Ty, 0));
4242 } else {
4243 Result = QualType(Ty, 0);
4244 }
4245
4246 return CanQualType::CreateUnsafe(Result);
4247}
4248
John McCall6c9dd522011-01-18 07:41:22 +00004249QualType ASTContext::getUnqualifiedArrayType(QualType type,
4250 Qualifiers &quals) {
4251 SplitQualType splitType = type.getSplitUnqualifiedType();
4252
4253 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4254 // the unqualified desugared type and then drops it on the floor.
4255 // We then have to strip that sugar back off with
4256 // getUnqualifiedDesugaredType(), which is silly.
4257 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00004258 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004259
4260 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004261 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00004262 quals = splitType.Quals;
4263 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004264 }
4265
John McCall6c9dd522011-01-18 07:41:22 +00004266 // Otherwise, recurse on the array's element type.
4267 QualType elementType = AT->getElementType();
4268 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4269
4270 // If that didn't change the element type, AT has no qualifiers, so we
4271 // can just use the results in splitType.
4272 if (elementType == unqualElementType) {
4273 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004274 quals = splitType.Quals;
4275 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004276 }
4277
4278 // Otherwise, add in the qualifiers from the outermost type, then
4279 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004280 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004281
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004282 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004283 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004284 CAT->getSizeModifier(), 0);
4285 }
4286
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004287 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004288 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004289 }
4290
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004291 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004292 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004293 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004294 VAT->getSizeModifier(),
4295 VAT->getIndexTypeCVRQualifiers(),
4296 VAT->getBracketsRange());
4297 }
4298
4299 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004300 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004301 DSAT->getSizeModifier(), 0,
4302 SourceRange());
4303}
4304
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004305/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4306/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4307/// they point to and return true. If T1 and T2 aren't pointer types
4308/// or pointer-to-member types, or if they are not similar at this
4309/// level, returns false and leaves T1 and T2 unchanged. Top-level
4310/// qualifiers on T1 and T2 are ignored. This function will typically
4311/// be called in a loop that successively "unwraps" pointer and
4312/// pointer-to-member types to compare them at each level.
4313bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4314 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4315 *T2PtrType = T2->getAs<PointerType>();
4316 if (T1PtrType && T2PtrType) {
4317 T1 = T1PtrType->getPointeeType();
4318 T2 = T2PtrType->getPointeeType();
4319 return true;
4320 }
4321
4322 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4323 *T2MPType = T2->getAs<MemberPointerType>();
4324 if (T1MPType && T2MPType &&
4325 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4326 QualType(T2MPType->getClass(), 0))) {
4327 T1 = T1MPType->getPointeeType();
4328 T2 = T2MPType->getPointeeType();
4329 return true;
4330 }
4331
David Blaikiebbafb8a2012-03-11 07:00:24 +00004332 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004333 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4334 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4335 if (T1OPType && T2OPType) {
4336 T1 = T1OPType->getPointeeType();
4337 T2 = T2OPType->getPointeeType();
4338 return true;
4339 }
4340 }
4341
4342 // FIXME: Block pointers, too?
4343
4344 return false;
4345}
4346
Jay Foad39c79802011-01-12 09:06:06 +00004347DeclarationNameInfo
4348ASTContext::getNameForTemplate(TemplateName Name,
4349 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004350 switch (Name.getKind()) {
4351 case TemplateName::QualifiedTemplate:
4352 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004353 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004354 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4355 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004356
John McCalld9dfe3a2011-06-30 08:33:18 +00004357 case TemplateName::OverloadedTemplate: {
4358 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4359 // DNInfo work in progress: CHECKME: what about DNLoc?
4360 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4361 }
4362
4363 case TemplateName::DependentTemplate: {
4364 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004365 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004366 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004367 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4368 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004369 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004370 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4371 // DNInfo work in progress: FIXME: source locations?
4372 DeclarationNameLoc DNLoc;
4373 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4374 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4375 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004376 }
4377 }
4378
John McCalld9dfe3a2011-06-30 08:33:18 +00004379 case TemplateName::SubstTemplateTemplateParm: {
4380 SubstTemplateTemplateParmStorage *subst
4381 = Name.getAsSubstTemplateTemplateParm();
4382 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4383 NameLoc);
4384 }
4385
4386 case TemplateName::SubstTemplateTemplateParmPack: {
4387 SubstTemplateTemplateParmPackStorage *subst
4388 = Name.getAsSubstTemplateTemplateParmPack();
4389 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4390 NameLoc);
4391 }
4392 }
4393
4394 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004395}
4396
Jay Foad39c79802011-01-12 09:06:06 +00004397TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004398 switch (Name.getKind()) {
4399 case TemplateName::QualifiedTemplate:
4400 case TemplateName::Template: {
4401 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004402 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004403 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004404 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4405
4406 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004407 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004408 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004409
John McCalld9dfe3a2011-06-30 08:33:18 +00004410 case TemplateName::OverloadedTemplate:
4411 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004412
John McCalld9dfe3a2011-06-30 08:33:18 +00004413 case TemplateName::DependentTemplate: {
4414 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4415 assert(DTN && "Non-dependent template names must refer to template decls.");
4416 return DTN->CanonicalTemplateName;
4417 }
4418
4419 case TemplateName::SubstTemplateTemplateParm: {
4420 SubstTemplateTemplateParmStorage *subst
4421 = Name.getAsSubstTemplateTemplateParm();
4422 return getCanonicalTemplateName(subst->getReplacement());
4423 }
4424
4425 case TemplateName::SubstTemplateTemplateParmPack: {
4426 SubstTemplateTemplateParmPackStorage *subst
4427 = Name.getAsSubstTemplateTemplateParmPack();
4428 TemplateTemplateParmDecl *canonParameter
4429 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4430 TemplateArgument canonArgPack
4431 = getCanonicalTemplateArgument(subst->getArgumentPack());
4432 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4433 }
4434 }
4435
4436 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004437}
4438
Douglas Gregoradee3e32009-11-11 23:06:43 +00004439bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4440 X = getCanonicalTemplateName(X);
4441 Y = getCanonicalTemplateName(Y);
4442 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4443}
4444
Mike Stump11289f42009-09-09 15:08:12 +00004445TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004446ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004447 switch (Arg.getKind()) {
4448 case TemplateArgument::Null:
4449 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004450
Douglas Gregora8e02e72009-07-28 23:00:59 +00004451 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004452 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004453
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004454 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004455 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004456 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004457 }
Mike Stump11289f42009-09-09 15:08:12 +00004458
Eli Friedmanb826a002012-09-26 02:36:12 +00004459 case TemplateArgument::NullPtr:
4460 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4461 /*isNullPtr*/true);
4462
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004463 case TemplateArgument::Template:
4464 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004465
4466 case TemplateArgument::TemplateExpansion:
4467 return TemplateArgument(getCanonicalTemplateName(
4468 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004469 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004470
Douglas Gregora8e02e72009-07-28 23:00:59 +00004471 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004472 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004473
Douglas Gregora8e02e72009-07-28 23:00:59 +00004474 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004475 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004476
Douglas Gregora8e02e72009-07-28 23:00:59 +00004477 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004478 if (Arg.pack_size() == 0)
4479 return Arg;
4480
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004481 TemplateArgument *CanonArgs
4482 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004483 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004484 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004485 AEnd = Arg.pack_end();
4486 A != AEnd; (void)++A, ++Idx)
4487 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004488
Benjamin Kramercce63472015-08-05 09:40:22 +00004489 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00004490 }
4491 }
4492
4493 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004494 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004495}
4496
Douglas Gregor333489b2009-03-27 23:10:48 +00004497NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004498ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004499 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004500 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004501
4502 switch (NNS->getKind()) {
4503 case NestedNameSpecifier::Identifier:
4504 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004505 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004506 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4507 NNS->getAsIdentifier());
4508
4509 case NestedNameSpecifier::Namespace:
4510 // A namespace is canonical; build a nested-name-specifier with
4511 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004512 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004513 NNS->getAsNamespace()->getOriginalNamespace());
4514
4515 case NestedNameSpecifier::NamespaceAlias:
4516 // A namespace is canonical; build a nested-name-specifier with
4517 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004518 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004519 NNS->getAsNamespaceAlias()->getNamespace()
4520 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004521
4522 case NestedNameSpecifier::TypeSpec:
4523 case NestedNameSpecifier::TypeSpecWithTemplate: {
4524 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004525
4526 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4527 // break it apart into its prefix and identifier, then reconsititute those
4528 // as the canonical nested-name-specifier. This is required to canonicalize
4529 // a dependent nested-name-specifier involving typedefs of dependent-name
4530 // types, e.g.,
4531 // typedef typename T::type T1;
4532 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004533 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4534 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004535 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004536
Eli Friedman5358a0a2012-03-03 04:09:56 +00004537 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4538 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4539 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004540 return NestedNameSpecifier::Create(*this, nullptr, false,
4541 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004542 }
4543
4544 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004545 case NestedNameSpecifier::Super:
4546 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004547 return NNS;
4548 }
4549
David Blaikie8a40f702012-01-17 06:56:22 +00004550 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004551}
4552
Jay Foad39c79802011-01-12 09:06:06 +00004553const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004554 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004555 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004556 // Handle the common positive case fast.
4557 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4558 return AT;
4559 }
Mike Stump11289f42009-09-09 15:08:12 +00004560
John McCall8ccfcb52009-09-24 19:53:00 +00004561 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004562 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004563 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004564
John McCall8ccfcb52009-09-24 19:53:00 +00004565 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004566 // implements C99 6.7.3p8: "If the specification of an array type includes
4567 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004568
Chris Lattner7adf0762008-08-04 07:31:14 +00004569 // If we get here, we either have type qualifiers on the type, or we have
4570 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004571 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004572
John McCall33ddac02011-01-19 10:06:00 +00004573 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004574 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004575
Chris Lattner7adf0762008-08-04 07:31:14 +00004576 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004577 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004578 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004579 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004580
Chris Lattner7adf0762008-08-04 07:31:14 +00004581 // Otherwise, we have an array and we have qualifiers on it. Push the
4582 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004583 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004584
Chris Lattner7adf0762008-08-04 07:31:14 +00004585 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4586 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4587 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004588 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004589 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4590 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4591 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004592 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004593
Mike Stump11289f42009-09-09 15:08:12 +00004594 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004595 = dyn_cast<DependentSizedArrayType>(ATy))
4596 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004597 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004598 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004599 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004600 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004601 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004602
Chris Lattner7adf0762008-08-04 07:31:14 +00004603 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004604 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004605 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004606 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004607 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004608 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004609}
4610
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004611QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004612 if (T->isArrayType() || T->isFunctionType())
4613 return getDecayedType(T);
4614 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004615}
4616
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004617QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004618 T = getVariableArrayDecayedType(T);
4619 T = getAdjustedParameterType(T);
4620 return T.getUnqualifiedType();
4621}
4622
David Majnemerd09a51c2015-03-03 01:50:05 +00004623QualType ASTContext::getExceptionObjectType(QualType T) const {
4624 // C++ [except.throw]p3:
4625 // A throw-expression initializes a temporary object, called the exception
4626 // object, the type of which is determined by removing any top-level
4627 // cv-qualifiers from the static type of the operand of throw and adjusting
4628 // the type from "array of T" or "function returning T" to "pointer to T"
4629 // or "pointer to function returning T", [...]
4630 T = getVariableArrayDecayedType(T);
4631 if (T->isArrayType() || T->isFunctionType())
4632 T = getDecayedType(T);
4633 return T.getUnqualifiedType();
4634}
4635
Chris Lattnera21ad802008-04-02 05:18:44 +00004636/// getArrayDecayedType - Return the properly qualified result of decaying the
4637/// specified array type to a pointer. This operation is non-trivial when
4638/// handling typedefs etc. The canonical type of "T" must be an array type,
4639/// this returns a pointer to a properly qualified element of the array.
4640///
4641/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004642QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004643 // Get the element type with 'getAsArrayType' so that we don't lose any
4644 // typedefs in the element type of the array. This also handles propagation
4645 // of type qualifiers from the array type into the element type if present
4646 // (C99 6.7.3p8).
4647 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4648 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004649
Chris Lattner7adf0762008-08-04 07:31:14 +00004650 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004651
4652 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004653 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004654}
4655
John McCall33ddac02011-01-19 10:06:00 +00004656QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4657 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004658}
4659
John McCall33ddac02011-01-19 10:06:00 +00004660QualType ASTContext::getBaseElementType(QualType type) const {
4661 Qualifiers qs;
4662 while (true) {
4663 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004664 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004665 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004666
John McCall33ddac02011-01-19 10:06:00 +00004667 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004668 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004669 }
Mike Stump11289f42009-09-09 15:08:12 +00004670
John McCall33ddac02011-01-19 10:06:00 +00004671 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004672}
4673
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004674/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004675uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004676ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4677 uint64_t ElementCount = 1;
4678 do {
4679 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004680 CA = dyn_cast_or_null<ConstantArrayType>(
4681 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004682 } while (CA);
4683 return ElementCount;
4684}
4685
Steve Naroff0af91202007-04-27 21:51:21 +00004686/// getFloatingRank - Return a relative rank for floating point types.
4687/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004688static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004689 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004690 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004691
John McCall9dd450b2009-09-21 23:43:11 +00004692 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4693 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004694 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004695 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004696 case BuiltinType::Float: return FloatRank;
4697 case BuiltinType::Double: return DoubleRank;
4698 case BuiltinType::LongDouble: return LongDoubleRank;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004699 case BuiltinType::Float128: return Float128Rank;
Steve Naroffe4718892007-04-27 18:30:00 +00004700 }
4701}
4702
Mike Stump11289f42009-09-09 15:08:12 +00004703/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4704/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004705/// 'typeDomain' is a real floating point or complex type.
4706/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004707QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4708 QualType Domain) const {
4709 FloatingRank EltRank = getFloatingRank(Size);
4710 if (Domain->isComplexType()) {
4711 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004712 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004713 case FloatRank: return FloatComplexTy;
4714 case DoubleRank: return DoubleComplexTy;
4715 case LongDoubleRank: return LongDoubleComplexTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004716 case Float128Rank: return Float128ComplexTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004717 }
Steve Naroff0af91202007-04-27 21:51:21 +00004718 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004719
4720 assert(Domain->isRealFloatingType() && "Unknown domain!");
4721 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004722 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004723 case FloatRank: return FloatTy;
4724 case DoubleRank: return DoubleTy;
4725 case LongDoubleRank: return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004726 case Float128Rank: return Float128Ty;
Steve Naroff9091ef72007-08-27 01:27:54 +00004727 }
David Blaikief47fa302012-01-17 02:30:50 +00004728 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004729}
4730
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004731/// getFloatingTypeOrder - Compare the rank of the two specified floating
4732/// point types, ignoring the domain of the type (i.e. 'double' ==
4733/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004734/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004735int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004736 FloatingRank LHSR = getFloatingRank(LHS);
4737 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004738
Chris Lattnerb90739d2008-04-06 23:38:49 +00004739 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004740 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004741 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004742 return 1;
4743 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004744}
4745
Chris Lattner76a00cf2008-04-06 22:59:24 +00004746/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4747/// routine will assert if passed a built-in type that isn't an integer or enum,
4748/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004749unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004750 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004751
Chris Lattner76a00cf2008-04-06 22:59:24 +00004752 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004753 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004754 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004755 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004756 case BuiltinType::Char_S:
4757 case BuiltinType::Char_U:
4758 case BuiltinType::SChar:
4759 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004760 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004761 case BuiltinType::Short:
4762 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004763 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004764 case BuiltinType::Int:
4765 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004766 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004767 case BuiltinType::Long:
4768 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004769 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004770 case BuiltinType::LongLong:
4771 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004772 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004773 case BuiltinType::Int128:
4774 case BuiltinType::UInt128:
4775 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004776 }
4777}
4778
Eli Friedman629ffb92009-08-20 04:21:42 +00004779/// \brief Whether this is a promotable bitfield reference according
4780/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4781///
4782/// \returns the type this bit-field will promote to, or NULL if no
4783/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004784QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004785 if (E->isTypeDependent() || E->isValueDependent())
4786 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00004787
4788 // FIXME: We should not do this unless E->refersToBitField() is true. This
4789 // matters in C where getSourceBitField() will find bit-fields for various
4790 // cases where the source expression is not a bit-field designator.
4791
John McCalld25db7e2013-05-06 21:39:12 +00004792 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004793 if (!Field)
4794 return QualType();
4795
4796 QualType FT = Field->getType();
4797
Richard Smithcaf33902011-10-10 18:28:20 +00004798 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004799 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00004800 // C++ [conv.prom]p5:
4801 // A prvalue for an integral bit-field can be converted to a prvalue of type
4802 // int if int can represent all the values of the bit-field; otherwise, it
4803 // can be converted to unsigned int if unsigned int can represent all the
4804 // values of the bit-field. If the bit-field is larger yet, no integral
4805 // promotion applies to it.
4806 // C11 6.3.1.1/2:
4807 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4808 // If an int can represent all values of the original type (as restricted by
4809 // the width, for a bit-field), the value is converted to an int; otherwise,
4810 // it is converted to an unsigned int.
4811 //
4812 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4813 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00004814 if (BitWidth < IntSize)
4815 return IntTy;
4816
4817 if (BitWidth == IntSize)
4818 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4819
4820 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00004821 // like the base type. GCC has some weird bugs in this area that we
4822 // deliberately do not follow (GCC follows a pre-standard resolution to
4823 // C's DR315 which treats bit-width as being part of the type, and this leaks
4824 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00004825 return QualType();
4826}
4827
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004828/// getPromotedIntegerType - Returns the type that Promotable will
4829/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4830/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004831QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004832 assert(!Promotable.isNull());
4833 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004834 if (const EnumType *ET = Promotable->getAs<EnumType>())
4835 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004836
4837 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4838 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4839 // (3.9.1) can be converted to a prvalue of the first of the following
4840 // types that can represent all the values of its underlying type:
4841 // int, unsigned int, long int, unsigned long int, long long int, or
4842 // unsigned long long int [...]
4843 // FIXME: Is there some better way to compute this?
4844 if (BT->getKind() == BuiltinType::WChar_S ||
4845 BT->getKind() == BuiltinType::WChar_U ||
4846 BT->getKind() == BuiltinType::Char16 ||
4847 BT->getKind() == BuiltinType::Char32) {
4848 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4849 uint64_t FromSize = getTypeSize(BT);
4850 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4851 LongLongTy, UnsignedLongLongTy };
4852 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4853 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4854 if (FromSize < ToSize ||
4855 (FromSize == ToSize &&
4856 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4857 return PromoteTypes[Idx];
4858 }
4859 llvm_unreachable("char type should fit into long long");
4860 }
4861 }
4862
4863 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004864 if (Promotable->isSignedIntegerType())
4865 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004866 uint64_t PromotableSize = getIntWidth(Promotable);
4867 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004868 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4869 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4870}
4871
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004872/// \brief Recurses in pointer/array types until it finds an objc retainable
4873/// type and returns its ownership.
4874Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4875 while (!T.isNull()) {
4876 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4877 return T.getObjCLifetime();
4878 if (T->isArrayType())
4879 T = getBaseElementType(T);
4880 else if (const PointerType *PT = T->getAs<PointerType>())
4881 T = PT->getPointeeType();
4882 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004883 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004884 else
4885 break;
4886 }
4887
4888 return Qualifiers::OCL_None;
4889}
4890
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004891static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4892 // Incomplete enum types are not treated as integer types.
4893 // FIXME: In C++, enum types are never integer types.
4894 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4895 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00004896 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004897}
4898
Mike Stump11289f42009-09-09 15:08:12 +00004899/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004900/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004901/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004902int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004903 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4904 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004905
4906 // Unwrap enums to their underlying type.
4907 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4908 LHSC = getIntegerTypeForEnum(ET);
4909 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4910 RHSC = getIntegerTypeForEnum(ET);
4911
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004912 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004913
Chris Lattner76a00cf2008-04-06 22:59:24 +00004914 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4915 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004916
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004917 unsigned LHSRank = getIntegerRank(LHSC);
4918 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004919
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004920 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4921 if (LHSRank == RHSRank) return 0;
4922 return LHSRank > RHSRank ? 1 : -1;
4923 }
Mike Stump11289f42009-09-09 15:08:12 +00004924
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004925 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4926 if (LHSUnsigned) {
4927 // If the unsigned [LHS] type is larger, return it.
4928 if (LHSRank >= RHSRank)
4929 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004930
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004931 // If the signed type can represent all values of the unsigned type, it
4932 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004933 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004934 return -1;
4935 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004936
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004937 // If the unsigned [RHS] type is larger, return it.
4938 if (RHSRank >= LHSRank)
4939 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004940
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004941 // If the signed type can represent all values of the unsigned type, it
4942 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004943 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004944 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004945}
Anders Carlsson98f07902007-08-17 05:31:46 +00004946
Ben Langmuirf5416742016-02-04 00:55:24 +00004947TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004948 if (!CFConstantStringTypeDecl) {
Ben Langmuirf5416742016-02-04 00:55:24 +00004949 assert(!CFConstantStringTagDecl &&
4950 "tag and typedef should be initialized together");
4951 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
4952 CFConstantStringTagDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004953
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004954 QualType FieldTypes[4];
Ben Langmuir4791a802016-02-25 16:36:26 +00004955 const char *FieldNames[4];
Mike Stump11289f42009-09-09 15:08:12 +00004956
Anders Carlsson98f07902007-08-17 05:31:46 +00004957 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004958 FieldTypes[0] = getPointerType(IntTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00004959 FieldNames[0] = "isa";
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004960 // int flags;
4961 FieldTypes[1] = IntTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00004962 FieldNames[1] = "flags";
Anders Carlsson98f07902007-08-17 05:31:46 +00004963 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004964 FieldTypes[2] = getPointerType(CharTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00004965 FieldNames[2] = "str";
Anders Carlsson98f07902007-08-17 05:31:46 +00004966 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004967 FieldTypes[3] = LongTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00004968 FieldNames[3] = "length";
Mike Stump11289f42009-09-09 15:08:12 +00004969
Anders Carlsson98f07902007-08-17 05:31:46 +00004970 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004971 for (unsigned i = 0; i < 4; ++i) {
Ben Langmuirf5416742016-02-04 00:55:24 +00004972 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004973 SourceLocation(),
Ben Langmuir4791a802016-02-25 16:36:26 +00004974 SourceLocation(),
4975 &Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00004976 FieldTypes[i], /*TInfo=*/nullptr,
4977 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00004978 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004979 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004980 Field->setAccess(AS_public);
Ben Langmuirf5416742016-02-04 00:55:24 +00004981 CFConstantStringTagDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004982 }
4983
Ben Langmuirf5416742016-02-04 00:55:24 +00004984 CFConstantStringTagDecl->completeDefinition();
4985 // This type is designed to be compatible with NSConstantString, but cannot
4986 // use the same name, since NSConstantString is an interface.
4987 auto tagType = getTagDeclType(CFConstantStringTagDecl);
4988 CFConstantStringTypeDecl =
4989 buildImplicitTypedef(tagType, "__NSConstantString");
Anders Carlsson98f07902007-08-17 05:31:46 +00004990 }
Mike Stump11289f42009-09-09 15:08:12 +00004991
Quentin Colombet043406b2016-02-03 22:41:00 +00004992 return CFConstantStringTypeDecl;
4993}
4994
Ben Langmuirf5416742016-02-04 00:55:24 +00004995RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
4996 if (!CFConstantStringTagDecl)
4997 getCFConstantStringDecl(); // Build the tag and the typedef.
4998 return CFConstantStringTagDecl;
4999}
5000
Quentin Colombet043406b2016-02-03 22:41:00 +00005001// getCFConstantStringType - Return the type used for constant CFStrings.
5002QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00005003 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00005004}
Anders Carlsson87c149b2007-10-11 01:00:40 +00005005
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005006QualType ASTContext::getObjCSuperType() const {
5007 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005008 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005009 TUDecl->addDecl(ObjCSuperTypeDecl);
5010 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
5011 }
5012 return ObjCSuperType;
5013}
5014
Douglas Gregor512b0772009-04-23 22:29:11 +00005015void ASTContext::setCFConstantStringType(QualType T) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005016 const TypedefType *TD = T->getAs<TypedefType>();
5017 assert(TD && "Invalid CFConstantStringType");
5018 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
5019 auto TagType =
5020 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
5021 assert(TagType && "Invalid CFConstantStringType");
5022 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00005023}
5024
Jay Foad39c79802011-01-12 09:06:06 +00005025QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00005026 if (BlockDescriptorType)
5027 return getTagDeclType(BlockDescriptorType);
5028
Alp Toker2dea15b2013-12-17 01:22:38 +00005029 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005030 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005031 RD = buildImplicitRecord("__block_descriptor");
5032 RD->startDefinition();
5033
Mike Stumpd0153282009-10-20 02:12:22 +00005034 QualType FieldTypes[] = {
5035 UnsignedLongTy,
5036 UnsignedLongTy,
5037 };
5038
Craig Topperd6d31ac2013-07-15 08:24:27 +00005039 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00005040 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005041 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00005042 };
5043
5044 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005045 FieldDecl *Field = FieldDecl::Create(
5046 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005047 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5048 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005049 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005050 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00005051 }
5052
Alp Toker2dea15b2013-12-17 01:22:38 +00005053 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00005054
Alp Toker2dea15b2013-12-17 01:22:38 +00005055 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005056
5057 return getTagDeclType(BlockDescriptorType);
5058}
5059
Jay Foad39c79802011-01-12 09:06:06 +00005060QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005061 if (BlockDescriptorExtendedType)
5062 return getTagDeclType(BlockDescriptorExtendedType);
5063
Alp Toker2dea15b2013-12-17 01:22:38 +00005064 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005065 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005066 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
5067 RD->startDefinition();
5068
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005069 QualType FieldTypes[] = {
5070 UnsignedLongTy,
5071 UnsignedLongTy,
5072 getPointerType(VoidPtrTy),
5073 getPointerType(VoidPtrTy)
5074 };
5075
Craig Topperd6d31ac2013-07-15 08:24:27 +00005076 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005077 "reserved",
5078 "Size",
5079 "CopyFuncPtr",
5080 "DestroyFuncPtr"
5081 };
5082
5083 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005084 FieldDecl *Field = FieldDecl::Create(
5085 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005086 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5087 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00005088 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005089 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005090 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005091 }
5092
Alp Toker2dea15b2013-12-17 01:22:38 +00005093 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005094
Alp Toker2dea15b2013-12-17 01:22:38 +00005095 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005096 return getTagDeclType(BlockDescriptorExtendedType);
5097}
5098
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005099/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
5100/// requires copy/dispose. Note that this must match the logic
5101/// in buildByrefHelpers.
5102bool ASTContext::BlockRequiresCopying(QualType Ty,
5103 const VarDecl *D) {
5104 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
5105 const Expr *copyExpr = getBlockVarCopyInits(D);
5106 if (!copyExpr && record->hasTrivialDestructor()) return false;
5107
Mike Stump94967902009-10-21 18:16:27 +00005108 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00005109 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005110
5111 if (!Ty->isObjCRetainableType()) return false;
5112
5113 Qualifiers qs = Ty.getQualifiers();
5114
5115 // If we have lifetime, that dominates.
5116 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005117 switch (lifetime) {
5118 case Qualifiers::OCL_None: llvm_unreachable("impossible");
5119
5120 // These are just bits as far as the runtime is concerned.
5121 case Qualifiers::OCL_ExplicitNone:
5122 case Qualifiers::OCL_Autoreleasing:
5123 return false;
5124
5125 // Tell the runtime that this is ARC __weak, called by the
5126 // byref routines.
5127 case Qualifiers::OCL_Weak:
5128 // ARC __strong __block variables need to be retained.
5129 case Qualifiers::OCL_Strong:
5130 return true;
5131 }
5132 llvm_unreachable("fell out of lifetime switch!");
5133 }
5134 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
5135 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00005136}
5137
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005138bool ASTContext::getByrefLifetime(QualType Ty,
5139 Qualifiers::ObjCLifetime &LifeTime,
5140 bool &HasByrefExtendedLayout) const {
5141
5142 if (!getLangOpts().ObjC1 ||
5143 getLangOpts().getGC() != LangOptions::NonGC)
5144 return false;
5145
5146 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00005147 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005148 HasByrefExtendedLayout = true;
5149 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005150 } else if ((LifeTime = Ty.getObjCLifetime())) {
5151 // Honor the ARC qualifiers.
5152 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
5153 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005154 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00005155 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005156 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005157 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005158 return true;
5159}
5160
Douglas Gregorbab8a962011-09-08 01:46:34 +00005161TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5162 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00005163 ObjCInstanceTypeDecl =
5164 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00005165 return ObjCInstanceTypeDecl;
5166}
5167
Anders Carlsson18acd442007-10-29 06:33:42 +00005168// This returns true if a type has been typedefed to BOOL:
5169// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00005170static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00005171 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00005172 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5173 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00005174
Anders Carlssond8499822007-10-29 05:01:08 +00005175 return false;
5176}
5177
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005178/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005179/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00005180CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00005181 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5182 return CharUnits::Zero();
5183
Ken Dyck40775002010-01-11 17:06:35 +00005184 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00005185
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005186 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00005187 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00005188 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005189 // Treat arrays as pointers, since that's how they're passed in.
5190 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00005191 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00005192 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00005193}
5194
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005195bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00005196 return getTargetInfo().getCXXABI().isMicrosoft() &&
5197 VD->isStaticDataMember() &&
David Majnemerfac52432015-10-19 23:22:49 +00005198 VD->getType()->isIntegralOrEnumerationType() &&
5199 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005200}
5201
Richard Smithd9b90092016-07-02 01:32:16 +00005202ASTContext::InlineVariableDefinitionKind
5203ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
5204 if (!VD->isInline())
5205 return InlineVariableDefinitionKind::None;
5206
5207 // In almost all cases, it's a weak definition.
5208 auto *First = VD->getFirstDecl();
5209 if (!First->isConstexpr() || First->isInlineSpecified() ||
5210 !VD->isStaticDataMember())
5211 return InlineVariableDefinitionKind::Weak;
5212
5213 // If there's a file-context declaration in this translation unit, it's a
5214 // non-discardable definition.
5215 for (auto *D : VD->redecls())
5216 if (D->getLexicalDeclContext()->isFileContext())
5217 return InlineVariableDefinitionKind::Strong;
5218
5219 // If we've not seen one yet, we don't know.
5220 return InlineVariableDefinitionKind::WeakUnknown;
5221}
5222
Ken Dyck40775002010-01-11 17:06:35 +00005223static inline
5224std::string charUnitsToString(const CharUnits &CU) {
5225 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005226}
5227
John McCall351762c2011-02-07 10:33:21 +00005228/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00005229/// declaration.
John McCall351762c2011-02-07 10:33:21 +00005230std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5231 std::string S;
5232
David Chisnall950a9512009-11-17 19:33:30 +00005233 const BlockDecl *Decl = Expr->getBlockDecl();
5234 QualType BlockTy =
5235 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5236 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005237 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00005238 getObjCEncodingForMethodParameter(
5239 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5240 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005241 else
Alp Toker314cc812014-01-25 16:55:45 +00005242 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00005243 // Compute size of all parameters.
5244 // Start with computing size of a pointer in number of bytes.
5245 // FIXME: There might(should) be a better way of doing this computation!
5246 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005247 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5248 CharUnits ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005249 for (auto PI : Decl->parameters()) {
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005250 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005251 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00005252 if (sz.isZero())
5253 continue;
Ken Dyck40775002010-01-11 17:06:35 +00005254 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00005255 ParmOffset += sz;
5256 }
5257 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00005258 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00005259 // Block pointer and offset.
5260 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00005261
5262 // Argument types.
5263 ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005264 for (auto PVDecl : Decl->parameters()) {
David Chisnall950a9512009-11-17 19:33:30 +00005265 QualType PType = PVDecl->getOriginalType();
5266 if (const ArrayType *AT =
5267 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5268 // Use array's original type only if it has known number of
5269 // elements.
5270 if (!isa<ConstantArrayType>(AT))
5271 PType = PVDecl->getType();
5272 } else if (PType->isFunctionType())
5273 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005274 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005275 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5276 S, true /*Extended*/);
5277 else
5278 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00005279 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005280 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00005281 }
John McCall351762c2011-02-07 10:33:21 +00005282
5283 return S;
David Chisnall950a9512009-11-17 19:33:30 +00005284}
5285
Douglas Gregora9d84932011-05-27 01:19:52 +00005286bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00005287 std::string& S) {
5288 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00005289 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00005290 CharUnits ParmOffset;
5291 // Compute size of all parameters.
David Majnemer59f77922016-06-24 04:05:48 +00005292 for (auto PI : Decl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005293 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00005294 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005295 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005296 continue;
5297
David Chisnall50e4eba2010-12-30 14:05:53 +00005298 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00005299 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00005300 ParmOffset += sz;
5301 }
5302 S += charUnitsToString(ParmOffset);
5303 ParmOffset = CharUnits::Zero();
5304
5305 // Argument types.
David Majnemer59f77922016-06-24 04:05:48 +00005306 for (auto PVDecl : Decl->parameters()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005307 QualType PType = PVDecl->getOriginalType();
5308 if (const ArrayType *AT =
5309 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5310 // Use array's original type only if it has known number of
5311 // elements.
5312 if (!isa<ConstantArrayType>(AT))
5313 PType = PVDecl->getType();
5314 } else if (PType->isFunctionType())
5315 PType = PVDecl->getType();
5316 getObjCEncodingForType(PType, S);
5317 S += charUnitsToString(ParmOffset);
5318 ParmOffset += getObjCEncodingTypeSize(PType);
5319 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005320
5321 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00005322}
5323
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005324/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5325/// method parameter or return type. If Extended, include class names and
5326/// block object types.
5327void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5328 QualType T, std::string& S,
5329 bool Extended) const {
5330 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5331 getObjCEncodingForTypeQualifier(QT, S);
5332 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005333 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005334 true /*OutermostType*/,
5335 false /*EncodingProperty*/,
5336 false /*StructField*/,
5337 Extended /*EncodeBlockParameters*/,
5338 Extended /*EncodeClassNames*/);
5339}
5340
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005341/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005342/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00005343bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005344 std::string& S,
5345 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005346 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005347 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00005348 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5349 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005350 // Compute size of all parameters.
5351 // Start with computing size of a pointer in number of bytes.
5352 // FIXME: There might(should) be a better way of doing this computation!
5353 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005354 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005355 // The first two arguments (self and _cmd) are pointers; account for
5356 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00005357 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005358 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005359 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005360 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005361 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005362 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005363 continue;
5364
Ken Dyck40775002010-01-11 17:06:35 +00005365 assert (sz.isPositive() &&
5366 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005367 ParmOffset += sz;
5368 }
Ken Dyck40775002010-01-11 17:06:35 +00005369 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005370 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005371 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005372
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005373 // Argument types.
5374 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005375 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005376 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005377 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005378 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005379 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005380 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5381 // Use array's original type only if it has known number of
5382 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005383 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005384 PType = PVDecl->getType();
5385 } else if (PType->isFunctionType())
5386 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005387 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5388 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005389 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005390 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005391 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005392
5393 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005394}
5395
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005396ObjCPropertyImplDecl *
5397ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5398 const ObjCPropertyDecl *PD,
5399 const Decl *Container) const {
5400 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005401 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005402 if (const ObjCCategoryImplDecl *CID =
5403 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005404 for (auto *PID : CID->property_impls())
5405 if (PID->getPropertyDecl() == PD)
5406 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005407 } else {
5408 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5409 for (auto *PID : OID->property_impls())
5410 if (PID->getPropertyDecl() == PD)
5411 return PID;
5412 }
5413 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005414}
5415
Daniel Dunbar4932b362008-08-28 04:38:10 +00005416/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005417/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005418/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5419/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005420/// Property attributes are stored as a comma-delimited C string. The simple
5421/// attributes readonly and bycopy are encoded as single characters. The
5422/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5423/// encoded as single characters, followed by an identifier. Property types
5424/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005425/// these attributes are defined by the following enumeration:
5426/// @code
5427/// enum PropertyAttributes {
5428/// kPropertyReadOnly = 'R', // property is read-only.
5429/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5430/// kPropertyByref = '&', // property is a reference to the value last assigned
5431/// kPropertyDynamic = 'D', // property is dynamic
5432/// kPropertyGetter = 'G', // followed by getter selector name
5433/// kPropertySetter = 'S', // followed by setter selector name
5434/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005435/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005436/// kPropertyWeak = 'W' // 'weak' property
5437/// kPropertyStrong = 'P' // property GC'able
5438/// kPropertyNonAtomic = 'N' // property non-atomic
5439/// };
5440/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005441void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005442 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005443 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005444 // Collect information from the property implementation decl(s).
5445 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005446 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005447
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005448 if (ObjCPropertyImplDecl *PropertyImpDecl =
5449 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5450 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5451 Dynamic = true;
5452 else
5453 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005454 }
5455
5456 // FIXME: This is not very efficient.
5457 S = "T";
5458
5459 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005460 // GCC has some special rules regarding encoding of properties which
5461 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005462 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005463
5464 if (PD->isReadOnly()) {
5465 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005466 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5467 S += ",C";
5468 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5469 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005470 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5471 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005472 } else {
5473 switch (PD->getSetterKind()) {
5474 case ObjCPropertyDecl::Assign: break;
5475 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005476 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005477 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005478 }
5479 }
5480
5481 // It really isn't clear at all what this means, since properties
5482 // are "dynamic by default".
5483 if (Dynamic)
5484 S += ",D";
5485
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005486 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5487 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005488
Daniel Dunbar4932b362008-08-28 04:38:10 +00005489 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5490 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005491 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005492 }
5493
5494 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5495 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005496 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005497 }
5498
5499 if (SynthesizePID) {
5500 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5501 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005502 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005503 }
5504
5505 // FIXME: OBJCGC: weak & strong
5506}
5507
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005508/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005509/// Another legacy compatibility encoding: 32-bit longs are encoded as
5510/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005511/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5512///
5513void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005514 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005515 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005516 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005517 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005518 else
Jay Foad39c79802011-01-12 09:06:06 +00005519 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005520 PointeeTy = IntTy;
5521 }
5522 }
5523}
5524
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005525void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005526 const FieldDecl *Field,
5527 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005528 // We follow the behavior of gcc, expanding structures which are
5529 // directly pointed to, and expanding embedded structures. Note that
5530 // these rules are sufficient to prevent recursive encoding of the
5531 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005532 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005533 true /* outermost type */, false, false,
5534 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005535}
5536
Joe Groff98ac7d22014-07-07 22:25:15 +00005537void ASTContext::getObjCEncodingForPropertyType(QualType T,
5538 std::string& S) const {
5539 // Encode result type.
5540 // GCC has some special rules regarding encoding of properties which
5541 // closely resembles encoding of ivars.
5542 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5543 true /* outermost type */,
5544 true /* encoding property */);
5545}
5546
John McCall393a78d2012-12-20 02:45:14 +00005547static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5548 BuiltinType::Kind kind) {
5549 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005550 case BuiltinType::Void: return 'v';
5551 case BuiltinType::Bool: return 'B';
5552 case BuiltinType::Char_U:
5553 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005554 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005555 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005556 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005557 case BuiltinType::UInt: return 'I';
5558 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005559 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005560 case BuiltinType::UInt128: return 'T';
5561 case BuiltinType::ULongLong: return 'Q';
5562 case BuiltinType::Char_S:
5563 case BuiltinType::SChar: return 'c';
5564 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005565 case BuiltinType::WChar_S:
5566 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005567 case BuiltinType::Int: return 'i';
5568 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005569 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005570 case BuiltinType::LongLong: return 'q';
5571 case BuiltinType::Int128: return 't';
5572 case BuiltinType::Float: return 'f';
5573 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005574 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005575 case BuiltinType::NullPtr: return '*'; // like char*
5576
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005577 case BuiltinType::Float128:
John McCall393a78d2012-12-20 02:45:14 +00005578 case BuiltinType::Half:
5579 // FIXME: potentially need @encodes for these!
5580 return ' ';
5581
5582 case BuiltinType::ObjCId:
5583 case BuiltinType::ObjCClass:
5584 case BuiltinType::ObjCSel:
5585 llvm_unreachable("@encoding ObjC primitive type");
5586
5587 // OpenCL and placeholder types don't need @encodings.
Alexey Bader954ba212016-04-08 13:40:33 +00005588#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5589 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00005590#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005591 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005592 case BuiltinType::OCLClkEvent:
5593 case BuiltinType::OCLQueue:
5594 case BuiltinType::OCLNDRange:
5595 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00005596 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005597 case BuiltinType::Dependent:
5598#define BUILTIN_TYPE(KIND, ID)
5599#define PLACEHOLDER_TYPE(KIND, ID) \
5600 case BuiltinType::KIND:
5601#include "clang/AST/BuiltinTypes.def"
5602 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005603 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005604 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005605}
5606
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005607static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5608 EnumDecl *Enum = ET->getDecl();
5609
5610 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5611 if (!Enum->isFixed())
5612 return 'i';
5613
5614 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005615 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5616 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005617}
5618
Jay Foad39c79802011-01-12 09:06:06 +00005619static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005620 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005621 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005622 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005623 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5624 // The GNU runtime requires more information; bitfields are encoded as b,
5625 // then the offset (in bits) of the first element, then the type of the
5626 // bitfield, then the size in bits. For example, in this structure:
5627 //
5628 // struct
5629 // {
5630 // int integer;
5631 // int flags:2;
5632 // };
5633 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5634 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5635 // information is not especially sensible, but we're stuck with it for
5636 // compatibility with GCC, although providing it breaks anything that
5637 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005638 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005639 const RecordDecl *RD = FD->getParent();
5640 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005641 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005642 if (const EnumType *ET = T->getAs<EnumType>())
5643 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005644 else {
5645 const BuiltinType *BT = T->castAs<BuiltinType>();
5646 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5647 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005648 }
Richard Smithcaf33902011-10-10 18:28:20 +00005649 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005650}
5651
Daniel Dunbar07d07852009-10-18 21:17:35 +00005652// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005653void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5654 bool ExpandPointedToStructures,
5655 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005656 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005657 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005658 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005659 bool StructField,
5660 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005661 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005662 bool EncodePointerToObjCTypedef,
5663 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00005664 CanQualType CT = getCanonicalType(T);
5665 switch (CT->getTypeClass()) {
5666 case Type::Builtin:
5667 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005668 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005669 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005670 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5671 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5672 else
5673 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005674 return;
Mike Stump11289f42009-09-09 15:08:12 +00005675
John McCall393a78d2012-12-20 02:45:14 +00005676 case Type::Complex: {
5677 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005678 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005679 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005680 return;
5681 }
John McCall393a78d2012-12-20 02:45:14 +00005682
5683 case Type::Atomic: {
5684 const AtomicType *AT = T->castAs<AtomicType>();
5685 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005686 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00005687 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005688 }
John McCall393a78d2012-12-20 02:45:14 +00005689
5690 // encoding for pointer or reference types.
5691 case Type::Pointer:
5692 case Type::LValueReference:
5693 case Type::RValueReference: {
5694 QualType PointeeTy;
5695 if (isa<PointerType>(CT)) {
5696 const PointerType *PT = T->castAs<PointerType>();
5697 if (PT->isObjCSelType()) {
5698 S += ':';
5699 return;
5700 }
5701 PointeeTy = PT->getPointeeType();
5702 } else {
5703 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5704 }
5705
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005706 bool isReadOnly = false;
5707 // For historical/compatibility reasons, the read-only qualifier of the
5708 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5709 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005710 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005711 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005712 if (OutermostType && T.isConstQualified()) {
5713 isReadOnly = true;
5714 S += 'r';
5715 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005716 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005717 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005718 while (P->getAs<PointerType>())
5719 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005720 if (P.isConstQualified()) {
5721 isReadOnly = true;
5722 S += 'r';
5723 }
5724 }
5725 if (isReadOnly) {
5726 // Another legacy compatibility encoding. Some ObjC qualifier and type
5727 // combinations need to be rearranged.
5728 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005729 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005730 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005731 }
Mike Stump11289f42009-09-09 15:08:12 +00005732
Anders Carlssond8499822007-10-29 05:01:08 +00005733 if (PointeeTy->isCharType()) {
5734 // char pointer types should be encoded as '*' unless it is a
5735 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005736 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005737 S += '*';
5738 return;
5739 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005740 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005741 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5742 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5743 S += '#';
5744 return;
5745 }
5746 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5747 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5748 S += '@';
5749 return;
5750 }
5751 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005752 }
Anders Carlssond8499822007-10-29 05:01:08 +00005753 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005754 getLegacyIntegralTypeEncoding(PointeeTy);
5755
Mike Stump11289f42009-09-09 15:08:12 +00005756 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005757 nullptr, false, false, false, false, false, false,
5758 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005759 return;
5760 }
John McCall393a78d2012-12-20 02:45:14 +00005761
5762 case Type::ConstantArray:
5763 case Type::IncompleteArray:
5764 case Type::VariableArray: {
5765 const ArrayType *AT = cast<ArrayType>(CT);
5766
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005767 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005768 // Incomplete arrays are encoded as a pointer to the array element.
5769 S += '^';
5770
Mike Stump11289f42009-09-09 15:08:12 +00005771 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005772 false, ExpandStructures, FD);
5773 } else {
5774 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005775
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005776 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5777 S += llvm::utostr(CAT->getSize().getZExtValue());
5778 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005779 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005780 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5781 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005782 S += '0';
5783 }
Mike Stump11289f42009-09-09 15:08:12 +00005784
5785 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005786 false, ExpandStructures, FD,
5787 false, false, false, false, false, false,
5788 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00005789 S += ']';
5790 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005791 return;
5792 }
Mike Stump11289f42009-09-09 15:08:12 +00005793
John McCall393a78d2012-12-20 02:45:14 +00005794 case Type::FunctionNoProto:
5795 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005796 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005797 return;
Mike Stump11289f42009-09-09 15:08:12 +00005798
John McCall393a78d2012-12-20 02:45:14 +00005799 case Type::Record: {
5800 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005801 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005802 // Anonymous structures print as '?'
5803 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5804 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005805 if (ClassTemplateSpecializationDecl *Spec
5806 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5807 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005808 llvm::raw_string_ostream OS(S);
5809 TemplateSpecializationType::PrintTemplateArgumentList(OS,
David Majnemer6fbeee32016-07-07 04:43:07 +00005810 TemplateArgs.asArray(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005811 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005812 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005813 } else {
5814 S += '?';
5815 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005816 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005817 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005818 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005819 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005820 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005821 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005822 if (FD) {
5823 S += '"';
5824 S += Field->getNameAsString();
5825 S += '"';
5826 }
Mike Stump11289f42009-09-09 15:08:12 +00005827
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005828 // Special case bit-fields.
5829 if (Field->isBitField()) {
5830 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005831 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005832 } else {
5833 QualType qt = Field->getType();
5834 getLegacyIntegralTypeEncoding(qt);
5835 getObjCEncodingForTypeImpl(qt, S, false, true,
5836 FD, /*OutermostType*/false,
5837 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005838 /*StructField*/true,
5839 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005840 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005841 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005842 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005843 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005844 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005845 return;
5846 }
Mike Stump11289f42009-09-09 15:08:12 +00005847
John McCall393a78d2012-12-20 02:45:14 +00005848 case Type::BlockPointer: {
5849 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005850 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005851 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005852 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005853
5854 S += '<';
5855 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005856 getObjCEncodingForTypeImpl(
5857 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5858 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005859 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5860 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005861 // Block self
5862 S += "@?";
5863 // Block parameters
5864 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005865 for (const auto &I : FPT->param_types())
5866 getObjCEncodingForTypeImpl(
5867 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5868 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005869 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5870 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005871 }
5872 S += '>';
5873 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005874 return;
5875 }
Mike Stump11289f42009-09-09 15:08:12 +00005876
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005877 case Type::ObjCObject: {
5878 // hack to match legacy encoding of *id and *Class
5879 QualType Ty = getObjCObjectPointerType(CT);
5880 if (Ty->isObjCIdType()) {
5881 S += "{objc_object=}";
5882 return;
5883 }
5884 else if (Ty->isObjCClassType()) {
5885 S += "{objc_class=}";
5886 return;
5887 }
5888 }
5889
John McCall393a78d2012-12-20 02:45:14 +00005890 case Type::ObjCInterface: {
5891 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005892 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00005893 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005894 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005895 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005896 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005897 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005898 DeepCollectObjCIvars(OI, true, Ivars);
5899 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005900 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005901 if (Field->isBitField())
5902 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005903 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005904 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5905 false, false, false, false, false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005906 EncodePointerToObjCTypedef,
5907 NotEncodedT);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005908 }
5909 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005910 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005911 }
Mike Stump11289f42009-09-09 15:08:12 +00005912
John McCall393a78d2012-12-20 02:45:14 +00005913 case Type::ObjCObjectPointer: {
5914 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005915 if (OPT->isObjCIdType()) {
5916 S += '@';
5917 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005918 }
Mike Stump11289f42009-09-09 15:08:12 +00005919
Steve Narofff0c86112009-10-28 22:03:49 +00005920 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5921 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5922 // Since this is a binary compatibility issue, need to consult with runtime
5923 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005924 S += '#';
5925 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005926 }
Mike Stump11289f42009-09-09 15:08:12 +00005927
Chris Lattnere7cabb92009-07-13 00:10:46 +00005928 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005929 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005930 ExpandPointedToStructures,
5931 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005932 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005933 // Note that we do extended encoding of protocol qualifer list
5934 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005935 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00005936 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005937 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005938 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005939 S += '>';
5940 }
5941 S += '"';
5942 }
5943 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005944 }
Mike Stump11289f42009-09-09 15:08:12 +00005945
Chris Lattnere7cabb92009-07-13 00:10:46 +00005946 QualType PointeeTy = OPT->getPointeeType();
5947 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005948 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5949 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005950 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005951 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005952 // {...};
5953 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005954 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005955 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005956 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5957 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5958 DeepCollectObjCIvars(OI, true, Ivars);
5959 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5960 if (cast<FieldDecl>(Ivars[i]) == FD) {
5961 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005962 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005963 S += '}';
5964 return;
5965 }
5966 }
5967 }
Mike Stump11289f42009-09-09 15:08:12 +00005968 getObjCEncodingForTypeImpl(PointeeTy, S,
5969 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00005970 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005971 false, false, false, false, false,
5972 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005973 return;
5974 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005975
5976 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005977 if (OPT->getInterfaceDecl() &&
5978 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005979 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005980 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00005981 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005982 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005983 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00005984 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005985 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005986 S += '"';
5987 }
5988 return;
5989 }
Mike Stump11289f42009-09-09 15:08:12 +00005990
John McCalla9e6e8d2010-05-17 23:56:34 +00005991 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005992 // FIXME: we shoul do better than that. 'M' is available.
5993 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005994 // This matches gcc's encoding, even though technically it is insufficient.
5995 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00005996 case Type::Vector:
5997 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005998 // Until we have a coherent encoding of these three types, issue warning.
5999 { if (NotEncodedT)
6000 *NotEncodedT = T;
6001 return;
6002 }
6003
6004 // We could see an undeduced auto type here during error recovery.
6005 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00006006 case Type::Auto:
Richard Smith27d807c2013-04-30 13:56:41 +00006007 return;
6008
Xiuli Pan9c14e282016-01-09 12:53:17 +00006009 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00006010#define ABSTRACT_TYPE(KIND, BASE)
6011#define TYPE(KIND, BASE)
6012#define DEPENDENT_TYPE(KIND, BASE) \
6013 case Type::KIND:
6014#define NON_CANONICAL_TYPE(KIND, BASE) \
6015 case Type::KIND:
6016#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
6017 case Type::KIND:
6018#include "clang/AST/TypeNodes.def"
6019 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00006020 }
John McCall393a78d2012-12-20 02:45:14 +00006021 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00006022}
6023
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006024void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
6025 std::string &S,
6026 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006027 bool includeVBases,
6028 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006029 assert(RDecl && "Expected non-null RecordDecl");
6030 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00006031 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006032 return;
6033
6034 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
6035 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
6036 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
6037
6038 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00006039 for (const auto &BI : CXXRec->bases()) {
6040 if (!BI.isVirtual()) {
6041 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006042 if (base->isEmpty())
6043 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006044 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006045 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6046 std::make_pair(offs, base));
6047 }
6048 }
6049 }
6050
6051 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00006052 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006053 uint64_t offs = layout.getFieldOffset(i);
6054 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00006055 std::make_pair(offs, Field));
6056 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006057 }
6058
6059 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00006060 for (const auto &BI : CXXRec->vbases()) {
6061 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006062 if (base->isEmpty())
6063 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006064 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00006065 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
6066 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00006067 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
6068 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006069 }
6070 }
6071
6072 CharUnits size;
6073 if (CXXRec) {
6074 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
6075 } else {
6076 size = layout.getSize();
6077 }
6078
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006079#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006080 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006081#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006082 std::multimap<uint64_t, NamedDecl *>::iterator
6083 CurLayObj = FieldOrBaseOffsets.begin();
6084
Douglas Gregorf5d6c742012-04-27 22:30:01 +00006085 if (CXXRec && CXXRec->isDynamicClass() &&
6086 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006087 if (FD) {
6088 S += "\"_vptr$";
6089 std::string recname = CXXRec->getNameAsString();
6090 if (recname.empty()) recname = "?";
6091 S += recname;
6092 S += '"';
6093 }
6094 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006095#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006096 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006097#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006098 }
6099
6100 if (!RDecl->hasFlexibleArrayMember()) {
6101 // Mark the end of the structure.
6102 uint64_t offs = toBits(size);
6103 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00006104 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006105 }
6106
6107 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006108#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006109 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006110 if (CurOffs < CurLayObj->first) {
6111 uint64_t padding = CurLayObj->first - CurOffs;
6112 // FIXME: There doesn't seem to be a way to indicate in the encoding that
6113 // packing/alignment of members is different that normal, in which case
6114 // the encoding will be out-of-sync with the real layout.
6115 // If the runtime switches to just consider the size of types without
6116 // taking into account alignment, we could make padding explicit in the
6117 // encoding (e.g. using arrays of chars). The encoding strings would be
6118 // longer then though.
6119 CurOffs += padding;
6120 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006121#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006122
6123 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00006124 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006125 break; // reached end of structure.
6126
6127 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
6128 // We expand the bases without their virtual bases since those are going
6129 // in the initial structure. Note that this differs from gcc which
6130 // expands virtual bases each time one is encountered in the hierarchy,
6131 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006132 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
6133 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006134 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006135#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006136 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006137#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006138 } else {
6139 FieldDecl *field = cast<FieldDecl>(dcl);
6140 if (FD) {
6141 S += '"';
6142 S += field->getNameAsString();
6143 S += '"';
6144 }
6145
6146 if (field->isBitField()) {
6147 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006148#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00006149 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006150#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006151 } else {
6152 QualType qt = field->getType();
6153 getLegacyIntegralTypeEncoding(qt);
6154 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
6155 /*OutermostType*/false,
6156 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006157 /*StructField*/true,
6158 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006159#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006160 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006161#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006162 }
6163 }
6164 }
6165}
6166
Mike Stump11289f42009-09-09 15:08:12 +00006167void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00006168 std::string& S) const {
6169 if (QT & Decl::OBJC_TQ_In)
6170 S += 'n';
6171 if (QT & Decl::OBJC_TQ_Inout)
6172 S += 'N';
6173 if (QT & Decl::OBJC_TQ_Out)
6174 S += 'o';
6175 if (QT & Decl::OBJC_TQ_Bycopy)
6176 S += 'O';
6177 if (QT & Decl::OBJC_TQ_Byref)
6178 S += 'R';
6179 if (QT & Decl::OBJC_TQ_Oneway)
6180 S += 'V';
6181}
6182
Douglas Gregor3ea72692011-08-12 05:46:01 +00006183TypedefDecl *ASTContext::getObjCIdDecl() const {
6184 if (!ObjCIdDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006185 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
Douglas Gregor3ea72692011-08-12 05:46:01 +00006186 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006187 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00006188 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00006189 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00006190}
6191
Douglas Gregor52e02802011-08-12 06:17:30 +00006192TypedefDecl *ASTContext::getObjCSelDecl() const {
6193 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006194 QualType T = getPointerType(ObjCBuiltinSelTy);
6195 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00006196 }
6197 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00006198}
6199
Douglas Gregor0a586182011-08-12 05:59:41 +00006200TypedefDecl *ASTContext::getObjCClassDecl() const {
6201 if (!ObjCClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006202 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
Douglas Gregor0a586182011-08-12 05:59:41 +00006203 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006204 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00006205 }
Douglas Gregor0a586182011-08-12 05:59:41 +00006206 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00006207}
6208
Douglas Gregord53ae832012-01-17 18:09:05 +00006209ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6210 if (!ObjCProtocolClassDecl) {
6211 ObjCProtocolClassDecl
6212 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6213 SourceLocation(),
6214 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00006215 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00006216 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00006217 SourceLocation(), true);
6218 }
6219
6220 return ObjCProtocolClassDecl;
6221}
6222
Meador Inge5d3fb222012-06-16 03:34:49 +00006223//===----------------------------------------------------------------------===//
6224// __builtin_va_list Construction Functions
6225//===----------------------------------------------------------------------===//
6226
Charles Davisc7d5c942015-09-17 20:55:33 +00006227static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6228 StringRef Name) {
6229 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006230 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00006231 return Context->buildImplicitTypedef(T, Name);
6232}
6233
6234static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6235 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6236}
6237
6238static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6239 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006240}
6241
6242static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6243 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006244 QualType T = Context->getPointerType(Context->VoidTy);
6245 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006246}
6247
Tim Northover9bb857a2013-01-31 12:13:10 +00006248static TypedefDecl *
6249CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006250 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006251 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006252 if (Context->getLangOpts().CPlusPlus) {
6253 // namespace std { struct __va_list {
6254 NamespaceDecl *NS;
6255 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6256 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00006257 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00006258 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006259 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006260 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00006261 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00006262 }
6263
6264 VaListTagDecl->startDefinition();
6265
6266 const size_t NumFields = 5;
6267 QualType FieldTypes[NumFields];
6268 const char *FieldNames[NumFields];
6269
6270 // void *__stack;
6271 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6272 FieldNames[0] = "__stack";
6273
6274 // void *__gr_top;
6275 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6276 FieldNames[1] = "__gr_top";
6277
6278 // void *__vr_top;
6279 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6280 FieldNames[2] = "__vr_top";
6281
6282 // int __gr_offs;
6283 FieldTypes[3] = Context->IntTy;
6284 FieldNames[3] = "__gr_offs";
6285
6286 // int __vr_offs;
6287 FieldTypes[4] = Context->IntTy;
6288 FieldNames[4] = "__vr_offs";
6289
6290 // Create fields
6291 for (unsigned i = 0; i < NumFields; ++i) {
6292 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6293 VaListTagDecl,
6294 SourceLocation(),
6295 SourceLocation(),
6296 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006297 FieldTypes[i], /*TInfo=*/nullptr,
6298 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00006299 /*Mutable=*/false,
6300 ICIS_NoInit);
6301 Field->setAccess(AS_public);
6302 VaListTagDecl->addDecl(Field);
6303 }
6304 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006305 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00006306 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00006307
6308 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006309 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006310}
6311
Meador Inge5d3fb222012-06-16 03:34:49 +00006312static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6313 // typedef struct __va_list_tag {
6314 RecordDecl *VaListTagDecl;
6315
Alp Toker2dea15b2013-12-17 01:22:38 +00006316 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006317 VaListTagDecl->startDefinition();
6318
6319 const size_t NumFields = 5;
6320 QualType FieldTypes[NumFields];
6321 const char *FieldNames[NumFields];
6322
6323 // unsigned char gpr;
6324 FieldTypes[0] = Context->UnsignedCharTy;
6325 FieldNames[0] = "gpr";
6326
6327 // unsigned char fpr;
6328 FieldTypes[1] = Context->UnsignedCharTy;
6329 FieldNames[1] = "fpr";
6330
6331 // unsigned short reserved;
6332 FieldTypes[2] = Context->UnsignedShortTy;
6333 FieldNames[2] = "reserved";
6334
6335 // void* overflow_arg_area;
6336 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6337 FieldNames[3] = "overflow_arg_area";
6338
6339 // void* reg_save_area;
6340 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6341 FieldNames[4] = "reg_save_area";
6342
6343 // Create fields
6344 for (unsigned i = 0; i < NumFields; ++i) {
6345 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6346 SourceLocation(),
6347 SourceLocation(),
6348 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006349 FieldTypes[i], /*TInfo=*/nullptr,
6350 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006351 /*Mutable=*/false,
6352 ICIS_NoInit);
6353 Field->setAccess(AS_public);
6354 VaListTagDecl->addDecl(Field);
6355 }
6356 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006357 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006358 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6359
6360 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006361 TypedefDecl *VaListTagTypedefDecl =
6362 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6363
Meador Inge5d3fb222012-06-16 03:34:49 +00006364 QualType VaListTagTypedefType =
6365 Context->getTypedefType(VaListTagTypedefDecl);
6366
6367 // typedef __va_list_tag __builtin_va_list[1];
6368 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6369 QualType VaListTagArrayType
6370 = Context->getConstantArrayType(VaListTagTypedefType,
6371 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006372 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006373}
6374
6375static TypedefDecl *
6376CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006377 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00006378 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006379 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006380 VaListTagDecl->startDefinition();
6381
6382 const size_t NumFields = 4;
6383 QualType FieldTypes[NumFields];
6384 const char *FieldNames[NumFields];
6385
6386 // unsigned gp_offset;
6387 FieldTypes[0] = Context->UnsignedIntTy;
6388 FieldNames[0] = "gp_offset";
6389
6390 // unsigned fp_offset;
6391 FieldTypes[1] = Context->UnsignedIntTy;
6392 FieldNames[1] = "fp_offset";
6393
6394 // void* overflow_arg_area;
6395 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6396 FieldNames[2] = "overflow_arg_area";
6397
6398 // void* reg_save_area;
6399 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6400 FieldNames[3] = "reg_save_area";
6401
6402 // Create fields
6403 for (unsigned i = 0; i < NumFields; ++i) {
6404 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6405 VaListTagDecl,
6406 SourceLocation(),
6407 SourceLocation(),
6408 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006409 FieldTypes[i], /*TInfo=*/nullptr,
6410 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006411 /*Mutable=*/false,
6412 ICIS_NoInit);
6413 Field->setAccess(AS_public);
6414 VaListTagDecl->addDecl(Field);
6415 }
6416 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006417 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006418 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6419
Richard Smith9b88a4c2015-07-27 05:40:23 +00006420 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00006421
Richard Smith9b88a4c2015-07-27 05:40:23 +00006422 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00006423 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006424 QualType VaListTagArrayType =
6425 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006426 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006427}
6428
6429static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6430 // typedef int __builtin_va_list[4];
6431 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6432 QualType IntArrayType
6433 = Context->getConstantArrayType(Context->IntTy,
6434 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006435 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006436}
6437
Logan Chien57086ce2012-10-10 06:56:20 +00006438static TypedefDecl *
6439CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006440 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006441 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006442 if (Context->getLangOpts().CPlusPlus) {
6443 // namespace std { struct __va_list {
6444 NamespaceDecl *NS;
6445 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6446 Context->getTranslationUnitDecl(),
6447 /*Inline*/false, SourceLocation(),
6448 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006449 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006450 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006451 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006452 }
6453
6454 VaListDecl->startDefinition();
6455
6456 // void * __ap;
6457 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6458 VaListDecl,
6459 SourceLocation(),
6460 SourceLocation(),
6461 &Context->Idents.get("__ap"),
6462 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006463 /*TInfo=*/nullptr,
6464 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006465 /*Mutable=*/false,
6466 ICIS_NoInit);
6467 Field->setAccess(AS_public);
6468 VaListDecl->addDecl(Field);
6469
6470 // };
6471 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00006472 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00006473
6474 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006475 QualType T = Context->getRecordType(VaListDecl);
6476 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006477}
6478
Ulrich Weigand47445072013-05-06 16:26:41 +00006479static TypedefDecl *
6480CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006481 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00006482 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006483 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006484 VaListTagDecl->startDefinition();
6485
6486 const size_t NumFields = 4;
6487 QualType FieldTypes[NumFields];
6488 const char *FieldNames[NumFields];
6489
6490 // long __gpr;
6491 FieldTypes[0] = Context->LongTy;
6492 FieldNames[0] = "__gpr";
6493
6494 // long __fpr;
6495 FieldTypes[1] = Context->LongTy;
6496 FieldNames[1] = "__fpr";
6497
6498 // void *__overflow_arg_area;
6499 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6500 FieldNames[2] = "__overflow_arg_area";
6501
6502 // void *__reg_save_area;
6503 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6504 FieldNames[3] = "__reg_save_area";
6505
6506 // Create fields
6507 for (unsigned i = 0; i < NumFields; ++i) {
6508 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6509 VaListTagDecl,
6510 SourceLocation(),
6511 SourceLocation(),
6512 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006513 FieldTypes[i], /*TInfo=*/nullptr,
6514 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006515 /*Mutable=*/false,
6516 ICIS_NoInit);
6517 Field->setAccess(AS_public);
6518 VaListTagDecl->addDecl(Field);
6519 }
6520 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006521 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00006522 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00006523
Richard Smith9b88a4c2015-07-27 05:40:23 +00006524 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00006525
6526 // typedef __va_list_tag __builtin_va_list[1];
6527 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006528 QualType VaListTagArrayType =
6529 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006530
Alp Toker56b5cc92013-12-15 10:36:26 +00006531 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006532}
6533
Meador Inge5d3fb222012-06-16 03:34:49 +00006534static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6535 TargetInfo::BuiltinVaListKind Kind) {
6536 switch (Kind) {
6537 case TargetInfo::CharPtrBuiltinVaList:
6538 return CreateCharPtrBuiltinVaListDecl(Context);
6539 case TargetInfo::VoidPtrBuiltinVaList:
6540 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006541 case TargetInfo::AArch64ABIBuiltinVaList:
6542 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006543 case TargetInfo::PowerABIBuiltinVaList:
6544 return CreatePowerABIBuiltinVaListDecl(Context);
6545 case TargetInfo::X86_64ABIBuiltinVaList:
6546 return CreateX86_64ABIBuiltinVaListDecl(Context);
6547 case TargetInfo::PNaClABIBuiltinVaList:
6548 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006549 case TargetInfo::AAPCSABIBuiltinVaList:
6550 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006551 case TargetInfo::SystemZBuiltinVaList:
6552 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006553 }
6554
6555 llvm_unreachable("Unhandled __builtin_va_list type kind");
6556}
6557
6558TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006559 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006560 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006561 assert(BuiltinVaListDecl->isImplicit());
6562 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006563
6564 return BuiltinVaListDecl;
6565}
6566
Richard Smith9b88a4c2015-07-27 05:40:23 +00006567Decl *ASTContext::getVaListTagDecl() const {
6568 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00006569 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00006570 if (!VaListTagDecl)
6571 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00006572
Richard Smith9b88a4c2015-07-27 05:40:23 +00006573 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00006574}
6575
Charles Davisc7d5c942015-09-17 20:55:33 +00006576TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6577 if (!BuiltinMSVaListDecl)
6578 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6579
6580 return BuiltinMSVaListDecl;
6581}
6582
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006583void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006584 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006585 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006586
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006587 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006588}
6589
John McCalld28ae272009-12-02 08:04:21 +00006590/// \brief Retrieve the template name that corresponds to a non-empty
6591/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006592TemplateName
6593ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6594 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006595 unsigned size = End - Begin;
6596 assert(size > 1 && "set is not overloaded!");
6597
6598 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6599 size * sizeof(FunctionTemplateDecl*));
6600 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6601
6602 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006603 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006604 NamedDecl *D = *I;
6605 assert(isa<FunctionTemplateDecl>(D) ||
6606 (isa<UsingShadowDecl>(D) &&
6607 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6608 *Storage++ = D;
6609 }
6610
6611 return TemplateName(OT);
6612}
6613
Douglas Gregordc572a32009-03-30 22:58:21 +00006614/// \brief Retrieve the template name that represents a qualified
6615/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006616TemplateName
6617ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6618 bool TemplateKeyword,
6619 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006620 assert(NNS && "Missing nested-name-specifier in qualified template name");
6621
Douglas Gregorc42075a2010-02-04 18:10:26 +00006622 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006623 llvm::FoldingSetNodeID ID;
6624 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6625
Craig Topper36250ad2014-05-12 05:36:57 +00006626 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006627 QualifiedTemplateName *QTN =
6628 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6629 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006630 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6631 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006632 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6633 }
6634
6635 return TemplateName(QTN);
6636}
6637
6638/// \brief Retrieve the template name that represents a dependent
6639/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006640TemplateName
6641ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6642 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006643 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006644 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006645
6646 llvm::FoldingSetNodeID ID;
6647 DependentTemplateName::Profile(ID, NNS, Name);
6648
Craig Topper36250ad2014-05-12 05:36:57 +00006649 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006650 DependentTemplateName *QTN =
6651 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6652
6653 if (QTN)
6654 return TemplateName(QTN);
6655
6656 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6657 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006658 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6659 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006660 } else {
6661 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006662 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6663 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006664 DependentTemplateName *CheckQTN =
6665 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6666 assert(!CheckQTN && "Dependent type name canonicalization broken");
6667 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006668 }
6669
6670 DependentTemplateNames.InsertNode(QTN, InsertPos);
6671 return TemplateName(QTN);
6672}
6673
Douglas Gregor71395fa2009-11-04 00:56:37 +00006674/// \brief Retrieve the template name that represents a dependent
6675/// template name such as \c MetaFun::template operator+.
6676TemplateName
6677ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006678 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006679 assert((!NNS || NNS->isDependent()) &&
6680 "Nested name specifier must be dependent");
6681
6682 llvm::FoldingSetNodeID ID;
6683 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00006684
6685 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006686 DependentTemplateName *QTN
6687 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006688
6689 if (QTN)
6690 return TemplateName(QTN);
6691
6692 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6693 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006694 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6695 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006696 } else {
6697 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006698 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6699 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006700
6701 DependentTemplateName *CheckQTN
6702 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6703 assert(!CheckQTN && "Dependent template name canonicalization broken");
6704 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006705 }
6706
6707 DependentTemplateNames.InsertNode(QTN, InsertPos);
6708 return TemplateName(QTN);
6709}
6710
Douglas Gregor5590be02011-01-15 06:45:20 +00006711TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006712ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6713 TemplateName replacement) const {
6714 llvm::FoldingSetNodeID ID;
6715 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00006716
6717 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00006718 SubstTemplateTemplateParmStorage *subst
6719 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6720
6721 if (!subst) {
6722 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6723 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6724 }
6725
6726 return TemplateName(subst);
6727}
6728
6729TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006730ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6731 const TemplateArgument &ArgPack) const {
6732 ASTContext &Self = const_cast<ASTContext &>(*this);
6733 llvm::FoldingSetNodeID ID;
6734 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00006735
6736 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00006737 SubstTemplateTemplateParmPackStorage *Subst
6738 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6739
6740 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006741 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006742 ArgPack.pack_size(),
6743 ArgPack.pack_begin());
6744 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6745 }
6746
6747 return TemplateName(Subst);
6748}
6749
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006750/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006751/// TargetInfo, produce the corresponding type. The unsigned @p Type
6752/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006753CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006754 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006755 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006756 case TargetInfo::SignedChar: return SignedCharTy;
6757 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006758 case TargetInfo::SignedShort: return ShortTy;
6759 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6760 case TargetInfo::SignedInt: return IntTy;
6761 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6762 case TargetInfo::SignedLong: return LongTy;
6763 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6764 case TargetInfo::SignedLongLong: return LongLongTy;
6765 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6766 }
6767
David Blaikie83d382b2011-09-23 05:06:16 +00006768 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006769}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006770
6771//===----------------------------------------------------------------------===//
6772// Type Predicates.
6773//===----------------------------------------------------------------------===//
6774
Fariborz Jahanian96207692009-02-18 21:49:28 +00006775/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6776/// garbage collection attribute.
6777///
John McCall553d45a2011-01-12 00:34:59 +00006778Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006779 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006780 return Qualifiers::GCNone;
6781
David Blaikiebbafb8a2012-03-11 07:00:24 +00006782 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006783 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6784
6785 // Default behaviour under objective-C's gc is for ObjC pointers
6786 // (or pointers to them) be treated as though they were declared
6787 // as __strong.
6788 if (GCAttrs == Qualifiers::GCNone) {
6789 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6790 return Qualifiers::Strong;
6791 else if (Ty->isPointerType())
6792 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6793 } else {
6794 // It's not valid to set GC attributes on anything that isn't a
6795 // pointer.
6796#ifndef NDEBUG
6797 QualType CT = Ty->getCanonicalTypeInternal();
6798 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6799 CT = AT->getElementType();
6800 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6801#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006802 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006803 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006804}
6805
Chris Lattner49af6a42008-04-07 06:51:04 +00006806//===----------------------------------------------------------------------===//
6807// Type Compatibility Testing
6808//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006809
Mike Stump11289f42009-09-09 15:08:12 +00006810/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006811/// compatible.
6812static bool areCompatVectorTypes(const VectorType *LHS,
6813 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006814 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006815 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006816 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006817}
6818
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006819bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6820 QualType SecondVec) {
6821 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6822 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6823
6824 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6825 return true;
6826
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006827 // Treat Neon vector types and most AltiVec vector types as if they are the
6828 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006829 const VectorType *First = FirstVec->getAs<VectorType>();
6830 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006831 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006832 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006833 First->getVectorKind() != VectorType::AltiVecPixel &&
6834 First->getVectorKind() != VectorType::AltiVecBool &&
6835 Second->getVectorKind() != VectorType::AltiVecPixel &&
6836 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006837 return true;
6838
6839 return false;
6840}
6841
Steve Naroff8e6aee52009-07-23 01:01:38 +00006842//===----------------------------------------------------------------------===//
6843// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6844//===----------------------------------------------------------------------===//
6845
6846/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6847/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006848bool
6849ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6850 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006851 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006852 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006853 for (auto *PI : rProto->protocols())
6854 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006855 return true;
6856 return false;
6857}
6858
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006859/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6860/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006861bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6862 QualType rhs) {
6863 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6864 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6865 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6866
Aaron Ballman83731462014-03-17 16:14:00 +00006867 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006868 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006869 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006870 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6871 match = true;
6872 break;
6873 }
6874 }
6875 if (!match)
6876 return false;
6877 }
6878 return true;
6879}
6880
Steve Naroff8e6aee52009-07-23 01:01:38 +00006881/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6882/// ObjCQualifiedIDType.
6883bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6884 bool compare) {
6885 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006886 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006887 lhs->isObjCIdType() || lhs->isObjCClassType())
6888 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006889 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006890 rhs->isObjCIdType() || rhs->isObjCClassType())
6891 return true;
6892
6893 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006894 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006895
Steve Naroff8e6aee52009-07-23 01:01:38 +00006896 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006897
Steve Naroff8e6aee52009-07-23 01:01:38 +00006898 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006899 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006900 // make sure we check the class hierarchy.
6901 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006902 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006903 // when comparing an id<P> on lhs with a static type on rhs,
6904 // see if static class implements all of id's protocols, directly or
6905 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006906 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006907 return false;
6908 }
6909 }
6910 // If there are no qualifiers and no interface, we have an 'id'.
6911 return true;
6912 }
Mike Stump11289f42009-09-09 15:08:12 +00006913 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006914 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006915 bool match = false;
6916
6917 // when comparing an id<P> on lhs with a static type on rhs,
6918 // see if static class implements all of id's protocols, directly or
6919 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006920 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006921 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6922 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6923 match = true;
6924 break;
6925 }
6926 }
Mike Stump11289f42009-09-09 15:08:12 +00006927 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006928 // make sure we check the class hierarchy.
6929 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006930 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006931 // when comparing an id<P> on lhs with a static type on rhs,
6932 // see if static class implements all of id's protocols, directly or
6933 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006934 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006935 match = true;
6936 break;
6937 }
6938 }
6939 }
6940 if (!match)
6941 return false;
6942 }
Mike Stump11289f42009-09-09 15:08:12 +00006943
Steve Naroff8e6aee52009-07-23 01:01:38 +00006944 return true;
6945 }
Mike Stump11289f42009-09-09 15:08:12 +00006946
Steve Naroff8e6aee52009-07-23 01:01:38 +00006947 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6948 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6949
Mike Stump11289f42009-09-09 15:08:12 +00006950 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006951 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006952 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006953 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006954 bool match = false;
6955
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006956 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006957 // see if static class implements all of id's protocols, directly or
6958 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006959 // First, lhs protocols in the qualifier list must be found, direct
6960 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00006961 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006962 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6963 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6964 match = true;
6965 break;
6966 }
6967 }
6968 if (!match)
6969 return false;
6970 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006971
6972 // Static class's protocols, or its super class or category protocols
6973 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6974 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6975 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6976 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6977 // This is rather dubious but matches gcc's behavior. If lhs has
6978 // no type qualifier and its class has no static protocol(s)
6979 // assume that it is mismatch.
6980 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6981 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00006982 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006983 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006984 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006985 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6986 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6987 match = true;
6988 break;
6989 }
6990 }
6991 if (!match)
6992 return false;
6993 }
6994 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006995 return true;
6996 }
6997 return false;
6998}
6999
Eli Friedman47f77112008-08-22 00:56:42 +00007000/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007001/// compatible for assignment from RHS to LHS. This handles validation of any
7002/// protocol qualifiers on the LHS or RHS.
7003///
Steve Naroff7cae42b2009-07-10 23:34:53 +00007004bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
7005 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00007006 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7007 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7008
Steve Naroff1329fa02009-07-15 18:40:39 +00007009 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00007010 if (LHS->isObjCUnqualifiedIdOrClass() ||
7011 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00007012 return true;
7013
Douglas Gregorab209d82015-07-07 03:58:42 +00007014 // Function object that propagates a successful result or handles
7015 // __kindof types.
7016 auto finish = [&](bool succeeded) -> bool {
7017 if (succeeded)
7018 return true;
7019
7020 if (!RHS->isKindOfType())
7021 return false;
7022
7023 // Strip off __kindof and protocol qualifiers, then check whether
7024 // we can assign the other way.
7025 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7026 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
7027 };
7028
7029 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
7030 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7031 QualType(RHSOPT,0),
7032 false));
7033 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007034
Douglas Gregorab209d82015-07-07 03:58:42 +00007035 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
7036 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
7037 QualType(RHSOPT,0)));
7038 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007039
John McCall8b07ec22010-05-15 11:32:37 +00007040 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00007041 if (LHS->getInterface() && RHS->getInterface()) {
7042 return finish(canAssignObjCInterfaces(LHS, RHS));
7043 }
Mike Stump11289f42009-09-09 15:08:12 +00007044
Steve Naroff8e6aee52009-07-23 01:01:38 +00007045 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007046}
7047
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007048/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00007049/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007050/// arguments in block literals. When passed as arguments, passing 'A*' where
7051/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
7052/// not OK. For the return type, the opposite is not OK.
7053bool ASTContext::canAssignObjCInterfacesInBlockPointer(
7054 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007055 const ObjCObjectPointerType *RHSOPT,
7056 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007057
7058 // Function object that propagates a successful result or handles
7059 // __kindof types.
7060 auto finish = [&](bool succeeded) -> bool {
7061 if (succeeded)
7062 return true;
7063
7064 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
7065 if (!Expected->isKindOfType())
7066 return false;
7067
7068 // Strip off __kindof and protocol qualifiers, then check whether
7069 // we can assign the other way.
7070 return canAssignObjCInterfacesInBlockPointer(
7071 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7072 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
7073 BlockReturnType);
7074 };
7075
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007076 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007077 return true;
7078
7079 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007080 return finish(RHSOPT->isObjCBuiltinType() ||
7081 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007082 }
7083
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007084 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00007085 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7086 QualType(RHSOPT,0),
7087 false));
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007088
7089 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
7090 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
7091 if (LHS && RHS) { // We have 2 user-defined types.
7092 if (LHS != RHS) {
7093 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007094 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007095 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007096 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007097 }
7098 else
7099 return true;
7100 }
7101 return false;
7102}
7103
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007104/// Comparison routine for Objective-C protocols to be used with
7105/// llvm::array_pod_sort.
7106static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
7107 ObjCProtocolDecl * const *rhs) {
7108 return (*lhs)->getName().compare((*rhs)->getName());
7109
7110}
7111
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007112/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007113/// of protocols inherited from two distinct objective-c pointer objects with
7114/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007115/// It is used to build composite qualifier list of the composite type of
7116/// the conditional expression involving two objective-c pointer objects.
7117static
7118void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007119 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007120 const ObjCObjectPointerType *LHSOPT,
7121 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007122 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007123
John McCall8b07ec22010-05-15 11:32:37 +00007124 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7125 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7126 assert(LHS->getInterface() && "LHS must have an interface base");
7127 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007128
7129 // Add all of the protocols for the LHS.
7130 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
7131
7132 // Start with the protocol qualifiers.
7133 for (auto proto : LHS->quals()) {
7134 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007135 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007136
7137 // Also add the protocols associated with the LHS interface.
7138 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
7139
7140 // Add all of the protocls for the RHS.
7141 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
7142
7143 // Start with the protocol qualifiers.
7144 for (auto proto : RHS->quals()) {
7145 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007146 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007147
7148 // Also add the protocols associated with the RHS interface.
7149 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
7150
7151 // Compute the intersection of the collected protocol sets.
7152 for (auto proto : LHSProtocolSet) {
7153 if (RHSProtocolSet.count(proto))
7154 IntersectionSet.push_back(proto);
7155 }
7156
7157 // Compute the set of protocols that is implied by either the common type or
7158 // the protocols within the intersection.
7159 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7160 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7161
7162 // Remove any implied protocols from the list of inherited protocols.
7163 if (!ImpliedProtocols.empty()) {
7164 IntersectionSet.erase(
7165 std::remove_if(IntersectionSet.begin(),
7166 IntersectionSet.end(),
7167 [&](ObjCProtocolDecl *proto) -> bool {
7168 return ImpliedProtocols.count(proto) > 0;
7169 }),
7170 IntersectionSet.end());
7171 }
7172
7173 // Sort the remaining protocols by name.
7174 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7175 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007176}
7177
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007178/// Determine whether the first type is a subtype of the second.
7179static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7180 QualType rhs) {
7181 // Common case: two object pointers.
7182 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7183 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7184 if (lhsOPT && rhsOPT)
7185 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7186
7187 // Two block pointers.
7188 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7189 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7190 if (lhsBlock && rhsBlock)
7191 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7192
7193 // If either is an unqualified 'id' and the other is a block, it's
7194 // acceptable.
7195 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7196 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7197 return true;
7198
7199 return false;
7200}
7201
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007202// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007203static bool sameObjCTypeArgs(ASTContext &ctx,
7204 const ObjCInterfaceDecl *iface,
7205 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00007206 ArrayRef<QualType> rhsArgs,
7207 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007208 if (lhsArgs.size() != rhsArgs.size())
7209 return false;
7210
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007211 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007212 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007213 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7214 continue;
7215
7216 switch (typeParams->begin()[i]->getVariance()) {
7217 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00007218 if (!stripKindOf ||
7219 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7220 rhsArgs[i].stripObjCKindOfType(ctx))) {
7221 return false;
7222 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007223 break;
7224
7225 case ObjCTypeParamVariance::Covariant:
7226 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7227 return false;
7228 break;
7229
7230 case ObjCTypeParamVariance::Contravariant:
7231 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7232 return false;
7233 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00007234 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007235 }
7236
7237 return true;
7238}
7239
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007240QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007241 const ObjCObjectPointerType *Lptr,
7242 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00007243 const ObjCObjectType *LHS = Lptr->getObjectType();
7244 const ObjCObjectType *RHS = Rptr->getObjectType();
7245 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7246 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007247
7248 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007249 return QualType();
Douglas Gregore83b9562015-07-07 03:57:53 +00007250
Manman Renc46f7d12016-05-06 19:35:02 +00007251 // When either LHS or RHS is a kindof type, we should return a kindof type.
7252 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
7253 // kindof(A).
7254 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
7255
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007256 // Follow the left-hand side up the class hierarchy until we either hit a
7257 // root or find the RHS. Record the ancestors in case we don't find it.
7258 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7259 LHSAncestors;
7260 while (true) {
7261 // Record this ancestor. We'll need this if the common type isn't in the
7262 // path from the LHS to the root.
7263 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00007264
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007265 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7266 // Get the type arguments.
7267 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7268 bool anyChanges = false;
7269 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7270 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007271 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7272 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007273 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007274 return QualType();
7275 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7276 // If only one has type arguments, the result will not have type
7277 // arguments.
7278 LHSTypeArgs = { };
7279 anyChanges = true;
7280 }
7281
7282 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007283 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007284 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7285 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00007286 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007287 anyChanges = true;
7288
7289 // If anything in the LHS will have changed, build a new result type.
Manman Renc46f7d12016-05-06 19:35:02 +00007290 // If we need to return a kindof type but LHS is not a kindof type, we
7291 // build a new result type.
7292 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007293 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007294 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00007295 anyKindOf || LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007296 return getObjCObjectPointerType(Result);
7297 }
7298
7299 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007300 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007301
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007302 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00007303 QualType LHSSuperType = LHS->getSuperClassType();
7304 if (LHSSuperType.isNull())
7305 break;
7306
7307 LHS = LHSSuperType->castAs<ObjCObjectType>();
7308 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007309
7310 // We didn't find anything by following the LHS to its root; now check
7311 // the RHS against the cached set of ancestors.
7312 while (true) {
7313 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7314 if (KnownLHS != LHSAncestors.end()) {
7315 LHS = KnownLHS->second;
7316
7317 // Get the type arguments.
7318 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7319 bool anyChanges = false;
7320 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7321 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007322 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7323 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007324 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007325 return QualType();
7326 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7327 // If only one has type arguments, the result will not have type
7328 // arguments.
7329 RHSTypeArgs = { };
7330 anyChanges = true;
7331 }
7332
7333 // Compute the intersection of protocols.
7334 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7335 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7336 Protocols);
7337 if (!Protocols.empty())
7338 anyChanges = true;
7339
Manman Renc46f7d12016-05-06 19:35:02 +00007340 // If we need to return a kindof type but RHS is not a kindof type, we
7341 // build a new result type.
7342 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007343 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007344 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00007345 anyKindOf || RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007346 return getObjCObjectPointerType(Result);
7347 }
7348
7349 return getObjCObjectPointerType(QualType(RHS, 0));
7350 }
7351
7352 // Find the superclass of the RHS.
7353 QualType RHSSuperType = RHS->getSuperClassType();
7354 if (RHSSuperType.isNull())
7355 break;
7356
7357 RHS = RHSSuperType->castAs<ObjCObjectType>();
7358 }
7359
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007360 return QualType();
7361}
7362
John McCall8b07ec22010-05-15 11:32:37 +00007363bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7364 const ObjCObjectType *RHS) {
7365 assert(LHS->getInterface() && "LHS is not an interface type");
7366 assert(RHS->getInterface() && "RHS is not an interface type");
7367
Chris Lattner49af6a42008-04-07 06:51:04 +00007368 // Verify that the base decls are compatible: the RHS must be a subclass of
7369 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00007370 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7371 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7372 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00007373 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007374
Douglas Gregore83b9562015-07-07 03:57:53 +00007375 // If the LHS has protocol qualifiers, determine whether all of them are
7376 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7377 // LHS).
7378 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007379 // OK if conversion of LHS to SuperClass results in narrowing of types
7380 // ; i.e., SuperClass may implement at least one of the protocols
7381 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7382 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7383 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7384 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7385 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7386 // qualifiers.
7387 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007388 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007389 // If there is no protocols associated with RHS, it is not a match.
7390 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00007391 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007392
7393 for (const auto *LHSProto : LHS->quals()) {
7394 bool SuperImplementsProtocol = false;
7395 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7396 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7397 SuperImplementsProtocol = true;
7398 break;
7399 }
7400 if (!SuperImplementsProtocol)
7401 return false;
7402 }
Chris Lattner49af6a42008-04-07 06:51:04 +00007403 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007404
7405 // If the LHS is specialized, we may need to check type arguments.
7406 if (LHS->isSpecialized()) {
7407 // Follow the superclass chain until we've matched the LHS class in the
7408 // hierarchy. This substitutes type arguments through.
7409 const ObjCObjectType *RHSSuper = RHS;
7410 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7411 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7412
7413 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007414 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007415 !sameObjCTypeArgs(*this, LHS->getInterface(),
7416 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007417 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007418 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00007419 }
7420 }
7421
7422 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00007423}
7424
Steve Naroffb7605152009-02-12 17:52:19 +00007425bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7426 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00007427 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7428 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007429
Steve Naroff7cae42b2009-07-10 23:34:53 +00007430 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00007431 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007432
7433 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7434 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00007435}
7436
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007437bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7438 return canAssignObjCInterfaces(
7439 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7440 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7441}
7442
Mike Stump11289f42009-09-09 15:08:12 +00007443/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00007444/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00007445/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00007446/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007447bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7448 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007449 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00007450 return hasSameType(LHS, RHS);
7451
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007452 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00007453}
7454
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007455bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00007456 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007457}
7458
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007459bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7460 return !mergeTypes(LHS, RHS, true).isNull();
7461}
7462
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007463/// mergeTransparentUnionType - if T is a transparent union type and a member
7464/// of T is compatible with SubType, return the merged type, else return
7465/// QualType()
7466QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7467 bool OfBlockPointer,
7468 bool Unqualified) {
7469 if (const RecordType *UT = T->getAsUnionType()) {
7470 RecordDecl *UD = UT->getDecl();
7471 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007472 for (const auto *I : UD->fields()) {
7473 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007474 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7475 if (!MT.isNull())
7476 return MT;
7477 }
7478 }
7479 }
7480
7481 return QualType();
7482}
7483
Alp Toker9cacbab2014-01-20 20:26:09 +00007484/// mergeFunctionParameterTypes - merge two types which appear as function
7485/// parameter types
7486QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7487 bool OfBlockPointer,
7488 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007489 // GNU extension: two types are compatible if they appear as a function
7490 // argument, one of the types is a transparent union type and the other
7491 // type is compatible with a union member
7492 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7493 Unqualified);
7494 if (!lmerge.isNull())
7495 return lmerge;
7496
7497 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7498 Unqualified);
7499 if (!rmerge.isNull())
7500 return rmerge;
7501
7502 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7503}
7504
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007505QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007506 bool OfBlockPointer,
7507 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00007508 const FunctionType *lbase = lhs->getAs<FunctionType>();
7509 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007510 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7511 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00007512 bool allLTypes = true;
7513 bool allRTypes = true;
7514
7515 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007516 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00007517 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00007518 QualType RHS = rbase->getReturnType();
7519 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00007520 bool UnqualifiedResult = Unqualified;
7521 if (!UnqualifiedResult)
7522 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007523 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00007524 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007525 else
Alp Toker314cc812014-01-25 16:55:45 +00007526 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00007527 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007528 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007529
7530 if (Unqualified)
7531 retType = retType.getUnqualifiedType();
7532
Alp Toker314cc812014-01-25 16:55:45 +00007533 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7534 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007535 if (Unqualified) {
7536 LRetType = LRetType.getUnqualifiedType();
7537 RRetType = RRetType.getUnqualifiedType();
7538 }
7539
7540 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007541 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007542 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007543 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00007544
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00007545 // FIXME: double check this
7546 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7547 // rbase->getRegParmAttr() != 0 &&
7548 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00007549 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7550 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00007551
Douglas Gregor8c940862010-01-18 17:14:39 +00007552 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00007553 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00007554 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00007555
John McCall8c6b56f2010-12-15 01:06:38 +00007556 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00007557 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7558 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00007559 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7560 return QualType();
7561
John McCall31168b02011-06-15 23:02:42 +00007562 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7563 return QualType();
7564
John McCall8c6b56f2010-12-15 01:06:38 +00007565 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7566 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007567
Rafael Espindola8778c282012-11-29 16:09:03 +00007568 if (lbaseInfo.getNoReturn() != NoReturn)
7569 allLTypes = false;
7570 if (rbaseInfo.getNoReturn() != NoReturn)
7571 allRTypes = false;
7572
John McCall31168b02011-06-15 23:02:42 +00007573 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007574
Eli Friedman47f77112008-08-22 00:56:42 +00007575 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007576 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7577 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00007578 // Compatible functions must have the same number of parameters
7579 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00007580 return QualType();
7581
7582 // Variadic and non-variadic functions aren't compatible
7583 if (lproto->isVariadic() != rproto->isVariadic())
7584 return QualType();
7585
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007586 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7587 return QualType();
7588
John McCall18afab72016-03-01 00:49:02 +00007589 if (!doFunctionTypesMatchOnExtParameterInfos(rproto, lproto))
Fariborz Jahanian97676972011-09-28 21:52:05 +00007590 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00007591
7592 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007593 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007594 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7595 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7596 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7597 QualType paramType = mergeFunctionParameterTypes(
7598 lParamType, rParamType, OfBlockPointer, Unqualified);
7599 if (paramType.isNull())
7600 return QualType();
7601
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007602 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007603 paramType = paramType.getUnqualifiedType();
7604
7605 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007606 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007607 lParamType = lParamType.getUnqualifiedType();
7608 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007609 }
Alp Toker601b22c2014-01-21 23:35:24 +00007610
7611 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007612 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007613 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007614 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007615 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007616
Eli Friedman47f77112008-08-22 00:56:42 +00007617 if (allLTypes) return lhs;
7618 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007619
7620 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7621 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007622 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007623 }
7624
7625 if (lproto) allRTypes = false;
7626 if (rproto) allLTypes = false;
7627
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007628 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007629 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007630 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007631 if (proto->isVariadic()) return QualType();
7632 // Check that the types are compatible with the types that
7633 // would result from default argument promotions (C99 6.7.5.3p15).
7634 // The only types actually affected are promotable integer
7635 // types and floats, which would be passed as a different
7636 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007637 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7638 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007639
Eli Friedman448ce402012-08-30 00:44:15 +00007640 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007641 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007642 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7643 paramTy = Enum->getDecl()->getIntegerType();
7644 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007645 return QualType();
7646 }
Alp Toker601b22c2014-01-21 23:35:24 +00007647
7648 if (paramTy->isPromotableIntegerType() ||
7649 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007650 return QualType();
7651 }
7652
7653 if (allLTypes) return lhs;
7654 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007655
7656 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7657 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007658 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007659 }
7660
7661 if (allLTypes) return lhs;
7662 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007663 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007664}
7665
John McCall433c2e62013-03-21 00:10:07 +00007666/// Given that we have an enum type and a non-enum type, try to merge them.
7667static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7668 QualType other, bool isBlockReturnType) {
7669 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7670 // a signed integer type, or an unsigned integer type.
7671 // Compatibility is based on the underlying type, not the promotion
7672 // type.
7673 QualType underlyingType = ET->getDecl()->getIntegerType();
7674 if (underlyingType.isNull()) return QualType();
7675 if (Context.hasSameType(underlyingType, other))
7676 return other;
7677
7678 // In block return types, we're more permissive and accept any
7679 // integral type of the same size.
7680 if (isBlockReturnType && other->isIntegerType() &&
7681 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7682 return other;
7683
7684 return QualType();
7685}
7686
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007687QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007688 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007689 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007690 // C++ [expr]: If an expression initially has the type "reference to T", the
7691 // type is adjusted to "T" prior to any further analysis, the expression
7692 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007693 // expression is an lvalue unless the reference is an rvalue reference and
7694 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007695 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7696 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007697
7698 if (Unqualified) {
7699 LHS = LHS.getUnqualifiedType();
7700 RHS = RHS.getUnqualifiedType();
7701 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007702
Eli Friedman47f77112008-08-22 00:56:42 +00007703 QualType LHSCan = getCanonicalType(LHS),
7704 RHSCan = getCanonicalType(RHS);
7705
7706 // If two types are identical, they are compatible.
7707 if (LHSCan == RHSCan)
7708 return LHS;
7709
John McCall8ccfcb52009-09-24 19:53:00 +00007710 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007711 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7712 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007713 if (LQuals != RQuals) {
Yaxun Liua1a87ad2016-04-12 19:43:36 +00007714 if (getLangOpts().OpenCL) {
Yaxun Liuab933942016-04-28 17:34:57 +00007715 if (LHSCan.getUnqualifiedType() != RHSCan.getUnqualifiedType() ||
Yaxun Liua1a87ad2016-04-12 19:43:36 +00007716 LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers())
7717 return QualType();
7718 if (LQuals.isAddressSpaceSupersetOf(RQuals))
7719 return LHS;
7720 if (RQuals.isAddressSpaceSupersetOf(LQuals))
7721 return RHS;
7722 }
John McCall8ccfcb52009-09-24 19:53:00 +00007723 // If any of these qualifiers are different, we have a type
7724 // mismatch.
7725 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007726 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7727 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007728 return QualType();
7729
7730 // Exactly one GC qualifier difference is allowed: __strong is
7731 // okay if the other type has no GC qualifier but is an Objective
7732 // C object pointer (i.e. implicitly strong by default). We fix
7733 // this by pretending that the unqualified type was actually
7734 // qualified __strong.
7735 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7736 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7737 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7738
7739 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7740 return QualType();
7741
7742 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7743 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7744 }
7745 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7746 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7747 }
Eli Friedman47f77112008-08-22 00:56:42 +00007748 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007749 }
7750
7751 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007752
Eli Friedmandcca6332009-06-01 01:22:52 +00007753 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7754 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007755
Chris Lattnerfd652912008-01-14 05:45:46 +00007756 // We want to consider the two function types to be the same for these
7757 // comparisons, just force one to the other.
7758 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7759 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007760
7761 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007762 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7763 LHSClass = Type::ConstantArray;
7764 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7765 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007766
John McCall8b07ec22010-05-15 11:32:37 +00007767 // ObjCInterfaces are just specialized ObjCObjects.
7768 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7769 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7770
Nate Begemance4d7fc2008-04-18 23:10:10 +00007771 // Canonicalize ExtVector -> Vector.
7772 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7773 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007774
Chris Lattner95554662008-04-07 05:43:21 +00007775 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007776 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007777 // Note that we only have special rules for turning block enum
7778 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007779 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007780 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007781 }
John McCall9dd450b2009-09-21 23:43:11 +00007782 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007783 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007784 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007785 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007786 if (OfBlockPointer && !BlockReturnType) {
7787 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7788 return LHS;
7789 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7790 return RHS;
7791 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007792
Eli Friedman47f77112008-08-22 00:56:42 +00007793 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007794 }
Eli Friedman47f77112008-08-22 00:56:42 +00007795
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007796 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007797 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007798#define TYPE(Class, Base)
7799#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007800#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007801#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7802#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7803#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007804 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007805
Richard Smith27d807c2013-04-30 13:56:41 +00007806 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007807 case Type::LValueReference:
7808 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007809 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007810 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007811
John McCall8b07ec22010-05-15 11:32:37 +00007812 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007813 case Type::IncompleteArray:
7814 case Type::VariableArray:
7815 case Type::FunctionProto:
7816 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007817 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007818
Chris Lattnerfd652912008-01-14 05:45:46 +00007819 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007820 {
7821 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007822 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7823 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007824 if (Unqualified) {
7825 LHSPointee = LHSPointee.getUnqualifiedType();
7826 RHSPointee = RHSPointee.getUnqualifiedType();
7827 }
7828 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7829 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007830 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007831 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007832 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007833 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007834 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007835 return getPointerType(ResultType);
7836 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007837 case Type::BlockPointer:
7838 {
7839 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007840 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7841 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007842 if (Unqualified) {
7843 LHSPointee = LHSPointee.getUnqualifiedType();
7844 RHSPointee = RHSPointee.getUnqualifiedType();
7845 }
7846 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7847 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007848 if (ResultType.isNull()) return QualType();
7849 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7850 return LHS;
7851 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7852 return RHS;
7853 return getBlockPointerType(ResultType);
7854 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007855 case Type::Atomic:
7856 {
7857 // Merge two pointer types, while trying to preserve typedef info
7858 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7859 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7860 if (Unqualified) {
7861 LHSValue = LHSValue.getUnqualifiedType();
7862 RHSValue = RHSValue.getUnqualifiedType();
7863 }
7864 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7865 Unqualified);
7866 if (ResultType.isNull()) return QualType();
7867 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7868 return LHS;
7869 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7870 return RHS;
7871 return getAtomicType(ResultType);
7872 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007873 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007874 {
7875 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7876 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7877 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7878 return QualType();
7879
7880 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7881 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007882 if (Unqualified) {
7883 LHSElem = LHSElem.getUnqualifiedType();
7884 RHSElem = RHSElem.getUnqualifiedType();
7885 }
7886
7887 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007888 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007889 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7890 return LHS;
7891 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7892 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007893 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7894 ArrayType::ArraySizeModifier(), 0);
7895 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7896 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007897 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7898 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007899 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7900 return LHS;
7901 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7902 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007903 if (LVAT) {
7904 // FIXME: This isn't correct! But tricky to implement because
7905 // the array's size has to be the size of LHS, but the type
7906 // has to be different.
7907 return LHS;
7908 }
7909 if (RVAT) {
7910 // FIXME: This isn't correct! But tricky to implement because
7911 // the array's size has to be the size of RHS, but the type
7912 // has to be different.
7913 return RHS;
7914 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007915 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7916 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007917 return getIncompleteArrayType(ResultType,
7918 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007919 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007920 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007921 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007922 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007923 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007924 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007925 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007926 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007927 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007928 case Type::Complex:
7929 // Distinct complex types are incompatible.
7930 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007931 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007932 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007933 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7934 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007935 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007936 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007937 case Type::ObjCObject: {
7938 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007939 // FIXME: This should be type compatibility, e.g. whether
7940 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007941 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7942 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7943 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007944 return LHS;
7945
Eli Friedman47f77112008-08-22 00:56:42 +00007946 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007947 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007948 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007949 if (OfBlockPointer) {
7950 if (canAssignObjCInterfacesInBlockPointer(
7951 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007952 RHS->getAs<ObjCObjectPointerType>(),
7953 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007954 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007955 return QualType();
7956 }
John McCall9dd450b2009-09-21 23:43:11 +00007957 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7958 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007959 return LHS;
7960
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007961 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007962 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00007963 case Type::Pipe:
7964 {
7965 // Merge two pointer types, while trying to preserve typedef info
7966 QualType LHSValue = LHS->getAs<PipeType>()->getElementType();
7967 QualType RHSValue = RHS->getAs<PipeType>()->getElementType();
7968 if (Unqualified) {
7969 LHSValue = LHSValue.getUnqualifiedType();
7970 RHSValue = RHSValue.getUnqualifiedType();
7971 }
7972 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7973 Unqualified);
7974 if (ResultType.isNull()) return QualType();
7975 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7976 return LHS;
7977 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7978 return RHS;
7979 return getPipeType(ResultType);
7980 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007981 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007982
David Blaikie8a40f702012-01-17 06:56:22 +00007983 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007984}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007985
John McCall18afab72016-03-01 00:49:02 +00007986bool ASTContext::doFunctionTypesMatchOnExtParameterInfos(
7987 const FunctionProtoType *firstFnType,
7988 const FunctionProtoType *secondFnType) {
7989 // Fast path: if the first type doesn't have ext parameter infos,
7990 // we match if and only if they second type also doesn't have them.
7991 if (!firstFnType->hasExtParameterInfos())
7992 return !secondFnType->hasExtParameterInfos();
7993
7994 // Otherwise, we can only match if the second type has them.
7995 if (!secondFnType->hasExtParameterInfos())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007996 return false;
John McCall18afab72016-03-01 00:49:02 +00007997
7998 auto firstEPI = firstFnType->getExtParameterInfos();
7999 auto secondEPI = secondFnType->getExtParameterInfos();
8000 assert(firstEPI.size() == secondEPI.size());
8001
8002 for (size_t i = 0, n = firstEPI.size(); i != n; ++i) {
8003 if (firstEPI[i] != secondEPI[i])
8004 return false;
8005 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00008006 return true;
8007}
8008
Chandler Carruth21c90602015-12-30 03:24:14 +00008009void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
8010 ObjCLayouts[CD] = nullptr;
8011}
8012
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008013/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
8014/// 'RHS' attributes and returns the merged version; including for function
8015/// return types.
8016QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
8017 QualType LHSCan = getCanonicalType(LHS),
8018 RHSCan = getCanonicalType(RHS);
8019 // If two types are identical, they are compatible.
8020 if (LHSCan == RHSCan)
8021 return LHS;
8022 if (RHSCan->isFunctionType()) {
8023 if (!LHSCan->isFunctionType())
8024 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00008025 QualType OldReturnType =
8026 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008027 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00008028 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008029 QualType ResReturnType =
8030 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
8031 if (ResReturnType.isNull())
8032 return QualType();
8033 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
8034 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
8035 // In either case, use OldReturnType to build the new function type.
8036 const FunctionType *F = LHS->getAs<FunctionType>();
8037 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008038 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8039 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00008040 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00008041 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008042 return ResultType;
8043 }
8044 }
8045 return QualType();
8046 }
8047
8048 // If the qualifiers are different, the types can still be merged.
8049 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8050 Qualifiers RQuals = RHSCan.getLocalQualifiers();
8051 if (LQuals != RQuals) {
8052 // If any of these qualifiers are different, we have a type mismatch.
8053 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
8054 LQuals.getAddressSpace() != RQuals.getAddressSpace())
8055 return QualType();
8056
8057 // Exactly one GC qualifier difference is allowed: __strong is
8058 // okay if the other type has no GC qualifier but is an Objective
8059 // C object pointer (i.e. implicitly strong by default). We fix
8060 // this by pretending that the unqualified type was actually
8061 // qualified __strong.
8062 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8063 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8064 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8065
8066 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8067 return QualType();
8068
8069 if (GC_L == Qualifiers::Strong)
8070 return LHS;
8071 if (GC_R == Qualifiers::Strong)
8072 return RHS;
8073 return QualType();
8074 }
8075
8076 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
8077 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8078 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8079 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
8080 if (ResQT == LHSBaseQT)
8081 return LHS;
8082 if (ResQT == RHSBaseQT)
8083 return RHS;
8084 }
8085 return QualType();
8086}
8087
Chris Lattner4ba0cef2008-04-07 07:01:58 +00008088//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008089// Integer Predicates
8090//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00008091
Jay Foad39c79802011-01-12 09:06:06 +00008092unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00008093 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00008094 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00008095 if (T->isBooleanType())
8096 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00008097 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008098 return (unsigned)getTypeSize(T);
8099}
8100
Abramo Bagnara13640492012-09-09 10:21:24 +00008101QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00008102 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00008103
8104 // Turn <4 x signed int> -> <4 x unsigned int>
8105 if (const VectorType *VTy = T->getAs<VectorType>())
8106 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00008107 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00008108
8109 // For enums, we return the unsigned version of the base type.
8110 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008111 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00008112
8113 const BuiltinType *BTy = T->getAs<BuiltinType>();
8114 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008115 switch (BTy->getKind()) {
8116 case BuiltinType::Char_S:
8117 case BuiltinType::SChar:
8118 return UnsignedCharTy;
8119 case BuiltinType::Short:
8120 return UnsignedShortTy;
8121 case BuiltinType::Int:
8122 return UnsignedIntTy;
8123 case BuiltinType::Long:
8124 return UnsignedLongTy;
8125 case BuiltinType::LongLong:
8126 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00008127 case BuiltinType::Int128:
8128 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008129 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008130 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008131 }
8132}
8133
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00008134ASTMutationListener::~ASTMutationListener() { }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00008135
Richard Smith1fa5d642013-05-11 05:45:24 +00008136void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
8137 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00008138
8139//===----------------------------------------------------------------------===//
8140// Builtin Type Computation
8141//===----------------------------------------------------------------------===//
8142
8143/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00008144/// pointer over the consumed characters. This returns the resultant type. If
8145/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
8146/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
8147/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008148///
8149/// RequiresICE is filled in on return to indicate whether the value is required
8150/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00008151static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00008152 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008153 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00008154 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00008155 // Modifiers.
8156 int HowLong = 0;
8157 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008158 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00008159
Chris Lattnerdc226c22010-10-01 22:42:38 +00008160 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00008161 bool Done = false;
8162 while (!Done) {
8163 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00008164 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00008165 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008166 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00008167 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008168 case 'S':
8169 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
8170 assert(!Signed && "Can't use 'S' modifier multiple times!");
8171 Signed = true;
8172 break;
8173 case 'U':
8174 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00008175 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008176 Unsigned = true;
8177 break;
8178 case 'L':
8179 assert(HowLong <= 2 && "Can't have LLLL modifier");
8180 ++HowLong;
8181 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00008182 case 'W':
8183 // This modifier represents int64 type.
8184 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
8185 switch (Context.getTargetInfo().getInt64Type()) {
8186 default:
8187 llvm_unreachable("Unexpected integer type");
8188 case TargetInfo::SignedLong:
8189 HowLong = 1;
8190 break;
8191 case TargetInfo::SignedLongLong:
8192 HowLong = 2;
8193 break;
8194 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00008195 }
8196 }
8197
8198 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00008199
Chris Lattnerecd79c62009-06-14 00:45:47 +00008200 // Read the base type.
8201 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00008202 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008203 case 'v':
8204 assert(HowLong == 0 && !Signed && !Unsigned &&
8205 "Bad modifiers used with 'v'!");
8206 Type = Context.VoidTy;
8207 break;
Jack Carter24bef982013-08-15 15:16:57 +00008208 case 'h':
8209 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00008210 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00008211 Type = Context.HalfTy;
8212 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008213 case 'f':
8214 assert(HowLong == 0 && !Signed && !Unsigned &&
8215 "Bad modifiers used with 'f'!");
8216 Type = Context.FloatTy;
8217 break;
8218 case 'd':
8219 assert(HowLong < 2 && !Signed && !Unsigned &&
8220 "Bad modifiers used with 'd'!");
8221 if (HowLong)
8222 Type = Context.LongDoubleTy;
8223 else
8224 Type = Context.DoubleTy;
8225 break;
8226 case 's':
8227 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8228 if (Unsigned)
8229 Type = Context.UnsignedShortTy;
8230 else
8231 Type = Context.ShortTy;
8232 break;
8233 case 'i':
8234 if (HowLong == 3)
8235 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8236 else if (HowLong == 2)
8237 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8238 else if (HowLong == 1)
8239 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8240 else
8241 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8242 break;
8243 case 'c':
8244 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8245 if (Signed)
8246 Type = Context.SignedCharTy;
8247 else if (Unsigned)
8248 Type = Context.UnsignedCharTy;
8249 else
8250 Type = Context.CharTy;
8251 break;
8252 case 'b': // boolean
8253 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8254 Type = Context.BoolTy;
8255 break;
8256 case 'z': // size_t.
8257 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8258 Type = Context.getSizeType();
8259 break;
8260 case 'F':
8261 Type = Context.getCFConstantStringType();
8262 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00008263 case 'G':
8264 Type = Context.getObjCIdType();
8265 break;
8266 case 'H':
8267 Type = Context.getObjCSelType();
8268 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00008269 case 'M':
8270 Type = Context.getObjCSuperType();
8271 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008272 case 'a':
8273 Type = Context.getBuiltinVaListType();
8274 assert(!Type.isNull() && "builtin va list type not initialized!");
8275 break;
8276 case 'A':
8277 // This is a "reference" to a va_list; however, what exactly
8278 // this means depends on how va_list is defined. There are two
8279 // different kinds of va_list: ones passed by value, and ones
8280 // passed by reference. An example of a by-value va_list is
8281 // x86, where va_list is a char*. An example of by-ref va_list
8282 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8283 // we want this argument to be a char*&; for x86-64, we want
8284 // it to be a __va_list_tag*.
8285 Type = Context.getBuiltinVaListType();
8286 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008287 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00008288 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008289 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00008290 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008291 break;
8292 case 'V': {
8293 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008294 unsigned NumElements = strtoul(Str, &End, 10);
8295 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008296 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00008297
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008298 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8299 RequiresICE, false);
8300 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00008301
8302 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00008303 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00008304 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008305 break;
8306 }
Douglas Gregorfed66992012-06-07 18:08:25 +00008307 case 'E': {
8308 char *End;
8309
8310 unsigned NumElements = strtoul(Str, &End, 10);
8311 assert(End != Str && "Missing vector size");
8312
8313 Str = End;
8314
8315 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8316 false);
8317 Type = Context.getExtVectorType(ElementType, NumElements);
8318 break;
8319 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008320 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008321 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8322 false);
8323 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008324 Type = Context.getComplexType(ElementType);
8325 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00008326 }
8327 case 'Y' : {
8328 Type = Context.getPointerDiffType();
8329 break;
8330 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00008331 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00008332 Type = Context.getFILEType();
8333 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008334 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008335 return QualType();
8336 }
Mike Stump2adb4da2009-07-28 23:47:15 +00008337 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00008338 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00008339 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00008340 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00008341 else
8342 Type = Context.getjmp_bufType();
8343
Mike Stump2adb4da2009-07-28 23:47:15 +00008344 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008345 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00008346 return QualType();
8347 }
8348 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00008349 case 'K':
8350 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8351 Type = Context.getucontext_tType();
8352
8353 if (Type.isNull()) {
8354 Error = ASTContext::GE_Missing_ucontext;
8355 return QualType();
8356 }
8357 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00008358 case 'p':
8359 Type = Context.getProcessIDType();
8360 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00008361 }
Mike Stump11289f42009-09-09 15:08:12 +00008362
Chris Lattnerdc226c22010-10-01 22:42:38 +00008363 // If there are modifiers and if we're allowed to parse them, go for it.
8364 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008365 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00008366 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00008367 default: Done = true; --Str; break;
8368 case '*':
8369 case '&': {
8370 // Both pointers and references can have their pointee types
8371 // qualified with an address space.
8372 char *End;
8373 unsigned AddrSpace = strtoul(Str, &End, 10);
8374 if (End != Str && AddrSpace != 0) {
8375 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
8376 Str = End;
8377 }
8378 if (c == '*')
8379 Type = Context.getPointerType(Type);
8380 else
8381 Type = Context.getLValueReferenceType(Type);
8382 break;
8383 }
8384 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8385 case 'C':
8386 Type = Type.withConst();
8387 break;
8388 case 'D':
8389 Type = Context.getVolatileType(Type);
8390 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00008391 case 'R':
8392 Type = Type.withRestrict();
8393 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008394 }
8395 }
Chris Lattner84733392010-10-01 07:13:18 +00008396
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008397 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00008398 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00008399
Chris Lattnerecd79c62009-06-14 00:45:47 +00008400 return Type;
8401}
8402
8403/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00008404QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008405 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00008406 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00008407 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00008408
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008409 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00008410
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008411 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008412 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008413 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8414 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008415 if (Error != GE_None)
8416 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008417
8418 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8419
Chris Lattnerecd79c62009-06-14 00:45:47 +00008420 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008421 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008422 if (Error != GE_None)
8423 return QualType();
8424
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008425 // If this argument is required to be an IntegerConstantExpression and the
8426 // caller cares, fill in the bitmask we return.
8427 if (RequiresICE && IntegerConstantArgs)
8428 *IntegerConstantArgs |= 1 << ArgTypes.size();
8429
Chris Lattnerecd79c62009-06-14 00:45:47 +00008430 // Do array -> pointer decay. The builtin should use the decayed type.
8431 if (Ty->isArrayType())
8432 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00008433
Chris Lattnerecd79c62009-06-14 00:45:47 +00008434 ArgTypes.push_back(Ty);
8435 }
8436
David Majnemerba3e5ec2015-03-13 18:26:17 +00008437 if (Id == Builtin::BI__GetExceptionInfo)
8438 return QualType();
8439
Chris Lattnerecd79c62009-06-14 00:45:47 +00008440 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8441 "'.' should only occur at end of builtin type list!");
8442
Reid Kleckner78af0702013-08-27 23:08:25 +00008443 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00008444 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8445
8446 bool Variadic = (TypeStr[0] == '.');
8447
8448 // We really shouldn't be making a no-proto type here, especially in C++.
8449 if (ArgTypes.empty() && Variadic)
8450 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00008451
John McCalldb40c7f2010-12-14 08:05:40 +00008452 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00008453 EPI.ExtInfo = EI;
8454 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00008455
Jordan Rose5c382722013-03-08 21:51:21 +00008456 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008457}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00008458
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008459static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8460 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008461 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008462 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008463
Rafael Espindola3ae00052013-05-13 00:12:11 +00008464 GVALinkage External = GVA_StrongExternal;
8465 switch (FD->getTemplateSpecializationKind()) {
8466 case TSK_Undeclared:
8467 case TSK_ExplicitSpecialization:
8468 External = GVA_StrongExternal;
8469 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008470
Rafael Espindola3ae00052013-05-13 00:12:11 +00008471 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008472 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008473
David Majnemerc3d07332014-05-15 06:25:57 +00008474 // C++11 [temp.explicit]p10:
8475 // [ Note: The intent is that an inline function that is the subject of
8476 // an explicit instantiation declaration will still be implicitly
8477 // instantiated when used so that the body can be considered for
8478 // inlining, but that no out-of-line copy of the inline function would be
8479 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00008480 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00008481 return GVA_AvailableExternally;
8482
Rafael Espindola3ae00052013-05-13 00:12:11 +00008483 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008484 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008485 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008486 }
8487
8488 if (!FD->isInlined())
8489 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00008490
David Majnemer3f021502015-10-08 04:53:31 +00008491 if ((!Context.getLangOpts().CPlusPlus &&
8492 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008493 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00008494 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008495 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8496
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008497 // GNU or C99 inline semantics. Determine whether this symbol should be
8498 // externally visible.
8499 if (FD->isInlineDefinitionExternallyVisible())
8500 return External;
8501
8502 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00008503 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008504 }
8505
David Majnemer54e3ba52014-04-02 23:17:29 +00008506 // Functions specified with extern and inline in -fms-compatibility mode
8507 // forcibly get emitted. While the body of the function cannot be later
8508 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00008509 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00008510 return GVA_StrongODR;
8511
David Majnemer27d69db2014-04-28 22:17:59 +00008512 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008513}
8514
Artem Belevichca2b9512016-05-02 20:30:03 +00008515static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
8516 GVALinkage L, const Decl *D) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008517 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8518 // dllexport/dllimport on inline functions.
8519 if (D->hasAttr<DLLImportAttr>()) {
8520 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8521 return GVA_AvailableExternally;
Artem Belevichca2b9512016-05-02 20:30:03 +00008522 } else if (D->hasAttr<DLLExportAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008523 if (L == GVA_DiscardableODR)
8524 return GVA_StrongODR;
Artem Belevichca2b9512016-05-02 20:30:03 +00008525 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
8526 D->hasAttr<CUDAGlobalAttr>()) {
8527 // Device-side functions with __global__ attribute must always be
8528 // visible externally so they can be launched from host.
8529 if (L == GVA_DiscardableODR || L == GVA_Internal)
8530 return GVA_StrongODR;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008531 }
8532 return L;
8533}
8534
8535GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
Artem Belevichca2b9512016-05-02 20:30:03 +00008536 return adjustGVALinkageForAttributes(
8537 *this, basicGVALinkageForFunction(*this, FD), FD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008538}
8539
8540static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8541 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008542 if (!VD->isExternallyVisible())
8543 return GVA_Internal;
8544
David Majnemer27d69db2014-04-28 22:17:59 +00008545 if (VD->isStaticLocal()) {
8546 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
8547 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8548 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8549 LexicalContext = LexicalContext->getLexicalParent();
8550
Richard Smith9e2341d2015-03-23 03:25:59 +00008551 // Let the static local variable inherit its linkage from the nearest
David Majnemer27d69db2014-04-28 22:17:59 +00008552 // enclosing function.
8553 if (LexicalContext)
8554 StaticLocalLinkage =
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008555 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
David Majnemer27d69db2014-04-28 22:17:59 +00008556
8557 // GVA_StrongODR function linkage is stronger than what we need,
8558 // downgrade to GVA_DiscardableODR.
8559 // This allows us to discard the variable if we never end up needing it.
8560 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
8561 : StaticLocalLinkage;
8562 }
8563
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008564 // MSVC treats in-class initialized static data members as definitions.
8565 // By giving them non-strong linkage, out-of-line definitions won't
8566 // cause link errors.
8567 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8568 return GVA_DiscardableODR;
8569
Richard Smithd9b90092016-07-02 01:32:16 +00008570 // Most non-template variables have strong linkage; inline variables are
8571 // linkonce_odr or (occasionally, for compatibility) weak_odr.
8572 GVALinkage StrongLinkage;
8573 switch (Context.getInlineVariableDefinitionKind(VD)) {
8574 case ASTContext::InlineVariableDefinitionKind::None:
8575 StrongLinkage = GVA_StrongExternal;
8576 break;
8577 case ASTContext::InlineVariableDefinitionKind::Weak:
8578 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
Richard Smith62f19e72016-06-25 00:15:56 +00008579 StrongLinkage = GVA_DiscardableODR;
Richard Smithd9b90092016-07-02 01:32:16 +00008580 break;
8581 case ASTContext::InlineVariableDefinitionKind::Strong:
8582 StrongLinkage = GVA_StrongODR;
8583 break;
8584 }
Richard Smith62f19e72016-06-25 00:15:56 +00008585
Richard Smith8809a0c2013-09-27 20:14:12 +00008586 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008587 case TSK_Undeclared:
Richard Smith62f19e72016-06-25 00:15:56 +00008588 return StrongLinkage;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008589
David Majnemer6d1780c2015-07-17 23:36:49 +00008590 case TSK_ExplicitSpecialization:
David Majnemer3f021502015-10-08 04:53:31 +00008591 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8592 VD->isStaticDataMember()
David Majnemer6d1780c2015-07-17 23:36:49 +00008593 ? GVA_StrongODR
Richard Smith62f19e72016-06-25 00:15:56 +00008594 : StrongLinkage;
David Majnemer6d1780c2015-07-17 23:36:49 +00008595
Rafael Espindola3ae00052013-05-13 00:12:11 +00008596 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008597 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008598
David Majnemer27d69db2014-04-28 22:17:59 +00008599 case TSK_ExplicitInstantiationDeclaration:
8600 return GVA_AvailableExternally;
8601
Rafael Espindola3ae00052013-05-13 00:12:11 +00008602 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008603 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008604 }
Rafael Espindola27699c82013-05-13 14:05:53 +00008605
8606 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008607}
8608
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008609GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Artem Belevichca2b9512016-05-02 20:30:03 +00008610 return adjustGVALinkageForAttributes(
8611 *this, basicGVALinkageForVariable(*this, VD), VD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008612}
8613
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00008614bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008615 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8616 if (!VD->isFileVarDecl())
8617 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00008618 // Global named register variables (GNU extension) are never emitted.
8619 if (VD->getStorageClass() == SC_Register)
8620 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00008621 if (VD->getDescribedVarTemplate() ||
8622 isa<VarTemplatePartialSpecializationDecl>(VD))
8623 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00008624 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8625 // We never need to emit an uninstantiated function template.
8626 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8627 return false;
Nico Weber66220292016-03-02 17:28:48 +00008628 } else if (isa<PragmaCommentDecl>(D))
8629 return true;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00008630 else if (isa<OMPThreadPrivateDecl>(D) ||
8631 D->hasAttr<OMPDeclareTargetDeclAttr>())
8632 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +00008633 else if (isa<PragmaDetectMismatchDecl>(D))
8634 return true;
Nico Weber66220292016-03-02 17:28:48 +00008635 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00008636 return !D->getDeclContext()->isDependentContext();
8637 else if (isa<OMPDeclareReductionDecl>(D))
8638 return !D->getDeclContext()->isDependentContext();
Richard Smithdc1f0422016-07-20 19:10:16 +00008639 else if (isa<ImportDecl>(D))
8640 return true;
Alexey Bataev97720002014-11-11 04:05:39 +00008641 else
Richard Smith5205a8c2013-04-01 20:22:16 +00008642 return false;
8643
8644 // If this is a member of a class template, we do not need to emit it.
8645 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008646 return false;
8647
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008648 // Weak references don't produce any output by themselves.
8649 if (D->hasAttr<WeakRefAttr>())
8650 return false;
8651
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008652 // Aliases and used decls are required.
8653 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8654 return true;
8655
8656 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8657 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00008658 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00008659 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008660
8661 // Constructors and destructors are required.
8662 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8663 return true;
8664
John McCall6bd2a892013-01-25 22:31:03 +00008665 // The key function for a class is required. This rule only comes
8666 // into play when inline functions can be key functions, though.
8667 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8668 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8669 const CXXRecordDecl *RD = MD->getParent();
8670 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8671 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8672 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8673 return true;
8674 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008675 }
8676 }
8677
8678 GVALinkage Linkage = GetGVALinkageForFunction(FD);
8679
8680 // static, static inline, always_inline, and extern inline functions can
8681 // always be deferred. Normal inline functions can be deferred in C99/C++.
8682 // Implicit template instantiations can also be deferred in C++.
David Majnemer27d69db2014-04-28 22:17:59 +00008683 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8684 Linkage == GVA_DiscardableODR)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008685 return false;
8686 return true;
8687 }
Douglas Gregor87d81242011-09-10 00:22:34 +00008688
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008689 const VarDecl *VD = cast<VarDecl>(D);
8690 assert(VD->isFileVarDecl() && "Expected file scoped var");
8691
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008692 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8693 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008694 return false;
8695
Richard Smitha0e5e542012-11-12 21:38:00 +00008696 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008697 GVALinkage L = GetGVALinkageForVariable(VD);
David Majnemerc3d07332014-05-15 06:25:57 +00008698 if (L != GVA_Internal && L != GVA_AvailableExternally &&
8699 L != GVA_DiscardableODR)
Richard Smitha0e5e542012-11-12 21:38:00 +00008700 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008701
Richard Smitha0e5e542012-11-12 21:38:00 +00008702 // Variables that have destruction with side-effects are required.
8703 if (VD->getType().isDestructedType())
8704 return true;
8705
8706 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00008707 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
8708 !VD->evaluateValue())
Richard Smitha0e5e542012-11-12 21:38:00 +00008709 return true;
8710
8711 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008712}
Charles Davis53c59df2010-08-16 03:33:14 +00008713
Reid Kleckner78af0702013-08-27 23:08:25 +00008714CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8715 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00008716 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00008717 if (IsCXXMethod)
8718 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00008719
Alexey Bataeva7547182016-05-18 09:06:38 +00008720 switch (LangOpts.getDefaultCallingConv()) {
8721 case LangOptions::DCC_None:
8722 break;
8723 case LangOptions::DCC_CDecl:
8724 return CC_C;
8725 case LangOptions::DCC_FastCall:
8726 if (getTargetInfo().hasFeature("sse2"))
8727 return CC_X86FastCall;
8728 break;
8729 case LangOptions::DCC_StdCall:
8730 if (!IsVariadic)
8731 return CC_X86StdCall;
8732 break;
8733 case LangOptions::DCC_VectorCall:
8734 // __vectorcall cannot be applied to variadic functions.
8735 if (!IsVariadic)
8736 return CC_X86VectorCall;
8737 break;
8738 }
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00008739 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00008740}
8741
Jay Foad39c79802011-01-12 09:06:06 +00008742bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00008743 // Pass through to the C++ ABI object
8744 return ABI->isNearlyEmpty(RD);
8745}
8746
Reid Kleckner96f8f932014-02-05 17:27:08 +00008747VTableContextBase *ASTContext::getVTableContext() {
8748 if (!VTContext.get()) {
8749 if (Target->getCXXABI().isMicrosoft())
8750 VTContext.reset(new MicrosoftVTableContext(*this));
8751 else
8752 VTContext.reset(new ItaniumVTableContext(*this));
8753 }
8754 return VTContext.get();
8755}
8756
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008757MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00008758 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00008759 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00008760 case TargetCXXABI::GenericItanium:
8761 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00008762 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00008763 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00008764 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00008765 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +00008766 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008767 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00008768 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008769 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008770 }
David Blaikie83d382b2011-09-23 05:06:16 +00008771 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008772}
8773
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00008774CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008775
8776size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00008777 return ASTRecordLayouts.getMemorySize() +
8778 llvm::capacity_in_bytes(ObjCLayouts) +
8779 llvm::capacity_in_bytes(KeyFunctions) +
8780 llvm::capacity_in_bytes(ObjCImpls) +
8781 llvm::capacity_in_bytes(BlockVarCopyInits) +
8782 llvm::capacity_in_bytes(DeclAttrs) +
8783 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8784 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8785 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8786 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8787 llvm::capacity_in_bytes(OverriddenMethods) +
8788 llvm::capacity_in_bytes(Types) +
8789 llvm::capacity_in_bytes(VariableArrayTypes) +
8790 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008791}
Ted Kremenek540017e2011-10-06 05:00:56 +00008792
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008793/// getIntTypeForBitwidth -
8794/// sets integer QualTy according to specified details:
8795/// bitwidth, signed/unsigned.
8796/// Returns empty type if there is no appropriate target types.
8797QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8798 unsigned Signed) const {
8799 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8800 CanQualType QualTy = getFromTargetType(Ty);
8801 if (!QualTy && DestWidth == 128)
8802 return Signed ? Int128Ty : UnsignedInt128Ty;
8803 return QualTy;
8804}
8805
8806/// getRealTypeForBitwidth -
8807/// sets floating point QualTy according to specified bitwidth.
8808/// Returns empty type if there is no appropriate target types.
8809QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8810 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8811 switch (Ty) {
8812 case TargetInfo::Float:
8813 return FloatTy;
8814 case TargetInfo::Double:
8815 return DoubleTy;
8816 case TargetInfo::LongDouble:
8817 return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00008818 case TargetInfo::Float128:
8819 return Float128Ty;
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008820 case TargetInfo::NoFloat:
8821 return QualType();
8822 }
8823
8824 llvm_unreachable("Unhandled TargetInfo::RealType value");
8825}
8826
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008827void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8828 if (Number > 1)
8829 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008830}
8831
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008832unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00008833 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008834 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008835}
8836
David Majnemer2206bf52014-03-05 08:57:59 +00008837void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8838 if (Number > 1)
8839 StaticLocalNumbers[VD] = Number;
8840}
8841
8842unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00008843 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +00008844 return I != StaticLocalNumbers.end() ? I->second : 1;
8845}
8846
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008847MangleNumberingContext &
8848ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008849 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8850 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8851 if (!MCtx)
8852 MCtx = createMangleNumberingContext();
8853 return *MCtx;
8854}
8855
8856MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8857 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008858}
8859
David Majnemere7a818f2015-03-06 18:53:55 +00008860const CXXConstructorDecl *
8861ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
8862 return ABI->getCopyConstructorForExceptionObject(
8863 cast<CXXRecordDecl>(RD->getFirstDecl()));
8864}
8865
8866void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
8867 CXXConstructorDecl *CD) {
8868 return ABI->addCopyConstructorForExceptionObject(
8869 cast<CXXRecordDecl>(RD->getFirstDecl()),
8870 cast<CXXConstructorDecl>(CD->getFirstDecl()));
8871}
8872
David Majnemerdfa6d202015-03-11 18:36:39 +00008873void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8874 unsigned ParmIdx, Expr *DAE) {
8875 ABI->addDefaultArgExprForConstructor(
8876 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE);
8877}
8878
8879Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8880 unsigned ParmIdx) {
8881 return ABI->getDefaultArgExprForConstructor(
8882 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx);
8883}
8884
David Majnemer00350522015-08-31 18:48:39 +00008885void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
8886 TypedefNameDecl *DD) {
8887 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
8888}
8889
8890TypedefNameDecl *
8891ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
8892 return ABI->getTypedefNameForUnnamedTagDecl(TD);
8893}
8894
8895void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
8896 DeclaratorDecl *DD) {
8897 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
8898}
8899
8900DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
8901 return ABI->getDeclaratorForUnnamedTagDecl(TD);
8902}
8903
Ted Kremenek540017e2011-10-06 05:00:56 +00008904void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8905 ParamIndices[D] = index;
8906}
8907
8908unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8909 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8910 assert(I != ParamIndices.end() &&
8911 "ParmIndices lacks entry set by ParmVarDecl");
8912 return I->second;
8913}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008914
Richard Smithe6c01442013-06-05 00:46:14 +00008915APValue *
8916ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8917 bool MayCreate) {
8918 assert(E && E->getStorageDuration() == SD_Static &&
8919 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +00008920 if (MayCreate) {
8921 APValue *&MTVI = MaterializedTemporaryValues[E];
8922 if (!MTVI)
8923 MTVI = new (*this) APValue;
8924 return MTVI;
8925 }
Richard Smithe6c01442013-06-05 00:46:14 +00008926
David Majnemer2dcef9e2015-08-13 23:50:15 +00008927 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +00008928}
8929
Fariborz Jahanian615de762013-05-28 17:37:39 +00008930bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8931 const llvm::Triple &T = getTargetInfo().getTriple();
8932 if (!T.isOSDarwin())
8933 return false;
8934
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008935 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8936 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8937 return false;
8938
Fariborz Jahanian615de762013-05-28 17:37:39 +00008939 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8940 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8941 uint64_t Size = sizeChars.getQuantity();
8942 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8943 unsigned Align = alignChars.getQuantity();
8944 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8945 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8946}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008947
8948namespace {
8949
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008950ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
8951 ASTContext::ParentMapPointers::mapped_type U) {
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00008952 if (const auto *D = U.dyn_cast<const Decl *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008953 return ast_type_traits::DynTypedNode::create(*D);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00008954 if (const auto *S = U.dyn_cast<const Stmt *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008955 return ast_type_traits::DynTypedNode::create(*S);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00008956 return *U.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008957}
8958
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008959/// Template specializations to abstract away from pointers and TypeLocs.
8960/// @{
8961template <typename T>
8962ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
8963 return ast_type_traits::DynTypedNode::create(*Node);
8964}
8965template <>
8966ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
8967 return ast_type_traits::DynTypedNode::create(Node);
8968}
8969template <>
8970ast_type_traits::DynTypedNode
8971createDynTypedNode(const NestedNameSpecifierLoc &Node) {
8972 return ast_type_traits::DynTypedNode::create(Node);
8973}
8974/// @}
8975
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008976 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8977 /// parents as defined by the \c RecursiveASTVisitor.
8978 ///
8979 /// Note that the relationship described here is purely in terms of AST
8980 /// traversal - there are other relationships (for example declaration context)
8981 /// in the AST that are better modeled by special matchers.
8982 ///
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00008983 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008984 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008985 public:
8986 /// \brief Builds and returns the translation unit's parent map.
8987 ///
8988 /// The caller takes ownership of the returned \c ParentMap.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008989 static std::pair<ASTContext::ParentMapPointers *,
8990 ASTContext::ParentMapOtherNodes *>
8991 buildMap(TranslationUnitDecl &TU) {
8992 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
8993 new ASTContext::ParentMapOtherNodes);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008994 Visitor.TraverseDecl(&TU);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008995 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008996 }
8997
8998 private:
8999 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
9000
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009001 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
9002 ASTContext::ParentMapOtherNodes *OtherParents)
9003 : Parents(Parents), OtherParents(OtherParents) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009004
9005 bool shouldVisitTemplateInstantiations() const {
9006 return true;
9007 }
9008 bool shouldVisitImplicitCode() const {
9009 return true;
9010 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009011
Richard Smith85838722015-11-24 03:09:01 +00009012 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
9013 typename MapTy>
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009014 bool TraverseNode(T Node, MapNodeTy MapNode,
Richard Smith85838722015-11-24 03:09:01 +00009015 BaseTraverseFn BaseTraverse, MapTy *Parents) {
Craig Topper36250ad2014-05-12 05:36:57 +00009016 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009017 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00009018 if (ParentStack.size() > 0) {
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00009019 // FIXME: Currently we add the same parent multiple times, but only
9020 // when no memoization data is available for the type.
9021 // For example when we visit all subexpressions of template
9022 // instantiations; this is suboptimal, but benign: the only way to
9023 // visit those is with hasAncestor / hasParent, and those do not create
9024 // new matches.
9025 // The plan is to enable DynTypedNode to be storable in a map or hash
9026 // map. The main problem there is to implement hash functions /
9027 // comparison operators for all types that DynTypedNode supports that
9028 // do not have pointer identity.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009029 auto &NodeOrVector = (*Parents)[MapNode];
Manuel Klimek95403e62014-05-21 13:28:59 +00009030 if (NodeOrVector.isNull()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009031 if (const auto *D = ParentStack.back().get<Decl>())
9032 NodeOrVector = D;
9033 else if (const auto *S = ParentStack.back().get<Stmt>())
9034 NodeOrVector = S;
9035 else
9036 NodeOrVector =
9037 new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009038 } else {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009039 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
9040 auto *Vector = new ASTContext::ParentVector(
9041 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009042 if (auto *Node =
9043 NodeOrVector
9044 .template dyn_cast<ast_type_traits::DynTypedNode *>())
9045 delete Node;
Benjamin Kramer422b3ff2015-10-23 13:24:18 +00009046 NodeOrVector = Vector;
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00009047 }
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00009048
9049 auto *Vector =
9050 NodeOrVector.template get<ASTContext::ParentVector *>();
9051 // Skip duplicates for types that have memoization data.
9052 // We must check that the type has memoization data before calling
9053 // std::find() because DynTypedNode::operator== can't compare all
9054 // types.
9055 bool Found = ParentStack.back().getMemoizationData() &&
9056 std::find(Vector->begin(), Vector->end(),
9057 ParentStack.back()) != Vector->end();
9058 if (!Found)
9059 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009060 }
9061 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009062 ParentStack.push_back(createDynTypedNode(Node));
Richard Smith85838722015-11-24 03:09:01 +00009063 bool Result = BaseTraverse();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009064 ParentStack.pop_back();
9065 return Result;
9066 }
9067
9068 bool TraverseDecl(Decl *DeclNode) {
Richard Smith85838722015-11-24 03:09:01 +00009069 return TraverseNode(DeclNode, DeclNode,
9070 [&] { return VisitorBase::TraverseDecl(DeclNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009071 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009072 }
9073
9074 bool TraverseStmt(Stmt *StmtNode) {
Richard Smith85838722015-11-24 03:09:01 +00009075 return TraverseNode(StmtNode, StmtNode,
9076 [&] { return VisitorBase::TraverseStmt(StmtNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009077 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009078 }
9079
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009080 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
Richard Smith85838722015-11-24 03:09:01 +00009081 return TraverseNode(
9082 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
9083 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
9084 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009085 }
9086
9087 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
9088 return TraverseNode(
9089 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
Richard Smith85838722015-11-24 03:09:01 +00009090 [&] {
9091 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
9092 },
9093 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009094 }
9095
9096 ASTContext::ParentMapPointers *Parents;
9097 ASTContext::ParentMapOtherNodes *OtherParents;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009098 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
9099
9100 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
9101 };
9102
Eugene Zelenkod4304d22015-11-04 21:37:17 +00009103} // anonymous namespace
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009104
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009105template <typename NodeTy, typename MapTy>
9106static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
9107 const MapTy &Map) {
9108 auto I = Map.find(Node);
9109 if (I == Map.end()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009110 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009111 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009112 if (auto *V = I->second.template dyn_cast<ASTContext::ParentVector *>()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009113 return llvm::makeArrayRef(*V);
Manuel Klimek95403e62014-05-21 13:28:59 +00009114 }
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009115 return getSingleDynTypedNodeFromParentMap(I->second);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009116}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009117
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009118ASTContext::DynTypedNodeList
9119ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
9120 if (!PointerParents) {
9121 // We always need to run over the whole translation unit, as
9122 // hasAncestor can escape any subtree.
9123 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
9124 PointerParents.reset(Maps.first);
9125 OtherParents.reset(Maps.second);
9126 }
9127 if (Node.getNodeKind().hasPointerIdentity())
9128 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
9129 return getDynNodeFromMap(Node, *OtherParents);
9130}
9131
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009132bool
9133ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
9134 const ObjCMethodDecl *MethodImpl) {
9135 // No point trying to match an unavailable/deprecated mothod.
9136 if (MethodDecl->hasAttr<UnavailableAttr>()
9137 || MethodDecl->hasAttr<DeprecatedAttr>())
9138 return false;
9139 if (MethodDecl->getObjCDeclQualifier() !=
9140 MethodImpl->getObjCDeclQualifier())
9141 return false;
Alp Toker314cc812014-01-25 16:55:45 +00009142 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009143 return false;
9144
9145 if (MethodDecl->param_size() != MethodImpl->param_size())
9146 return false;
9147
9148 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
9149 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
9150 EF = MethodDecl->param_end();
9151 IM != EM && IF != EF; ++IM, ++IF) {
9152 const ParmVarDecl *DeclVar = (*IF);
9153 const ParmVarDecl *ImplVar = (*IM);
9154 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
9155 return false;
9156 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
9157 return false;
9158 }
9159 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
9160
9161}
Richard Smith053f6c62014-05-16 23:01:30 +00009162
9163// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
9164// doesn't include ASTContext.h
9165template
9166clang::LazyGenerationalUpdatePtr<
9167 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
9168clang::LazyGenerationalUpdatePtr<
9169 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
9170 const clang::ASTContext &Ctx, Decl *Value);