blob: 34a78c6a0c62feb28643394965d2b5795a5b9b02 [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
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000654 assert(!TTP->getRequiresClause() &&
655 "Unexpected requires-clause on template template-parameter");
George Burgess IVb7e4e482016-08-25 01:54:37 +0000656 Expr *const CanonRequiresClause = nullptr;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000657
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000658 TemplateTemplateParmDecl *CanonTTP
659 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
660 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000661 TTP->getPosition(),
662 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000663 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000664 TemplateParameterList::Create(*this, SourceLocation(),
665 SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +0000666 CanonParams,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000667 SourceLocation(),
668 CanonRequiresClause));
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000669
670 // Get the new insert position for the node we care about.
671 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000672 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000673 (void)Canonical;
674
675 // Create the canonical template template parameter entry.
676 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
677 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
678 return CanonTTP;
679}
680
Charles Davis53c59df2010-08-16 03:33:14 +0000681CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000682 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000683
John McCall359b8852013-01-25 22:30:49 +0000684 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000685 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000686 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000687 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +0000688 case TargetCXXABI::WatchOS:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000689 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000690 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000691 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000692 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000693 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000694 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000695 return CreateMicrosoftCXXABI(*this);
696 }
David Blaikie8a40f702012-01-17 06:56:22 +0000697 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000698}
699
Douglas Gregore8bbc122011-09-02 00:18:52 +0000700static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000701 const LangOptions &LOpts) {
702 if (LOpts.FakeAddressSpaceMap) {
703 // The fake address space map must have a distinct entry for each
704 // language-specific address space.
705 static const unsigned FakeAddrSpaceMap[] = {
Yaxun Liub34ec822017-04-11 17:24:23 +0000706 0, // Default
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000707 1, // opencl_global
Egor Churaev28f00aa2016-12-23 16:11:25 +0000708 3, // opencl_local
709 2, // opencl_constant
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000710 4, // opencl_generic
711 5, // cuda_device
712 6, // cuda_constant
713 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000714 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000715 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000716 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000717 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000718 }
719}
720
David Tweed31d09b02013-09-13 12:04:22 +0000721static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
722 const LangOptions &LangOpts) {
723 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000724 case LangOptions::ASMM_Target:
725 return TI.useAddressSpaceMapMangling();
726 case LangOptions::ASMM_On:
727 return true;
728 case LangOptions::ASMM_Off:
729 return false;
730 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000731 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000732}
733
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000734ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000735 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000736 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000737 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
738 DependentTemplateSpecializationTypes(this_()),
739 SubstTemplateTemplateParmPacks(this_()),
740 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +0000741 UInt128Decl(nullptr), BuiltinVaListDecl(nullptr),
742 BuiltinMSVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr),
743 ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
Ben Langmuirf5416742016-02-04 00:55:24 +0000744 CFConstantStringTagDecl(nullptr), CFConstantStringTypeDecl(nullptr),
745 ObjCInstanceTypeDecl(nullptr), FILEDecl(nullptr), jmp_bufDecl(nullptr),
746 sigjmp_bufDecl(nullptr), ucontext_tDecl(nullptr),
747 BlockDescriptorType(nullptr), BlockDescriptorExtendedType(nullptr),
748 cudaConfigureCallDecl(nullptr), FirstLocalImport(), LastLocalImport(),
Eric Fiselier6ad68552016-07-01 01:24:09 +0000749 ExternCContext(nullptr), MakeIntegerSeqDecl(nullptr),
750 TypePackElementDecl(nullptr), SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000751 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Dean Michael Berris835832d2017-03-30 00:29:36 +0000752 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
753 LangOpts.XRayNeverInstrumentFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000754 AddrSpaceMap(nullptr), Target(nullptr), AuxTarget(nullptr),
755 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
756 BuiltinInfo(builtins), DeclarationNames(*this), ExternalSource(nullptr),
757 Listener(nullptr), Comments(SM), CommentsLoaded(false),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000758 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000759 TUDecl = TranslationUnitDecl::Create(*this);
760}
761
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000762ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000763 ReleaseParentMapEntries();
764
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000765 // Release the DenseMaps associated with DeclContext objects.
766 // FIXME: Is this the ideal solution?
767 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000768
Manuel Klimeka7328992013-06-03 13:51:33 +0000769 // Call all of the deallocation functions on all of their targets.
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000770 for (auto &Pair : Deallocations)
771 (Pair.first)(Pair.second);
Manuel Klimeka7328992013-06-03 13:51:33 +0000772
Ted Kremenek076baeb2010-06-08 23:00:58 +0000773 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000774 // because they can contain DenseMaps.
775 for (llvm::DenseMap<const ObjCContainerDecl*,
776 const ASTRecordLayout*>::iterator
777 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
778 // Increment in loop to prevent using deallocated memory.
779 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
780 R->Destroy(*this);
781
Ted Kremenek076baeb2010-06-08 23:00:58 +0000782 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
783 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
784 // Increment in loop to prevent using deallocated memory.
785 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
786 R->Destroy(*this);
787 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000788
789 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
790 AEnd = DeclAttrs.end();
791 A != AEnd; ++A)
792 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000793
David Majnemere694f3e2015-08-14 14:43:50 +0000794 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
795 MaterializedTemporaryValues)
796 MTVPair.second->~APValue();
797
Richard Smith423f46f2016-07-20 21:38:26 +0000798 for (const auto &Value : ModuleInitializers)
799 Value.second->~PerModuleInitializers();
Douglas Gregor561eceb2010-08-30 16:49:28 +0000800}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000801
Manuel Klimek95403e62014-05-21 13:28:59 +0000802void ASTContext::ReleaseParentMapEntries() {
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000803 if (!PointerParents) return;
804 for (const auto &Entry : *PointerParents) {
805 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
806 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
807 } else if (Entry.second.is<ParentVector *>()) {
808 delete Entry.second.get<ParentVector *>();
809 }
810 }
811 for (const auto &Entry : *OtherParents) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000812 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
813 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +0000814 } else if (Entry.second.is<ParentVector *>()) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000815 delete Entry.second.get<ParentVector *>();
816 }
817 }
818}
819
Douglas Gregor1a809332010-05-23 18:26:36 +0000820void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000821 Deallocations.push_back({Callback, Data});
Douglas Gregor1a809332010-05-23 18:26:36 +0000822}
823
Mike Stump11289f42009-09-09 15:08:12 +0000824void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000825ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000826 ExternalSource = std::move(Source);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000827}
828
Chris Lattner4eb445d2007-01-26 01:27:23 +0000829void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000830 llvm::errs() << "\n*** AST Context Stats:\n";
831 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000832
Douglas Gregora30d0462009-05-26 14:40:08 +0000833 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000834#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000835#define ABSTRACT_TYPE(Name, Parent)
836#include "clang/AST/TypeNodes.def"
837 0 // Extra
838 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000839
Chris Lattner4eb445d2007-01-26 01:27:23 +0000840 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
841 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000842 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000843 }
844
Douglas Gregora30d0462009-05-26 14:40:08 +0000845 unsigned Idx = 0;
846 unsigned TotalBytes = 0;
847#define TYPE(Name, Parent) \
848 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000849 llvm::errs() << " " << counts[Idx] << " " << #Name \
850 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000851 TotalBytes += counts[Idx] * sizeof(Name##Type); \
852 ++Idx;
853#define ABSTRACT_TYPE(Name, Parent)
854#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000855
Chandler Carruth3c147a72011-07-04 05:32:14 +0000856 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
857
Douglas Gregor7454c562010-07-02 20:37:36 +0000858 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000859 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
860 << NumImplicitDefaultConstructors
861 << " implicit default constructors created\n";
862 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
863 << NumImplicitCopyConstructors
864 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000865 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000866 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
867 << NumImplicitMoveConstructors
868 << " implicit move constructors created\n";
869 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
870 << NumImplicitCopyAssignmentOperators
871 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000872 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000873 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
874 << NumImplicitMoveAssignmentOperators
875 << " implicit move assignment operators created\n";
876 llvm::errs() << NumImplicitDestructorsDeclared << "/"
877 << NumImplicitDestructors
878 << " implicit destructors created\n";
879
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000880 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000881 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000882 ExternalSource->PrintStats();
883 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000884
Douglas Gregor5b11d492010-07-25 17:53:33 +0000885 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000886}
887
Richard Smith42413142015-05-15 20:05:43 +0000888void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
889 bool NotifyListeners) {
890 if (NotifyListeners)
891 if (auto *Listener = getASTMutationListener())
892 Listener->RedefinedHiddenDefinition(ND, M);
893
Benjamin Kramera72a70a2016-10-17 13:00:44 +0000894 if (getLangOpts().ModulesLocalVisibility)
895 MergedDefModules[ND].push_back(M);
896 else
Richard Smith90dc5252017-06-23 01:04:34 +0000897 ND->setVisibleDespiteOwningModule();
Richard Smith42413142015-05-15 20:05:43 +0000898}
899
900void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
901 auto It = MergedDefModules.find(ND);
902 if (It == MergedDefModules.end())
903 return;
904
Benjamin Kramera72a70a2016-10-17 13:00:44 +0000905 auto &Merged = It->second;
Richard Smith42413142015-05-15 20:05:43 +0000906 llvm::DenseSet<Module*> Found;
907 for (Module *&M : Merged)
908 if (!Found.insert(M).second)
909 M = nullptr;
910 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
911}
912
Richard Smithdc1f0422016-07-20 19:10:16 +0000913void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
914 if (LazyInitializers.empty())
915 return;
916
917 auto *Source = Ctx.getExternalSource();
918 assert(Source && "lazy initializers but no external source");
919
920 auto LazyInits = std::move(LazyInitializers);
921 LazyInitializers.clear();
922
923 for (auto ID : LazyInits)
924 Initializers.push_back(Source->GetExternalDecl(ID));
925
926 assert(LazyInitializers.empty() &&
927 "GetExternalDecl for lazy module initializer added more inits");
928}
929
930void ASTContext::addModuleInitializer(Module *M, Decl *D) {
931 // One special case: if we add a module initializer that imports another
932 // module, and that module's only initializer is an ImportDecl, simplify.
933 if (auto *ID = dyn_cast<ImportDecl>(D)) {
934 auto It = ModuleInitializers.find(ID->getImportedModule());
935
936 // Maybe the ImportDecl does nothing at all. (Common case.)
937 if (It == ModuleInitializers.end())
938 return;
939
940 // Maybe the ImportDecl only imports another ImportDecl.
941 auto &Imported = *It->second;
942 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
943 Imported.resolve(*this);
944 auto *OnlyDecl = Imported.Initializers.front();
945 if (isa<ImportDecl>(OnlyDecl))
946 D = OnlyDecl;
947 }
948 }
949
950 auto *&Inits = ModuleInitializers[M];
951 if (!Inits)
952 Inits = new (*this) PerModuleInitializers;
953 Inits->Initializers.push_back(D);
954}
955
956void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
957 auto *&Inits = ModuleInitializers[M];
958 if (!Inits)
959 Inits = new (*this) PerModuleInitializers;
960 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
961 IDs.begin(), IDs.end());
962}
963
964ArrayRef<Decl*> ASTContext::getModuleInitializers(Module *M) {
965 auto It = ModuleInitializers.find(M);
966 if (It == ModuleInitializers.end())
967 return None;
968
969 auto *Inits = It->second;
970 Inits->resolve(*this);
971 return Inits->Initializers;
972}
973
Richard Smithf19e1272015-03-07 00:04:49 +0000974ExternCContextDecl *ASTContext::getExternCContextDecl() const {
975 if (!ExternCContext)
976 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
977
978 return ExternCContext;
979}
980
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000981BuiltinTemplateDecl *
982ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
983 const IdentifierInfo *II) const {
984 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
985 BuiltinTemplate->setImplicit();
986 TUDecl->addDecl(BuiltinTemplate);
987
988 return BuiltinTemplate;
989}
990
991BuiltinTemplateDecl *
992ASTContext::getMakeIntegerSeqDecl() const {
993 if (!MakeIntegerSeqDecl)
994 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
995 getMakeIntegerSeqName());
996 return MakeIntegerSeqDecl;
997}
998
Eric Fiselier6ad68552016-07-01 01:24:09 +0000999BuiltinTemplateDecl *
1000ASTContext::getTypePackElementDecl() const {
1001 if (!TypePackElementDecl)
1002 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1003 getTypePackElementName());
1004 return TypePackElementDecl;
1005}
1006
Alp Toker2dea15b2013-12-17 01:22:38 +00001007RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1008 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001009 SourceLocation Loc;
1010 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00001011 if (getLangOpts().CPlusPlus)
1012 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1013 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001014 else
Alp Toker2dea15b2013-12-17 01:22:38 +00001015 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1016 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001017 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +00001018 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1019 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +00001020 return NewDecl;
1021}
1022
1023TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1024 StringRef Name) const {
1025 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1026 TypedefDecl *NewDecl = TypedefDecl::Create(
1027 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1028 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1029 NewDecl->setImplicit();
1030 return NewDecl;
1031}
1032
Douglas Gregor801c99d2011-08-12 06:49:56 +00001033TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001034 if (!Int128Decl)
1035 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001036 return Int128Decl;
1037}
1038
1039TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001040 if (!UInt128Decl)
1041 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001042 return UInt128Decl;
1043}
Chris Lattner4eb445d2007-01-26 01:27:23 +00001044
John McCall48f2d582009-10-23 23:03:21 +00001045void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +00001046 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +00001047 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +00001048 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001049}
1050
Artem Belevichb5bc9232015-09-22 17:23:22 +00001051void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1052 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001053 assert((!this->Target || this->Target == &Target) &&
1054 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +00001055 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +00001056
Douglas Gregore8bbc122011-09-02 00:18:52 +00001057 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +00001058 this->AuxTarget = AuxTarget;
1059
Douglas Gregore8bbc122011-09-02 00:18:52 +00001060 ABI.reset(createCXXABI(Target));
1061 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +00001062 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +00001063
Chris Lattner970e54e2006-11-12 00:37:36 +00001064 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +00001065 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +00001066
Chris Lattner970e54e2006-11-12 00:37:36 +00001067 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001068 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001069 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001070 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001071 InitBuiltinType(CharTy, BuiltinType::Char_S);
1072 else
1073 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001074 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001075 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1076 InitBuiltinType(ShortTy, BuiltinType::Short);
1077 InitBuiltinType(IntTy, BuiltinType::Int);
1078 InitBuiltinType(LongTy, BuiltinType::Long);
1079 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001080
Chris Lattner970e54e2006-11-12 00:37:36 +00001081 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001082 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1083 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1084 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1085 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1086 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001087
Chris Lattner970e54e2006-11-12 00:37:36 +00001088 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001089 InitBuiltinType(FloatTy, BuiltinType::Float);
1090 InitBuiltinType(DoubleTy, BuiltinType::Double);
1091 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001092
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001093 // GNU extension, __float128 for IEEE quadruple precision
1094 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1095
Chris Lattnerf122cef2009-04-30 02:43:43 +00001096 // GNU extension, 128-bit integers.
1097 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1098 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1099
Hans Wennborg0d81e012013-05-10 10:08:40 +00001100 // C++ 3.9.1p5
1101 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1102 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1103 else // -fshort-wchar makes wchar_t be unsigned.
1104 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1105 if (LangOpts.CPlusPlus && LangOpts.WChar)
1106 WideCharTy = WCharTy;
1107 else {
1108 // C99 (or C++ using -fno-wchar).
1109 WideCharTy = getFromTargetType(Target.getWCharType());
1110 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001111
James Molloy36365542012-05-04 10:55:22 +00001112 WIntTy = getFromTargetType(Target.getWIntType());
1113
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001114 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1115 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1116 else // C99
1117 Char16Ty = getFromTargetType(Target.getChar16Type());
1118
1119 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1120 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1121 else // C99
1122 Char32Ty = getFromTargetType(Target.getChar32Type());
1123
Douglas Gregor4619e432008-12-05 23:32:09 +00001124 // Placeholder type for type-dependent expressions whose type is
1125 // completely unknown. No code should ever check a type against
1126 // DependentTy and users should never see it; however, it is here to
1127 // help diagnose failures to properly check for type-dependent
1128 // expressions.
1129 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001130
John McCall36e7fe32010-10-12 00:20:44 +00001131 // Placeholder type for functions.
1132 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1133
John McCall0009fcc2011-04-26 20:42:42 +00001134 // Placeholder type for bound members.
1135 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1136
John McCall526ab472011-10-25 17:37:35 +00001137 // Placeholder type for pseudo-objects.
1138 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1139
John McCall31996342011-04-07 08:22:57 +00001140 // "any" type; useful for debugger-like clients.
1141 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1142
John McCall8a6b59a2011-10-17 18:09:15 +00001143 // Placeholder type for unbridged ARC casts.
1144 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1145
Eli Friedman34866c72012-08-31 00:14:07 +00001146 // Placeholder type for builtin functions.
1147 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1148
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001149 // Placeholder type for OMP array sections.
1150 if (LangOpts.OpenMP)
1151 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1152
Chris Lattner970e54e2006-11-12 00:37:36 +00001153 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001154 FloatComplexTy = getComplexType(FloatTy);
1155 DoubleComplexTy = getComplexType(DoubleTy);
1156 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001157 Float128ComplexTy = getComplexType(Float128Ty);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001158
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001159 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001160 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1161 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001162 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001163
Alexey Bader954ba212016-04-08 13:40:33 +00001164 if (LangOpts.OpenCL) {
1165#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1166 InitBuiltinType(SingletonId, BuiltinType::Id);
Alexey Baderb62f1442016-04-13 08:33:41 +00001167#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001168
Guy Benyei61054192013-02-07 10:55:47 +00001169 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001170 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001171 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1172 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001173 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001174 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001175
1176 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001177 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1178 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001179
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001180 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001181
1182 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001183
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001184 // void * type
Yaxun Liu39195062017-08-04 18:16:31 +00001185 if (LangOpts.OpenCLVersion >= 200) {
1186 auto Q = VoidTy.getQualifiers();
1187 Q.setAddressSpace(LangAS::opencl_generic);
1188 VoidPtrTy = getPointerType(getCanonicalType(
1189 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1190 } else {
1191 VoidPtrTy = getPointerType(VoidTy);
1192 }
Sebastian Redl576fd422009-05-10 18:38:11 +00001193
1194 // nullptr type (C++0x 2.14.7)
1195 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001196
1197 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1198 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001199
1200 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001201 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001202}
1203
David Blaikie9c902b52011-09-25 23:23:43 +00001204DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001205 return SourceMgr.getDiagnostics();
1206}
1207
Douglas Gregor561eceb2010-08-30 16:49:28 +00001208AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1209 AttrVec *&Result = DeclAttrs[D];
1210 if (!Result) {
1211 void *Mem = Allocate(sizeof(AttrVec));
1212 Result = new (Mem) AttrVec;
1213 }
1214
1215 return *Result;
1216}
1217
1218/// \brief Erase the attributes corresponding to the given declaration.
1219void ASTContext::eraseDeclAttrs(const Decl *D) {
1220 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1221 if (Pos != DeclAttrs.end()) {
1222 Pos->second->~AttrVec();
1223 DeclAttrs.erase(Pos);
1224 }
1225}
1226
Larisse Voufo39a1e502013-08-06 01:03:05 +00001227// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001228MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001229ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001230 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001231 return getTemplateOrSpecializationInfo(Var)
1232 .dyn_cast<MemberSpecializationInfo *>();
1233}
1234
1235ASTContext::TemplateOrSpecializationInfo
1236ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1237 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1238 TemplateOrInstantiation.find(Var);
1239 if (Pos == TemplateOrInstantiation.end())
1240 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001241
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001242 return Pos->second;
1243}
1244
Mike Stump11289f42009-09-09 15:08:12 +00001245void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001246ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001247 TemplateSpecializationKind TSK,
1248 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001249 assert(Inst->isStaticDataMember() && "Not a static data member");
1250 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001251 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1252 Tmpl, TSK, PointOfInstantiation));
1253}
1254
1255void
1256ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1257 TemplateOrSpecializationInfo TSI) {
1258 assert(!TemplateOrInstantiation[Inst] &&
1259 "Already noted what the variable was instantiated from");
1260 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001261}
1262
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001263FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1264 const FunctionDecl *FD){
1265 assert(FD && "Specialization is 0");
1266 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001267 = ClassScopeSpecializationPattern.find(FD);
1268 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001269 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001270
1271 return Pos->second;
1272}
1273
1274void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1275 FunctionDecl *Pattern) {
1276 assert(FD && "Specialization is 0");
1277 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001278 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001279}
1280
John McCalle61f2ba2009-11-18 02:36:19 +00001281NamedDecl *
Richard Smithd8a9e372016-12-18 21:39:37 +00001282ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1283 auto Pos = InstantiatedFromUsingDecl.find(UUD);
John McCallb96ec562009-12-04 22:46:56 +00001284 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001285 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001286
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001287 return Pos->second;
1288}
1289
1290void
Richard Smithd8a9e372016-12-18 21:39:37 +00001291ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
John McCallb96ec562009-12-04 22:46:56 +00001292 assert((isa<UsingDecl>(Pattern) ||
1293 isa<UnresolvedUsingValueDecl>(Pattern) ||
1294 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1295 "pattern decl is not a using decl");
Richard Smithd8a9e372016-12-18 21:39:37 +00001296 assert((isa<UsingDecl>(Inst) ||
1297 isa<UnresolvedUsingValueDecl>(Inst) ||
1298 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1299 "instantiation did not produce a using decl");
John McCallb96ec562009-12-04 22:46:56 +00001300 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1301 InstantiatedFromUsingDecl[Inst] = Pattern;
1302}
1303
1304UsingShadowDecl *
1305ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1306 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1307 = InstantiatedFromUsingShadowDecl.find(Inst);
1308 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001309 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001310
1311 return Pos->second;
1312}
1313
1314void
1315ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1316 UsingShadowDecl *Pattern) {
1317 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1318 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001319}
1320
Anders Carlsson5da84842009-09-01 04:26:58 +00001321FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1322 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1323 = InstantiatedFromUnnamedFieldDecl.find(Field);
1324 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001325 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001326
Anders Carlsson5da84842009-09-01 04:26:58 +00001327 return Pos->second;
1328}
1329
1330void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1331 FieldDecl *Tmpl) {
1332 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1333 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1334 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1335 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001336
Anders Carlsson5da84842009-09-01 04:26:58 +00001337 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1338}
1339
Douglas Gregor832940b2010-03-02 23:58:15 +00001340ASTContext::overridden_cxx_method_iterator
1341ASTContext::overridden_methods_begin(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());
Douglas Gregor832940b2010-03-02 23:58:15 +00001344 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001345 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001346 return Pos->second.begin();
1347}
1348
1349ASTContext::overridden_cxx_method_iterator
1350ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001351 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1352 OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001353 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001354 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001355 return Pos->second.end();
1356}
1357
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001358unsigned
1359ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001360 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1361 OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001362 if (Pos == OverriddenMethods.end())
1363 return 0;
Chandler Carruthb1bcd5d2016-06-11 04:45:38 +00001364 return Pos->second.size();
Clement Courbet8251ebf2016-06-10 11:54:43 +00001365}
1366
Clement Courbet6ecaec82016-07-05 07:49:31 +00001367ASTContext::overridden_method_range
1368ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1369 return overridden_method_range(overridden_methods_begin(Method),
1370 overridden_methods_end(Method));
1371}
1372
Douglas Gregor832940b2010-03-02 23:58:15 +00001373void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1374 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001375 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001376 OverriddenMethods[Method].push_back(Overridden);
1377}
1378
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001379void ASTContext::getOverriddenMethods(
1380 const NamedDecl *D,
1381 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001382 assert(D);
1383
1384 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001385 Overridden.append(overridden_methods_begin(CXXMethod),
1386 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001387 return;
1388 }
1389
1390 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1391 if (!Method)
1392 return;
1393
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001394 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1395 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001396 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001397}
1398
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001399void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1400 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1401 assert(!Import->isFromASTFile() && "Non-local import declaration");
1402 if (!FirstLocalImport) {
1403 FirstLocalImport = Import;
1404 LastLocalImport = Import;
1405 return;
1406 }
1407
1408 LastLocalImport->NextLocalImport = Import;
1409 LastLocalImport = Import;
1410}
1411
Chris Lattner53cfe802007-07-18 17:52:12 +00001412//===----------------------------------------------------------------------===//
1413// Type Sizing and Analysis
1414//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001415
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001416/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1417/// scalar floating point type.
1418const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001419 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001420 assert(BT && "Not a floating point type!");
1421 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001422 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001423 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001424 case BuiltinType::Float: return Target->getFloatFormat();
1425 case BuiltinType::Double: return Target->getDoubleFormat();
1426 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001427 case BuiltinType::Float128: return Target->getFloat128Format();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001428 }
1429}
1430
Rafael Espindola71eccb32013-08-08 19:53:46 +00001431CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001432 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001433
John McCall94268702010-10-08 18:24:19 +00001434 bool UseAlignAttrOnly = false;
1435 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1436 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001437
John McCall94268702010-10-08 18:24:19 +00001438 // __attribute__((aligned)) can increase or decrease alignment
1439 // *except* on a struct or struct member, where it only increases
1440 // alignment unless 'packed' is also specified.
1441 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001442 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001443 // ignore that possibility; Sema should diagnose it.
1444 if (isa<FieldDecl>(D)) {
1445 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1446 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1447 } else {
1448 UseAlignAttrOnly = true;
1449 }
1450 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001451 else if (isa<FieldDecl>(D))
1452 UseAlignAttrOnly =
1453 D->hasAttr<PackedAttr>() ||
1454 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001455
John McCall4e819612011-01-20 07:57:12 +00001456 // If we're using the align attribute only, just ignore everything
1457 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001458 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001459 // do nothing
1460
John McCall94268702010-10-08 18:24:19 +00001461 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001462 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001463 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001464 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001465 T = RT->getPointeeType();
1466 else
1467 T = getPointerType(RT->getPointeeType());
1468 }
Richard Smithf6d70302014-06-10 23:34:28 +00001469 QualType BaseT = getBaseElementType(T);
Akira Hatanakad62f2c82017-01-06 17:56:15 +00001470 if (T->isFunctionType())
1471 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1472 else if (!BaseT->isIncompleteType()) {
John McCall33ddac02011-01-19 10:06:00 +00001473 // Adjust alignments of declarations with array type by the
1474 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001475 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001476 unsigned MinWidth = Target->getLargeArrayMinWidth();
1477 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001478 if (isa<VariableArrayType>(arrayType))
1479 Align = std::max(Align, Target->getLargeArrayAlign());
1480 else if (isa<ConstantArrayType>(arrayType) &&
1481 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1482 Align = std::max(Align, Target->getLargeArrayAlign());
1483 }
John McCall33ddac02011-01-19 10:06:00 +00001484 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001485 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00001486 if (BaseT.getQualifiers().hasUnaligned())
1487 Align = Target->getCharWidth();
Ulrich Weigandfa806422013-05-06 16:23:57 +00001488 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001489 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001490 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1491 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001492 }
John McCall4e819612011-01-20 07:57:12 +00001493
1494 // Fields can be subject to extra alignment constraints, like if
1495 // the field is packed, the struct is packed, or the struct has a
1496 // a max-field-alignment constraint (#pragma pack). So calculate
1497 // the actual alignment of the field within the struct, and then
1498 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001499 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1500 const RecordDecl *Parent = Field->getParent();
1501 // We can only produce a sensible answer if the record is valid.
1502 if (!Parent->isInvalidDecl()) {
1503 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001504
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001505 // Start with the record's overall alignment.
1506 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001507
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001508 // Use the GCD of that and the offset within the record.
1509 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1510 if (Offset > 0) {
1511 // Alignment is always a power of 2, so the GCD will be a power of 2,
1512 // which means we get to do this crazy thing instead of Euclid's.
1513 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1514 if (LowBitOfOffset < FieldAlign)
1515 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1516 }
1517
1518 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001519 }
Charles Davis3fc51072010-02-23 04:52:00 +00001520 }
Chris Lattner68061312009-01-24 21:53:27 +00001521 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001522
Ken Dyckcc56c542011-01-15 18:38:59 +00001523 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001524}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001525
John McCallf1249922012-08-21 04:10:00 +00001526// getTypeInfoDataSizeInChars - Return the size of a type, in
1527// chars. If the type is a record, its data size is returned. This is
1528// the size of the memcpy that's performed when assigning this type
1529// using a trivial copy/move assignment operator.
1530std::pair<CharUnits, CharUnits>
1531ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1532 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1533
1534 // In C++, objects can sometimes be allocated into the tail padding
1535 // of a base-class subobject. We decide whether that's possible
1536 // during class layout, so here we can just trust the layout results.
1537 if (getLangOpts().CPlusPlus) {
1538 if (const RecordType *RT = T->getAs<RecordType>()) {
1539 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1540 sizeAndAlign.first = layout.getDataSize();
1541 }
1542 }
1543
1544 return sizeAndAlign;
1545}
1546
Richard Trieu04d2d942013-05-14 21:59:17 +00001547/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1548/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1549std::pair<CharUnits, CharUnits>
1550static getConstantArrayInfoInChars(const ASTContext &Context,
1551 const ConstantArrayType *CAT) {
1552 std::pair<CharUnits, CharUnits> EltInfo =
1553 Context.getTypeInfoInChars(CAT->getElementType());
1554 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001555 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1556 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001557 "Overflow in array type char size evaluation");
1558 uint64_t Width = EltInfo.first.getQuantity() * Size;
1559 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001560 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1561 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001562 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001563 return std::make_pair(CharUnits::fromQuantity(Width),
1564 CharUnits::fromQuantity(Align));
1565}
1566
John McCall87fe5d52010-05-20 01:18:31 +00001567std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001568ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001569 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1570 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001571 TypeInfo Info = getTypeInfo(T);
1572 return std::make_pair(toCharUnitsFromBits(Info.Width),
1573 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001574}
1575
1576std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001577ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001578 return getTypeInfoInChars(T.getTypePtr());
1579}
1580
David Majnemer34b57492014-07-30 01:30:47 +00001581bool ASTContext::isAlignmentRequired(const Type *T) const {
1582 return getTypeInfo(T).AlignIsRequired;
1583}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001584
David Majnemer34b57492014-07-30 01:30:47 +00001585bool ASTContext::isAlignmentRequired(QualType T) const {
1586 return isAlignmentRequired(T.getTypePtr());
1587}
1588
Richard Smithb2f0f052016-10-10 18:54:32 +00001589unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1590 // An alignment on a typedef overrides anything else.
1591 if (auto *TT = T->getAs<TypedefType>())
1592 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1593 return Align;
1594
1595 // If we have an (array of) complete type, we're done.
1596 T = getBaseElementType(T);
1597 if (!T->isIncompleteType())
1598 return getTypeAlign(T);
1599
1600 // If we had an array type, its element type might be a typedef
1601 // type with an alignment attribute.
1602 if (auto *TT = T->getAs<TypedefType>())
1603 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1604 return Align;
1605
1606 // Otherwise, see if the declaration of the type had an attribute.
1607 if (auto *TT = T->getAs<TagType>())
1608 return TT->getDecl()->getMaxAlignment();
1609
1610 return 0;
1611}
1612
David Majnemer34b57492014-07-30 01:30:47 +00001613TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001614 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1615 if (I != MemoizedTypeInfo.end())
1616 return I->second;
1617
1618 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1619 TypeInfo TI = getTypeInfoImpl(T);
1620 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001621 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001622}
1623
1624/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1625/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001626///
1627/// FIXME: Pointers into different addr spaces could have different sizes and
1628/// alignment requirements: getPointerInfo should take an AddrSpace, this
1629/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001630TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1631 uint64_t Width = 0;
1632 unsigned Align = 8;
1633 bool AlignIsRequired = false;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001634 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001635#define TYPE(Class, Base)
1636#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001637#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001638#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001639#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1640 case Type::Class: \
1641 assert(!T->isDependentType() && "should not see dependent types here"); \
1642 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001643#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001644 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001645
Chris Lattner355332d2007-07-13 22:27:08 +00001646 case Type::FunctionNoProto:
1647 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001648 // GCC extension: alignof(function) = 32 bits
1649 Width = 0;
1650 Align = 32;
1651 break;
1652
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001653 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001654 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001655 Width = 0;
1656 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1657 break;
1658
Steve Naroff5c131802007-08-30 01:06:46 +00001659 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001660 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001661
David Majnemer34b57492014-07-30 01:30:47 +00001662 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001663 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001664 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001665 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001666 Width = EltInfo.Width * Size;
1667 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001668 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1669 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001670 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001671 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001672 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001673 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001674 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001675 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001676 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1677 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001678 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001679 // If the alignment is not a power of 2, round up to the next power of 2.
1680 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001681 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001682 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001683 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001684 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001685 // Adjust the alignment based on the target max.
1686 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1687 if (TargetVectorAlign && TargetVectorAlign < Align)
1688 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001689 break;
1690 }
Chris Lattner647fb222007-07-18 18:26:58 +00001691
Chris Lattner7570e9c2008-03-08 08:52:55 +00001692 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001693 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001694 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001695 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001696 // GCC extension: alignof(void) = 8 bits.
1697 Width = 0;
1698 Align = 8;
1699 break;
1700
Chris Lattner6a4f7452007-12-19 19:23:28 +00001701 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001702 Width = Target->getBoolWidth();
1703 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001704 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001705 case BuiltinType::Char_S:
1706 case BuiltinType::Char_U:
1707 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001708 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001709 Width = Target->getCharWidth();
1710 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001711 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001712 case BuiltinType::WChar_S:
1713 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001714 Width = Target->getWCharWidth();
1715 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001716 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001717 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001718 Width = Target->getChar16Width();
1719 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001720 break;
1721 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001722 Width = Target->getChar32Width();
1723 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001724 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001725 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001726 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001727 Width = Target->getShortWidth();
1728 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001729 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001730 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001731 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001732 Width = Target->getIntWidth();
1733 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001734 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001735 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001736 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001737 Width = Target->getLongWidth();
1738 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001739 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001740 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001741 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001742 Width = Target->getLongLongWidth();
1743 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001744 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001745 case BuiltinType::Int128:
1746 case BuiltinType::UInt128:
1747 Width = 128;
1748 Align = 128; // int128_t is 128-bit aligned on all targets.
1749 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001750 case BuiltinType::Half:
1751 Width = Target->getHalfWidth();
1752 Align = Target->getHalfAlign();
1753 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001754 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001755 Width = Target->getFloatWidth();
1756 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001757 break;
1758 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001759 Width = Target->getDoubleWidth();
1760 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001761 break;
1762 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001763 Width = Target->getLongDoubleWidth();
1764 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001765 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001766 case BuiltinType::Float128:
1767 Width = Target->getFloat128Width();
1768 Align = Target->getFloat128Align();
1769 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001770 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001771 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1772 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001773 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001774 case BuiltinType::ObjCId:
1775 case BuiltinType::ObjCClass:
1776 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001777 Width = Target->getPointerWidth(0);
1778 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001779 break;
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001780 case BuiltinType::OCLSampler: {
1781 auto AS = getTargetAddressSpace(LangAS::opencl_constant);
1782 Width = Target->getPointerWidth(AS);
1783 Align = Target->getPointerAlign(AS);
Guy Benyei61054192013-02-07 10:55:47 +00001784 break;
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001785 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001786 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001787 case BuiltinType::OCLClkEvent:
1788 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001789 case BuiltinType::OCLReserveID:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001790 // Currently these types are pointers to opaque types.
1791 Width = Target->getPointerWidth(0);
1792 Align = Target->getPointerAlign(0);
1793 break;
Yaxun Liu99444cb2016-08-03 20:38:06 +00001794#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1795 case BuiltinType::Id:
1796#include "clang/Basic/OpenCLImageTypes.def"
1797 {
1798 auto AS = getTargetAddressSpace(Target->getOpenCLImageAddrSpace());
1799 Width = Target->getPointerWidth(AS);
1800 Align = Target->getPointerAlign(AS);
1801 }
Chris Lattner983a8bb2007-07-13 22:13:22 +00001802 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001803 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001804 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001805 Width = Target->getPointerWidth(0);
1806 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001807 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001808 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001809 unsigned AS = getTargetAddressSpace(
1810 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001811 Width = Target->getPointerWidth(AS);
1812 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001813 break;
1814 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001815 case Type::LValueReference:
1816 case Type::RValueReference: {
1817 // alignof and sizeof should never enter this code path here, so we go
1818 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001819 unsigned AS = getTargetAddressSpace(
1820 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001821 Width = Target->getPointerWidth(AS);
1822 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001823 break;
1824 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001825 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001826 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001827 Width = Target->getPointerWidth(AS);
1828 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001829 break;
1830 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001831 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001832 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001833 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001834 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001835 }
Chris Lattner647fb222007-07-18 18:26:58 +00001836 case Type::Complex: {
1837 // Complex types have the same alignment as their elements, but twice the
1838 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001839 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1840 Width = EltInfo.Width * 2;
1841 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001842 break;
1843 }
John McCall8b07ec22010-05-15 11:32:37 +00001844 case Type::ObjCObject:
1845 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001846 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001847 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001848 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001849 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001850 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001851 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001852 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001853 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001854 break;
1855 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001856 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001857 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001858 const TagType *TT = cast<TagType>(T);
1859
1860 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001861 Width = 8;
1862 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001863 break;
1864 }
Mike Stump11289f42009-09-09 15:08:12 +00001865
David Majnemer475b25e2015-01-21 10:54:38 +00001866 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1867 const EnumDecl *ED = ET->getDecl();
1868 TypeInfo Info =
1869 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1870 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1871 Info.Align = AttrAlign;
1872 Info.AlignIsRequired = true;
1873 }
1874 return Info;
1875 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001876
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001877 const RecordType *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001878 const RecordDecl *RD = RT->getDecl();
1879 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001880 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001881 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001882 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001883 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001884 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001885
Chris Lattner63d2b362009-10-22 05:17:15 +00001886 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001887 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1888 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001889
Richard Smith600b5262017-01-26 20:40:47 +00001890 case Type::Auto:
1891 case Type::DeducedTemplateSpecialization: {
1892 const DeducedType *A = cast<DeducedType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001893 assert(!A->getDeducedType().isNull() &&
1894 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001895 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001896 }
1897
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001898 case Type::Paren:
1899 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1900
Manman Rene6be26c2016-09-13 17:25:08 +00001901 case Type::ObjCTypeParam:
1902 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
1903
Douglas Gregoref462e62009-04-30 17:32:17 +00001904 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001905 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001906 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001907 // If the typedef has an aligned attribute on it, it overrides any computed
1908 // alignment we have. This violates the GCC documentation (which says that
1909 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001910 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001911 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001912 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001913 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001914 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001915 AlignIsRequired = Info.AlignIsRequired;
1916 }
David Majnemer34b57492014-07-30 01:30:47 +00001917 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001918 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001919 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001920
Abramo Bagnara6150c882010-05-11 21:36:43 +00001921 case Type::Elaborated:
1922 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001923
John McCall81904512011-01-06 01:58:22 +00001924 case Type::Attributed:
1925 return getTypeInfo(
1926 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1927
Eli Friedman0dfb8892011-10-06 23:00:33 +00001928 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001929 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001930 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1931 Width = Info.Width;
1932 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001933
1934 // If the size of the type doesn't exceed the platform's max
1935 // atomic promotion width, make the size and alignment more
1936 // favorable to atomic operations:
1937 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1938 // Round the size up to a power of 2.
1939 if (!llvm::isPowerOf2_64(Width))
1940 Width = llvm::NextPowerOf2(Width);
1941
1942 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001943 Align = static_cast<unsigned>(Width);
1944 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001945 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00001946 break;
1947
1948 case Type::Pipe: {
Anastasia Stulovab3398932017-06-05 11:27:03 +00001949 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
1950 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
Xiuli Pan9c14e282016-01-09 12:53:17 +00001951 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001952
Douglas Gregoref462e62009-04-30 17:32:17 +00001953 }
Mike Stump11289f42009-09-09 15:08:12 +00001954
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001955 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001956 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001957}
1958
Alexey Bataev00396512015-07-02 03:40:19 +00001959unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1960 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1961 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1962 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1963 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1964 getTargetInfo().getABI() == "elfv1-qpx" &&
1965 T->isSpecificBuiltinType(BuiltinType::Double))
1966 SimdAlign = 256;
1967 return SimdAlign;
1968}
1969
Ken Dyckcc56c542011-01-15 18:38:59 +00001970/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1971CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1972 return CharUnits::fromQuantity(BitSize / getCharWidth());
1973}
1974
Ken Dyckb0fcc592011-02-11 01:54:29 +00001975/// toBits - Convert a size in characters to a size in characters.
1976int64_t ASTContext::toBits(CharUnits CharSize) const {
1977 return CharSize.getQuantity() * getCharWidth();
1978}
1979
Ken Dyck8c89d592009-12-22 14:23:30 +00001980/// getTypeSizeInChars - Return the size of the specified type, in characters.
1981/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001982CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001983 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001984}
Jay Foad39c79802011-01-12 09:06:06 +00001985CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001986 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001987}
1988
Ken Dycka6046ab2010-01-26 17:25:18 +00001989/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001990/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001991CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001992 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001993}
Jay Foad39c79802011-01-12 09:06:06 +00001994CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001995 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001996}
1997
Chris Lattnera3402cd2009-01-27 18:08:34 +00001998/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1999/// type for the current target in bits. This can be different than the ABI
2000/// alignment in cases where it is beneficial for performance to overalign
2001/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00002002unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00002003 TypeInfo TI = getTypeInfo(T);
2004 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00002005
David Majnemere1544562015-04-24 01:25:05 +00002006 T = T->getBaseElementTypeUnsafe();
2007
2008 // The preferred alignment of member pointers is that of a pointer.
2009 if (T->isMemberPointerType())
2010 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2011
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00002012 if (!Target->allowsLargerPreferedTypeAlignment())
2013 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00002014
Eli Friedman7ab09572009-05-25 21:27:19 +00002015 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00002016 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00002017 T = CT->getElementType().getTypePtr();
David Majnemer475b25e2015-01-21 10:54:38 +00002018 if (const EnumType *ET = T->getAs<EnumType>())
2019 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00002020 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00002021 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2022 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00002023 // Don't increase the alignment if an alignment attribute was specified on a
2024 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00002025 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00002026 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00002027
Chris Lattnera3402cd2009-01-27 18:08:34 +00002028 return ABIAlign;
2029}
2030
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002031/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2032/// for __attribute__((aligned)) on this target, to be used if no alignment
2033/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00002034unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002035 return getTargetInfo().getDefaultAlignForAttributeAligned();
2036}
2037
Ulrich Weigandfa806422013-05-06 16:23:57 +00002038/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2039/// to a global variable of the specified type.
2040unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2041 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
2042}
2043
2044/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2045/// should be given to a global variable of the specified type.
2046CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2047 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2048}
2049
David Majnemer08ef2ba2015-06-23 20:34:18 +00002050CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2051 CharUnits Offset = CharUnits::Zero();
2052 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2053 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2054 Offset += Layout->getBaseClassOffset(Base);
2055 Layout = &getASTRecordLayout(Base);
2056 }
2057 return Offset;
2058}
2059
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002060/// DeepCollectObjCIvars -
2061/// This routine first collects all declared, but not synthesized, ivars in
2062/// super class and then collects all ivars, including those synthesized for
2063/// current class. This routine is used for implementation of current class
2064/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002065///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002066void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2067 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00002068 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002069 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2070 DeepCollectObjCIvars(SuperClass, false, Ivars);
2071 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00002072 for (const auto *I : OI->ivars())
2073 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002074 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002075 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00002076 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002077 Iv= Iv->getNextIvar())
2078 Ivars.push_back(Iv);
2079 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002080}
2081
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002082/// CollectInheritedProtocols - Collect all protocols in current class and
2083/// those inherited by it.
2084void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00002085 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002086 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002087 // We can use protocol_iterator here instead of
2088 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002089 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002090 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00002091 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002092
2093 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00002094 for (const auto *Cat : OI->visible_categories())
2095 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002096
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002097 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2098 while (SD) {
2099 CollectInheritedProtocols(SD, Protocols);
2100 SD = SD->getSuperClass();
2101 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002102 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002103 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002104 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002105 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002106 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002107 // Insert the protocol.
2108 if (!Protocols.insert(
2109 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2110 return;
2111
2112 for (auto *Proto : OP->protocols())
2113 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002114 }
2115}
2116
Jay Foad39c79802011-01-12 09:06:06 +00002117unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002118 unsigned count = 0;
2119 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002120 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002121 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002122
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002123 // Count ivar defined in this class's implementation. This
2124 // includes synthesized ivars.
2125 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002126 count += ImplDecl->ivar_size();
2127
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002128 return count;
2129}
2130
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002131bool ASTContext::isSentinelNullExpr(const Expr *E) {
2132 if (!E)
2133 return false;
2134
2135 // nullptr_t is always treated as null.
2136 if (E->getType()->isNullPtrType()) return true;
2137
2138 if (E->getType()->isAnyPointerType() &&
2139 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2140 Expr::NPC_ValueDependentIsNull))
2141 return true;
2142
2143 // Unfortunately, __null has type 'int'.
2144 if (isa<GNUNullExpr>(E)) return true;
2145
2146 return false;
2147}
2148
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002149/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
2150ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2151 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2152 I = ObjCImpls.find(D);
2153 if (I != ObjCImpls.end())
2154 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002155 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002156}
2157/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
2158ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2159 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2160 I = ObjCImpls.find(D);
2161 if (I != ObjCImpls.end())
2162 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002163 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002164}
2165
2166/// \brief Set the implementation of ObjCInterfaceDecl.
2167void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2168 ObjCImplementationDecl *ImplD) {
2169 assert(IFaceD && ImplD && "Passed null params");
2170 ObjCImpls[IFaceD] = ImplD;
2171}
2172/// \brief Set the implementation of ObjCCategoryDecl.
2173void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2174 ObjCCategoryImplDecl *ImplD) {
2175 assert(CatD && ImplD && "Passed null params");
2176 ObjCImpls[CatD] = ImplD;
2177}
2178
Chandler Carruth21c90602015-12-30 03:24:14 +00002179const ObjCMethodDecl *
2180ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2181 return ObjCMethodRedecls.lookup(MD);
2182}
2183
2184void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2185 const ObjCMethodDecl *Redecl) {
2186 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2187 ObjCMethodRedecls[MD] = Redecl;
2188}
2189
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002190const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2191 const NamedDecl *ND) const {
2192 if (const ObjCInterfaceDecl *ID =
2193 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002194 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002195 if (const ObjCCategoryDecl *CD =
2196 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002197 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002198 if (const ObjCImplDecl *IMD =
2199 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002200 return IMD->getClassInterface();
2201
Craig Topper36250ad2014-05-12 05:36:57 +00002202 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002203}
2204
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002205/// \brief Get the copy initialization expression of VarDecl,or NULL if
2206/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00002207Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002208 assert(VD && "Passed null params");
2209 assert(VD->hasAttr<BlocksAttr>() &&
2210 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00002211 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002212 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00002213 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002214}
2215
2216/// \brief Set the copy inialization expression of a block var decl.
2217void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2218 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002219 assert(VD->hasAttr<BlocksAttr>() &&
2220 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002221 BlockVarCopyInits[VD] = Init;
2222}
2223
John McCallbcd03502009-12-07 02:54:59 +00002224TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002225 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002226 if (!DataSize)
2227 DataSize = TypeLoc::getFullDataSizeForType(T);
2228 else
2229 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002230 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002231
John McCallbcd03502009-12-07 02:54:59 +00002232 TypeSourceInfo *TInfo =
2233 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2234 new (TInfo) TypeSourceInfo(T);
2235 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002236}
2237
John McCallbcd03502009-12-07 02:54:59 +00002238TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002239 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002240 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002241 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002242 return DI;
2243}
2244
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002245const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002246ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002247 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002248}
2249
2250const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002251ASTContext::getASTObjCImplementationLayout(
2252 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002253 return getObjCLayout(D->getClassInterface(), D);
2254}
2255
Chris Lattner983a8bb2007-07-13 22:13:22 +00002256//===----------------------------------------------------------------------===//
2257// Type creation/memoization methods
2258//===----------------------------------------------------------------------===//
2259
Jay Foad39c79802011-01-12 09:06:06 +00002260QualType
John McCall33ddac02011-01-19 10:06:00 +00002261ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2262 unsigned fastQuals = quals.getFastQualifiers();
2263 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002264
2265 // Check if we've already instantiated this type.
2266 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002267 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002268 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002269 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2270 assert(eq->getQualifiers() == quals);
2271 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002272 }
2273
John McCall33ddac02011-01-19 10:06:00 +00002274 // If the base type is not canonical, make the appropriate canonical type.
2275 QualType canon;
2276 if (!baseType->isCanonicalUnqualified()) {
2277 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002278 canonSplit.Quals.addConsistentQualifiers(quals);
2279 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002280
2281 // Re-find the insert position.
2282 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2283 }
2284
2285 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2286 ExtQualNodes.InsertNode(eq, insertPos);
2287 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002288}
2289
Jay Foad39c79802011-01-12 09:06:06 +00002290QualType
2291ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002292 QualType CanT = getCanonicalType(T);
2293 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002294 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002295
John McCall8ccfcb52009-09-24 19:53:00 +00002296 // If we are composing extended qualifiers together, merge together
2297 // into one ExtQuals node.
2298 QualifierCollector Quals;
2299 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002300
John McCall8ccfcb52009-09-24 19:53:00 +00002301 // If this type already has an address space specified, it cannot get
2302 // another one.
2303 assert(!Quals.hasAddressSpace() &&
2304 "Type cannot be in multiple addr spaces!");
2305 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002306
John McCall8ccfcb52009-09-24 19:53:00 +00002307 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002308}
2309
Chris Lattnerd60183d2009-02-18 22:53:11 +00002310QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002311 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002312 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002313 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002314 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002315
John McCall53fa7142010-12-24 02:08:15 +00002316 if (const PointerType *ptr = T->getAs<PointerType>()) {
2317 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002318 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002319 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2320 return getPointerType(ResultType);
2321 }
2322 }
Mike Stump11289f42009-09-09 15:08:12 +00002323
John McCall8ccfcb52009-09-24 19:53:00 +00002324 // If we are composing extended qualifiers together, merge together
2325 // into one ExtQuals node.
2326 QualifierCollector Quals;
2327 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002328
John McCall8ccfcb52009-09-24 19:53:00 +00002329 // If this type already has an ObjCGC specified, it cannot get
2330 // another one.
2331 assert(!Quals.hasObjCGCAttr() &&
2332 "Type cannot have multiple ObjCGCs!");
2333 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002334
John McCall8ccfcb52009-09-24 19:53:00 +00002335 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002336}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002337
John McCall4f5019e2010-12-19 02:44:49 +00002338const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2339 FunctionType::ExtInfo Info) {
2340 if (T->getExtInfo() == Info)
2341 return T;
2342
2343 QualType Result;
2344 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002345 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002346 } else {
2347 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2348 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2349 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002350 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002351 }
2352
2353 return cast<FunctionType>(Result.getTypePtr());
2354}
2355
Richard Smith2a7d4812013-05-04 07:00:32 +00002356void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2357 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002358 FD = FD->getMostRecentDecl();
2359 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002360 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2361 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002362 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002363 if (FunctionDecl *Next = FD->getPreviousDecl())
2364 FD = Next;
2365 else
2366 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002367 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002368 if (ASTMutationListener *L = getASTMutationListener())
2369 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002370}
2371
Richard Smith0b3a4622014-11-13 20:01:57 +00002372/// Get a function type and produce the equivalent function type with the
2373/// specified exception specification. Type sugar that can be present on a
2374/// declaration of a function with an exception specification is permitted
2375/// and preserved. Other type sugar (for instance, typedefs) is not.
2376static QualType getFunctionTypeWithExceptionSpec(
2377 ASTContext &Context, QualType Orig,
2378 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2379 // Might have some parens.
2380 if (auto *PT = dyn_cast<ParenType>(Orig))
2381 return Context.getParenType(
2382 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2383
2384 // Might have a calling-convention attribute.
2385 if (auto *AT = dyn_cast<AttributedType>(Orig))
2386 return Context.getAttributedType(
2387 AT->getAttrKind(),
2388 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2389 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2390 ESI));
2391
2392 // Anything else must be a function type. Rebuild it with the new exception
2393 // specification.
2394 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2395 return Context.getFunctionType(
2396 Proto->getReturnType(), Proto->getParamTypes(),
2397 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2398}
2399
Richard Smithdfe85e22016-12-15 02:35:39 +00002400bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2401 QualType U) {
2402 return hasSameType(T, U) ||
2403 (getLangOpts().CPlusPlus1z &&
2404 hasSameType(getFunctionTypeWithExceptionSpec(*this, T, EST_None),
2405 getFunctionTypeWithExceptionSpec(*this, U, EST_None)));
2406}
2407
Richard Smith0b3a4622014-11-13 20:01:57 +00002408void ASTContext::adjustExceptionSpec(
2409 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2410 bool AsWritten) {
2411 // Update the type.
2412 QualType Updated =
2413 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2414 FD->setType(Updated);
2415
2416 if (!AsWritten)
2417 return;
2418
2419 // Update the type in the type source information too.
2420 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2421 // If the type and the type-as-written differ, we may need to update
2422 // the type-as-written too.
2423 if (TSInfo->getType() != FD->getType())
2424 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2425
2426 // FIXME: When we get proper type location information for exceptions,
2427 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2428 // up the TypeSourceInfo;
2429 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2430 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2431 "TypeLoc size mismatch from updating exception specification");
2432 TSInfo->overrideType(Updated);
2433 }
2434}
2435
Chris Lattnerc6395932007-06-22 20:56:16 +00002436/// getComplexType - Return the uniqued reference to the type for a complex
2437/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002438QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002439 // Unique pointers, to guarantee there is only one pointer of a particular
2440 // structure.
2441 llvm::FoldingSetNodeID ID;
2442 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002443
Craig Topper36250ad2014-05-12 05:36:57 +00002444 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002445 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2446 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002447
Chris Lattnerc6395932007-06-22 20:56:16 +00002448 // If the pointee type isn't canonical, this won't be a canonical type either,
2449 // so fill in the canonical type field.
2450 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002451 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002452 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002453
Chris Lattnerc6395932007-06-22 20:56:16 +00002454 // Get the new insert position for the node we care about.
2455 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002456 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002457 }
John McCall90d1c2d2009-09-24 23:30:46 +00002458 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002459 Types.push_back(New);
2460 ComplexTypes.InsertNode(New, InsertPos);
2461 return QualType(New, 0);
2462}
2463
Chris Lattner970e54e2006-11-12 00:37:36 +00002464/// getPointerType - Return the uniqued reference to the type for a pointer to
2465/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002466QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002467 // Unique pointers, to guarantee there is only one pointer of a particular
2468 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002469 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002470 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002471
Craig Topper36250ad2014-05-12 05:36:57 +00002472 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002473 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002474 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002475
Chris Lattner7ccecb92006-11-12 08:50:50 +00002476 // If the pointee type isn't canonical, this won't be a canonical type either,
2477 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002478 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002479 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002480 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002481
Bob Wilsonc8541f22013-03-15 17:12:43 +00002482 // Get the new insert position for the node we care about.
2483 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002484 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002485 }
John McCall90d1c2d2009-09-24 23:30:46 +00002486 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002487 Types.push_back(New);
2488 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002489 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002490}
2491
Reid Kleckner0503a872013-12-05 01:23:43 +00002492QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2493 llvm::FoldingSetNodeID ID;
2494 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002495 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002496 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2497 if (AT)
2498 return QualType(AT, 0);
2499
2500 QualType Canonical = getCanonicalType(New);
2501
2502 // Get the new insert position for the node we care about.
2503 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002504 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002505
2506 AT = new (*this, TypeAlignment)
2507 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2508 Types.push_back(AT);
2509 AdjustedTypes.InsertNode(AT, InsertPos);
2510 return QualType(AT, 0);
2511}
2512
Reid Kleckner8a365022013-06-24 17:51:48 +00002513QualType ASTContext::getDecayedType(QualType T) const {
2514 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2515
Reid Kleckner8a365022013-06-24 17:51:48 +00002516 QualType Decayed;
2517
2518 // C99 6.7.5.3p7:
2519 // A declaration of a parameter as "array of type" shall be
2520 // adjusted to "qualified pointer to type", where the type
2521 // qualifiers (if any) are those specified within the [ and ] of
2522 // the array type derivation.
2523 if (T->isArrayType())
2524 Decayed = getArrayDecayedType(T);
2525
2526 // C99 6.7.5.3p8:
2527 // A declaration of a parameter as "function returning type"
2528 // shall be adjusted to "pointer to function returning type", as
2529 // in 6.3.2.1.
2530 if (T->isFunctionType())
2531 Decayed = getPointerType(T);
2532
Reid Kleckner0503a872013-12-05 01:23:43 +00002533 llvm::FoldingSetNodeID ID;
2534 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002535 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002536 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2537 if (AT)
2538 return QualType(AT, 0);
2539
Reid Kleckner8a365022013-06-24 17:51:48 +00002540 QualType Canonical = getCanonicalType(Decayed);
2541
2542 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002543 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002544 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002545
Reid Kleckner0503a872013-12-05 01:23:43 +00002546 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2547 Types.push_back(AT);
2548 AdjustedTypes.InsertNode(AT, InsertPos);
2549 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002550}
2551
Mike Stump11289f42009-09-09 15:08:12 +00002552/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002553/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002554QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002555 assert(T->isFunctionType() && "block of function types only");
2556 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002557 // structure.
2558 llvm::FoldingSetNodeID ID;
2559 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002560
Craig Topper36250ad2014-05-12 05:36:57 +00002561 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002562 if (BlockPointerType *PT =
2563 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2564 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002565
2566 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002567 // type either so fill in the canonical type field.
2568 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002569 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002570 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002571
Steve Naroffec33ed92008-08-27 16:04:49 +00002572 // Get the new insert position for the node we care about.
2573 BlockPointerType *NewIP =
2574 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002575 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002576 }
John McCall90d1c2d2009-09-24 23:30:46 +00002577 BlockPointerType *New
2578 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002579 Types.push_back(New);
2580 BlockPointerTypes.InsertNode(New, InsertPos);
2581 return QualType(New, 0);
2582}
2583
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002584/// getLValueReferenceType - Return the uniqued reference to the type for an
2585/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002586QualType
2587ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002588 assert(getCanonicalType(T) != OverloadTy &&
2589 "Unresolved overloaded function type");
2590
Bill Wendling3708c182007-05-27 10:15:43 +00002591 // Unique pointers, to guarantee there is only one pointer of a particular
2592 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002593 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002594 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002595
Craig Topper36250ad2014-05-12 05:36:57 +00002596 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002597 if (LValueReferenceType *RT =
2598 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002599 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002600
John McCallfc93cf92009-10-22 22:37:11 +00002601 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2602
Bill Wendling3708c182007-05-27 10:15:43 +00002603 // If the referencee type isn't canonical, this won't be a canonical type
2604 // either, so fill in the canonical type field.
2605 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002606 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2607 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2608 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002609
Bill Wendling3708c182007-05-27 10:15:43 +00002610 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002611 LValueReferenceType *NewIP =
2612 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002613 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002614 }
2615
John McCall90d1c2d2009-09-24 23:30:46 +00002616 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002617 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2618 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002619 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002620 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002621
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002622 return QualType(New, 0);
2623}
2624
2625/// getRValueReferenceType - Return the uniqued reference to the type for an
2626/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002627QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002628 // Unique pointers, to guarantee there is only one pointer of a particular
2629 // structure.
2630 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002631 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002632
Craig Topper36250ad2014-05-12 05:36:57 +00002633 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002634 if (RValueReferenceType *RT =
2635 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2636 return QualType(RT, 0);
2637
John McCallfc93cf92009-10-22 22:37:11 +00002638 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2639
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002640 // If the referencee type isn't canonical, this won't be a canonical type
2641 // either, so fill in the canonical type field.
2642 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002643 if (InnerRef || !T.isCanonical()) {
2644 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2645 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002646
2647 // Get the new insert position for the node we care about.
2648 RValueReferenceType *NewIP =
2649 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002650 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002651 }
2652
John McCall90d1c2d2009-09-24 23:30:46 +00002653 RValueReferenceType *New
2654 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002655 Types.push_back(New);
2656 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002657 return QualType(New, 0);
2658}
2659
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002660/// getMemberPointerType - Return the uniqued reference to the type for a
2661/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002662QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002663 // Unique pointers, to guarantee there is only one pointer of a particular
2664 // structure.
2665 llvm::FoldingSetNodeID ID;
2666 MemberPointerType::Profile(ID, T, Cls);
2667
Craig Topper36250ad2014-05-12 05:36:57 +00002668 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002669 if (MemberPointerType *PT =
2670 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2671 return QualType(PT, 0);
2672
2673 // If the pointee or class type isn't canonical, this won't be a canonical
2674 // type either, so fill in the canonical type field.
2675 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002676 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002677 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2678
2679 // Get the new insert position for the node we care about.
2680 MemberPointerType *NewIP =
2681 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002682 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002683 }
John McCall90d1c2d2009-09-24 23:30:46 +00002684 MemberPointerType *New
2685 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002686 Types.push_back(New);
2687 MemberPointerTypes.InsertNode(New, InsertPos);
2688 return QualType(New, 0);
2689}
2690
Mike Stump11289f42009-09-09 15:08:12 +00002691/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002692/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002693QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002694 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002695 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002696 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002697 assert((EltTy->isDependentType() ||
2698 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002699 "Constant array of VLAs is illegal!");
2700
Chris Lattnere2df3f92009-05-13 04:12:56 +00002701 // Convert the array size into a canonical width matching the pointer size for
2702 // the target.
2703 llvm::APInt ArySize(ArySizeIn);
Konstantin Zhuravlyov9c1e3102017-03-21 18:55:39 +00002704 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
Mike Stump11289f42009-09-09 15:08:12 +00002705
Chris Lattner23b7eb62007-06-15 23:05:46 +00002706 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002707 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002708
Craig Topper36250ad2014-05-12 05:36:57 +00002709 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002710 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002711 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002712 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002713
John McCall33ddac02011-01-19 10:06:00 +00002714 // If the element type isn't canonical or has qualifiers, this won't
2715 // be a canonical type either, so fill in the canonical type field.
2716 QualType Canon;
2717 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2718 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002719 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002720 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002721 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002722
Chris Lattner36f8e652007-01-27 08:31:04 +00002723 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002724 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002725 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002726 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002727 }
Mike Stump11289f42009-09-09 15:08:12 +00002728
John McCall90d1c2d2009-09-24 23:30:46 +00002729 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002730 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002731 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002732 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002733 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002734}
2735
John McCall06549462011-01-18 08:40:38 +00002736/// getVariableArrayDecayedType - Turns the given type, which may be
2737/// variably-modified, into the corresponding type with all the known
2738/// sizes replaced with [*].
2739QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2740 // Vastly most common case.
2741 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002742
John McCall06549462011-01-18 08:40:38 +00002743 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002744
John McCall06549462011-01-18 08:40:38 +00002745 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002746 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002747 switch (ty->getTypeClass()) {
2748#define TYPE(Class, Base)
2749#define ABSTRACT_TYPE(Class, Base)
2750#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2751#include "clang/AST/TypeNodes.def"
2752 llvm_unreachable("didn't desugar past all non-canonical types?");
2753
2754 // These types should never be variably-modified.
2755 case Type::Builtin:
2756 case Type::Complex:
2757 case Type::Vector:
2758 case Type::ExtVector:
2759 case Type::DependentSizedExtVector:
2760 case Type::ObjCObject:
2761 case Type::ObjCInterface:
2762 case Type::ObjCObjectPointer:
2763 case Type::Record:
2764 case Type::Enum:
2765 case Type::UnresolvedUsing:
2766 case Type::TypeOfExpr:
2767 case Type::TypeOf:
2768 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002769 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002770 case Type::DependentName:
2771 case Type::InjectedClassName:
2772 case Type::TemplateSpecialization:
2773 case Type::DependentTemplateSpecialization:
2774 case Type::TemplateTypeParm:
2775 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002776 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00002777 case Type::DeducedTemplateSpecialization:
John McCall06549462011-01-18 08:40:38 +00002778 case Type::PackExpansion:
2779 llvm_unreachable("type should never be variably-modified");
2780
2781 // These types can be variably-modified but should never need to
2782 // further decay.
2783 case Type::FunctionNoProto:
2784 case Type::FunctionProto:
2785 case Type::BlockPointer:
2786 case Type::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00002787 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00002788 return type;
2789
2790 // These types can be variably-modified. All these modifications
2791 // preserve structure except as noted by comments.
2792 // TODO: if we ever care about optimizing VLAs, there are no-op
2793 // optimizations available here.
2794 case Type::Pointer:
2795 result = getPointerType(getVariableArrayDecayedType(
2796 cast<PointerType>(ty)->getPointeeType()));
2797 break;
2798
2799 case Type::LValueReference: {
2800 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2801 result = getLValueReferenceType(
2802 getVariableArrayDecayedType(lv->getPointeeType()),
2803 lv->isSpelledAsLValue());
2804 break;
2805 }
2806
2807 case Type::RValueReference: {
2808 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2809 result = getRValueReferenceType(
2810 getVariableArrayDecayedType(lv->getPointeeType()));
2811 break;
2812 }
2813
Eli Friedman0dfb8892011-10-06 23:00:33 +00002814 case Type::Atomic: {
2815 const AtomicType *at = cast<AtomicType>(ty);
2816 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2817 break;
2818 }
2819
John McCall06549462011-01-18 08:40:38 +00002820 case Type::ConstantArray: {
2821 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2822 result = getConstantArrayType(
2823 getVariableArrayDecayedType(cat->getElementType()),
2824 cat->getSize(),
2825 cat->getSizeModifier(),
2826 cat->getIndexTypeCVRQualifiers());
2827 break;
2828 }
2829
2830 case Type::DependentSizedArray: {
2831 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2832 result = getDependentSizedArrayType(
2833 getVariableArrayDecayedType(dat->getElementType()),
2834 dat->getSizeExpr(),
2835 dat->getSizeModifier(),
2836 dat->getIndexTypeCVRQualifiers(),
2837 dat->getBracketsRange());
2838 break;
2839 }
2840
2841 // Turn incomplete types into [*] types.
2842 case Type::IncompleteArray: {
2843 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2844 result = getVariableArrayType(
2845 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002846 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002847 ArrayType::Normal,
2848 iat->getIndexTypeCVRQualifiers(),
2849 SourceRange());
2850 break;
2851 }
2852
2853 // Turn VLA types into [*] types.
2854 case Type::VariableArray: {
2855 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2856 result = getVariableArrayType(
2857 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002858 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002859 ArrayType::Star,
2860 vat->getIndexTypeCVRQualifiers(),
2861 vat->getBracketsRange());
2862 break;
2863 }
2864 }
2865
2866 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002867 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002868}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002869
Steve Naroffcadebd02007-08-30 18:14:25 +00002870/// getVariableArrayType - Returns a non-unique reference to the type for a
2871/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002872QualType ASTContext::getVariableArrayType(QualType EltTy,
2873 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002874 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002875 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002876 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002877 // Since we don't unique expressions, it isn't possible to unique VLA's
2878 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002879 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002880
John McCall33ddac02011-01-19 10:06:00 +00002881 // Be sure to pull qualifiers off the element type.
2882 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2883 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002884 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002885 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002886 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002887 }
2888
John McCall90d1c2d2009-09-24 23:30:46 +00002889 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002890 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002891
2892 VariableArrayTypes.push_back(New);
2893 Types.push_back(New);
2894 return QualType(New, 0);
2895}
2896
Douglas Gregor4619e432008-12-05 23:32:09 +00002897/// getDependentSizedArrayType - Returns a non-unique reference to
2898/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002899/// type.
John McCall33ddac02011-01-19 10:06:00 +00002900QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2901 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002902 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002903 unsigned elementTypeQuals,
2904 SourceRange brackets) const {
2905 assert((!numElements || numElements->isTypeDependent() ||
2906 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002907 "Size must be type- or value-dependent!");
2908
John McCall33ddac02011-01-19 10:06:00 +00002909 // Dependently-sized array types that do not have a specified number
2910 // of elements will have their sizes deduced from a dependent
2911 // initializer. We do no canonicalization here at all, which is okay
2912 // because they can't be used in most locations.
2913 if (!numElements) {
2914 DependentSizedArrayType *newType
2915 = new (*this, TypeAlignment)
2916 DependentSizedArrayType(*this, elementType, QualType(),
2917 numElements, ASM, elementTypeQuals,
2918 brackets);
2919 Types.push_back(newType);
2920 return QualType(newType, 0);
2921 }
2922
2923 // Otherwise, we actually build a new type every time, but we
2924 // also build a canonical type.
2925
2926 SplitQualType canonElementType = getCanonicalType(elementType).split();
2927
Craig Topper36250ad2014-05-12 05:36:57 +00002928 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002929 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002930 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002931 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002932 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002933
John McCall33ddac02011-01-19 10:06:00 +00002934 // Look for an existing type with these properties.
2935 DependentSizedArrayType *canonTy =
2936 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002937
John McCall33ddac02011-01-19 10:06:00 +00002938 // If we don't have one, build one.
2939 if (!canonTy) {
2940 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002941 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002942 QualType(), numElements, ASM, elementTypeQuals,
2943 brackets);
2944 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2945 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002946 }
2947
John McCall33ddac02011-01-19 10:06:00 +00002948 // Apply qualifiers from the element type to the array.
2949 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002950 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002951
David Majnemer16a74702015-07-24 05:54:19 +00002952 // If we didn't need extra canonicalization for the element type or the size
2953 // expression, then just use that as our result.
2954 if (QualType(canonElementType.Ty, 0) == elementType &&
2955 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00002956 return canon;
2957
2958 // Otherwise, we need to build a type which follows the spelling
2959 // of the element type.
2960 DependentSizedArrayType *sugaredType
2961 = new (*this, TypeAlignment)
2962 DependentSizedArrayType(*this, elementType, canon, numElements,
2963 ASM, elementTypeQuals, brackets);
2964 Types.push_back(sugaredType);
2965 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002966}
2967
John McCall33ddac02011-01-19 10:06:00 +00002968QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002969 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002970 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002971 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002972 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002973
Craig Topper36250ad2014-05-12 05:36:57 +00002974 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002975 if (IncompleteArrayType *iat =
2976 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2977 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002978
2979 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002980 // either, so fill in the canonical type field. We also have to pull
2981 // qualifiers off the element type.
2982 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002983
John McCall33ddac02011-01-19 10:06:00 +00002984 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2985 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002986 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002987 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002988 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002989
2990 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002991 IncompleteArrayType *existing =
2992 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2993 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002994 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002995
John McCall33ddac02011-01-19 10:06:00 +00002996 IncompleteArrayType *newType = new (*this, TypeAlignment)
2997 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002998
John McCall33ddac02011-01-19 10:06:00 +00002999 IncompleteArrayTypes.InsertNode(newType, insertPos);
3000 Types.push_back(newType);
3001 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00003002}
3003
Steve Naroff91fcddb2007-07-18 18:00:27 +00003004/// getVectorType - Return the unique reference to a vector type of
3005/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00003006QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00003007 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00003008 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00003009
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003010 // Check if we've already instantiated a vector of this type.
3011 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00003012 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00003013
Craig Topper36250ad2014-05-12 05:36:57 +00003014 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003015 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3016 return QualType(VTP, 0);
3017
3018 // If the element type isn't canonical, this won't be a canonical type either,
3019 // so fill in the canonical type field.
3020 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00003021 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00003022 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00003023
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003024 // Get the new insert position for the node we care about.
3025 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003026 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003027 }
John McCall90d1c2d2009-09-24 23:30:46 +00003028 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00003029 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003030 VectorTypes.InsertNode(New, InsertPos);
3031 Types.push_back(New);
3032 return QualType(New, 0);
3033}
3034
Nate Begemance4d7fc2008-04-18 23:10:10 +00003035/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00003036/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00003037QualType
3038ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00003039 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00003040
Steve Naroff91fcddb2007-07-18 18:00:27 +00003041 // Check if we've already instantiated a vector of this type.
3042 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00003043 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003044 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00003045 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003046 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3047 return QualType(VTP, 0);
3048
3049 // If the element type isn't canonical, this won't be a canonical type either,
3050 // so fill in the canonical type field.
3051 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003052 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00003053 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00003054
Steve Naroff91fcddb2007-07-18 18:00:27 +00003055 // Get the new insert position for the node we care about.
3056 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003057 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003058 }
John McCall90d1c2d2009-09-24 23:30:46 +00003059 ExtVectorType *New = new (*this, TypeAlignment)
3060 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00003061 VectorTypes.InsertNode(New, InsertPos);
3062 Types.push_back(New);
3063 return QualType(New, 0);
3064}
3065
Jay Foad39c79802011-01-12 09:06:06 +00003066QualType
3067ASTContext::getDependentSizedExtVectorType(QualType vecType,
3068 Expr *SizeExpr,
3069 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00003070 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003071 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00003072 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003073
Craig Topper36250ad2014-05-12 05:36:57 +00003074 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00003075 DependentSizedExtVectorType *Canon
3076 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3077 DependentSizedExtVectorType *New;
3078 if (Canon) {
3079 // We already have a canonical version of this array type; use it as
3080 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00003081 New = new (*this, TypeAlignment)
3082 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3083 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003084 } else {
3085 QualType CanonVecTy = getCanonicalType(vecType);
3086 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00003087 New = new (*this, TypeAlignment)
3088 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3089 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003090
3091 DependentSizedExtVectorType *CanonCheck
3092 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3093 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3094 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00003095 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3096 } else {
3097 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3098 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00003099 New = new (*this, TypeAlignment)
3100 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003101 }
3102 }
Mike Stump11289f42009-09-09 15:08:12 +00003103
Douglas Gregor758a8692009-06-17 21:51:59 +00003104 Types.push_back(New);
3105 return QualType(New, 0);
3106}
3107
John McCall18afab72016-03-01 00:49:02 +00003108/// \brief Determine whether \p T is canonical as the result type of a function.
3109static bool isCanonicalResultType(QualType T) {
3110 return T.isCanonical() &&
3111 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3112 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3113}
3114
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003115/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003116///
Jay Foad39c79802011-01-12 09:06:06 +00003117QualType
3118ASTContext::getFunctionNoProtoType(QualType ResultTy,
3119 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003120 // Unique functions, to guarantee there is only one function of a particular
3121 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003122 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003123 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00003124
Craig Topper36250ad2014-05-12 05:36:57 +00003125 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003126 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003127 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003128 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003129
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003130 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003131 if (!isCanonicalResultType(ResultTy)) {
3132 Canonical =
3133 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003134
Chris Lattner47955de2007-01-27 08:37:20 +00003135 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003136 FunctionNoProtoType *NewIP =
3137 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003138 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003139 }
Mike Stump11289f42009-09-09 15:08:12 +00003140
John McCall90d1c2d2009-09-24 23:30:46 +00003141 FunctionNoProtoType *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003142 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003143 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003144 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003145 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003146}
3147
Douglas Gregora602a152015-10-01 20:20:47 +00003148CanQualType
3149ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3150 CanQualType CanResultType = getCanonicalType(ResultType);
3151
3152 // Canonical result types do not have ARC lifetime qualifiers.
3153 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3154 Qualifiers Qs = CanResultType.getQualifiers();
3155 Qs.removeObjCLifetime();
3156 return CanQualType::CreateUnsafe(
3157 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3158 }
3159
3160 return CanResultType;
3161}
3162
Richard Smith3c4f8d22016-10-16 17:54:23 +00003163static bool isCanonicalExceptionSpecification(
3164 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3165 if (ESI.Type == EST_None)
3166 return true;
3167 if (!NoexceptInType)
3168 return false;
3169
3170 // C++17 onwards: exception specification is part of the type, as a simple
3171 // boolean "can this function type throw".
3172 if (ESI.Type == EST_BasicNoexcept)
3173 return true;
3174
3175 // A dynamic exception specification is canonical if it only contains pack
Richard Smith2a2cda52016-10-18 19:29:18 +00003176 // expansions (so we can't tell whether it's non-throwing) and all its
3177 // contained types are canonical.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003178 if (ESI.Type == EST_Dynamic) {
Richard Smithfda59e52016-10-26 01:05:54 +00003179 bool AnyPackExpansions = false;
3180 for (QualType ET : ESI.Exceptions) {
3181 if (!ET.isCanonical())
Richard Smith3c4f8d22016-10-16 17:54:23 +00003182 return false;
Richard Smithfda59e52016-10-26 01:05:54 +00003183 if (ET->getAs<PackExpansionType>())
3184 AnyPackExpansions = true;
3185 }
3186 return AnyPackExpansions;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003187 }
3188
Richard Smith2a2cda52016-10-18 19:29:18 +00003189 // A noexcept(expr) specification is (possibly) canonical if expr is
3190 // value-dependent.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003191 if (ESI.Type == EST_ComputedNoexcept)
3192 return ESI.NoexceptExpr && ESI.NoexceptExpr->isValueDependent();
3193
3194 return false;
3195}
3196
Richard Smith304b1242016-10-18 20:13:25 +00003197QualType ASTContext::getFunctionTypeInternal(
3198 QualType ResultTy, ArrayRef<QualType> ArgArray,
3199 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003200 size_t NumArgs = ArgArray.size();
3201
Richard Smith2a2cda52016-10-18 19:29:18 +00003202 // Unique functions, to guarantee there is only one function of a particular
3203 // structure.
3204 llvm::FoldingSetNodeID ID;
3205 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3206 *this, true);
Richard Smith3c4f8d22016-10-16 17:54:23 +00003207
Richard Smith2a2cda52016-10-18 19:29:18 +00003208 QualType Canonical;
3209 bool Unique = false;
3210
3211 void *InsertPos = nullptr;
3212 if (FunctionProtoType *FPT =
3213 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3214 QualType Existing = QualType(FPT, 0);
3215
3216 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3217 // it so long as our exception specification doesn't contain a dependent
Richard Smith304b1242016-10-18 20:13:25 +00003218 // noexcept expression, or we're just looking for a canonical type.
3219 // Otherwise, we're going to need to create a type
Richard Smith2a2cda52016-10-18 19:29:18 +00003220 // sugar node to hold the concrete expression.
Richard Smith304b1242016-10-18 20:13:25 +00003221 if (OnlyWantCanonical || EPI.ExceptionSpec.Type != EST_ComputedNoexcept ||
Richard Smith2a2cda52016-10-18 19:29:18 +00003222 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3223 return Existing;
3224
3225 // We need a new type sugar node for this one, to hold the new noexcept
3226 // expression. We do no canonicalization here, but that's OK since we don't
3227 // expect to see the same noexcept expression much more than once.
3228 Canonical = getCanonicalType(Existing);
3229 Unique = true;
3230 }
3231
3232 bool NoexceptInType = getLangOpts().CPlusPlus1z;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003233 bool IsCanonicalExceptionSpec =
3234 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3235
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003236 // Determine whether the type being created is already canonical or not.
Richard Smith2a2cda52016-10-18 19:29:18 +00003237 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
Richard Smith3c4f8d22016-10-16 17:54:23 +00003238 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003239 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003240 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003241 isCanonical = false;
3242
Richard Smith304b1242016-10-18 20:13:25 +00003243 if (OnlyWantCanonical)
3244 assert(isCanonical &&
3245 "given non-canonical parameters constructing canonical type");
3246
Richard Smith2a2cda52016-10-18 19:29:18 +00003247 // If this type isn't canonical, get the canonical version of it if we don't
3248 // already have it. The exception spec is only partially part of the
3249 // canonical type, and only in C++17 onwards.
3250 if (!isCanonical && Canonical.isNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003251 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003252 CanonicalArgs.reserve(NumArgs);
3253 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003254 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003255
Benjamin Kramer3f515cd2016-10-26 12:51:45 +00003256 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
John McCalldb40c7f2010-12-14 08:05:40 +00003257 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003258 CanonicalEPI.HasTrailingReturn = false;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003259
3260 if (IsCanonicalExceptionSpec) {
3261 // Exception spec is already OK.
3262 } else if (NoexceptInType) {
3263 switch (EPI.ExceptionSpec.Type) {
3264 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
3265 // We don't know yet. It shouldn't matter what we pick here; no-one
3266 // should ever look at this.
3267 LLVM_FALLTHROUGH;
Richard Smith2a2cda52016-10-18 19:29:18 +00003268 case EST_None: case EST_MSAny:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003269 CanonicalEPI.ExceptionSpec.Type = EST_None;
3270 break;
3271
Richard Smith2a2cda52016-10-18 19:29:18 +00003272 // A dynamic exception specification is almost always "not noexcept",
3273 // with the exception that a pack expansion might expand to no types.
3274 case EST_Dynamic: {
3275 bool AnyPacks = false;
3276 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3277 if (ET->getAs<PackExpansionType>())
3278 AnyPacks = true;
3279 ExceptionTypeStorage.push_back(getCanonicalType(ET));
3280 }
3281 if (!AnyPacks)
3282 CanonicalEPI.ExceptionSpec.Type = EST_None;
3283 else {
3284 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3285 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3286 }
3287 break;
3288 }
3289
Richard Smith3c4f8d22016-10-16 17:54:23 +00003290 case EST_DynamicNone: case EST_BasicNoexcept:
3291 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3292 break;
3293
3294 case EST_ComputedNoexcept:
3295 llvm::APSInt Value(1);
3296 auto *E = CanonicalEPI.ExceptionSpec.NoexceptExpr;
3297 if (!E || !E->isIntegerConstantExpr(Value, *this, nullptr,
3298 /*IsEvaluated*/false)) {
3299 // This noexcept specification is invalid.
3300 // FIXME: Should this be able to happen?
3301 CanonicalEPI.ExceptionSpec.Type = EST_None;
3302 break;
3303 }
3304
3305 CanonicalEPI.ExceptionSpec.Type =
3306 Value.getBoolValue() ? EST_BasicNoexcept : EST_None;
3307 break;
3308 }
Richard Smith3c4f8d22016-10-16 17:54:23 +00003309 } else {
3310 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3311 }
John McCalldb40c7f2010-12-14 08:05:40 +00003312
Douglas Gregora602a152015-10-01 20:20:47 +00003313 // Adjust the canonical function result type.
3314 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Richard Smith304b1242016-10-18 20:13:25 +00003315 Canonical =
3316 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003317
Chris Lattnerfd4de792007-01-27 01:15:32 +00003318 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003319 FunctionProtoType *NewIP =
3320 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003321 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003322 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003323
John McCall31168b02011-06-15 23:02:42 +00003324 // FunctionProtoType objects are allocated with extra bytes after
3325 // them for three variable size arrays at the end:
3326 // - parameter types
3327 // - exception types
John McCall18afab72016-03-01 00:49:02 +00003328 // - extended parameter information
John McCall31168b02011-06-15 23:02:42 +00003329 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003330 // expression, or information used to resolve the exception
3331 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00003332 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003333 NumArgs * sizeof(QualType);
John McCall18afab72016-03-01 00:49:02 +00003334
Richard Smith8acb4282014-07-31 21:57:55 +00003335 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3336 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3337 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00003338 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00003339 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00003340 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00003341 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003342 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003343 }
John McCall18afab72016-03-01 00:49:02 +00003344
3345 // Put the ExtParameterInfos last. If all were equal, it would make
3346 // more sense to put these before the exception specification, because
3347 // it's much easier to skip past them compared to the elaborate switch
3348 // required to skip the exception specification. However, all is not
3349 // equal; ExtParameterInfos are used to model very uncommon features,
3350 // and it's better not to burden the more common paths.
3351 if (EPI.ExtParameterInfos) {
3352 Size += NumArgs * sizeof(FunctionProtoType::ExtParameterInfo);
3353 }
John McCall31168b02011-06-15 23:02:42 +00003354
John McCalldb40c7f2010-12-14 08:05:40 +00003355 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003356 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003357 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003358 Types.push_back(FTP);
Richard Smith2a2cda52016-10-18 19:29:18 +00003359 if (!Unique)
3360 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003361 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003362}
Chris Lattneref51c202006-11-10 07:17:23 +00003363
Joey Goulye3c85de2016-12-01 11:30:49 +00003364QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
Xiuli Pan9c14e282016-01-09 12:53:17 +00003365 llvm::FoldingSetNodeID ID;
Joey Goulye3c85de2016-12-01 11:30:49 +00003366 PipeType::Profile(ID, T, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003367
3368 void *InsertPos = 0;
Joey Goulye3c85de2016-12-01 11:30:49 +00003369 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
Xiuli Pan9c14e282016-01-09 12:53:17 +00003370 return QualType(PT, 0);
3371
3372 // If the pipe element type isn't canonical, this won't be a canonical type
3373 // either, so fill in the canonical type field.
3374 QualType Canonical;
3375 if (!T.isCanonical()) {
Joey Goulye3c85de2016-12-01 11:30:49 +00003376 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003377
3378 // Get the new insert position for the node we care about.
Joey Goulye3c85de2016-12-01 11:30:49 +00003379 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003380 assert(!NewIP && "Shouldn't be in the map!");
3381 (void)NewIP;
3382 }
Joey Goulye3c85de2016-12-01 11:30:49 +00003383 PipeType *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003384 Types.push_back(New);
Joey Goulye3c85de2016-12-01 11:30:49 +00003385 PipeTypes.InsertNode(New, InsertPos);
Joey Gouly5788b782016-11-18 14:10:54 +00003386 return QualType(New, 0);
3387}
3388
Joey Goulye3c85de2016-12-01 11:30:49 +00003389QualType ASTContext::getReadPipeType(QualType T) const {
3390 return getPipeType(T, true);
3391}
3392
Joey Gouly5788b782016-11-18 14:10:54 +00003393QualType ASTContext::getWritePipeType(QualType T) const {
Joey Goulye3c85de2016-12-01 11:30:49 +00003394 return getPipeType(T, false);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003395}
3396
John McCalle78aac42010-03-10 03:28:59 +00003397#ifndef NDEBUG
3398static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3399 if (!isa<CXXRecordDecl>(D)) return false;
3400 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3401 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3402 return true;
3403 if (RD->getDescribedClassTemplate() &&
3404 !isa<ClassTemplateSpecializationDecl>(RD))
3405 return true;
3406 return false;
3407}
3408#endif
3409
3410/// getInjectedClassNameType - Return the unique reference to the
3411/// injected class name type for the specified templated declaration.
3412QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003413 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003414 assert(NeedsInjectedClassNameType(Decl));
3415 if (Decl->TypeForDecl) {
3416 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003417 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003418 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3419 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3420 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3421 } else {
John McCall424cec92011-01-19 06:33:43 +00003422 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003423 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003424 Decl->TypeForDecl = newType;
3425 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003426 }
3427 return QualType(Decl->TypeForDecl, 0);
3428}
3429
Douglas Gregor83a586e2008-04-13 21:07:44 +00003430/// getTypeDeclType - Return the unique reference to the type for the
3431/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003432QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003433 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003434 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003435
Richard Smithdda56e42011-04-15 14:24:37 +00003436 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003437 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003438
John McCall96f0b5f2010-03-10 06:48:02 +00003439 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3440 "Template type parameter types are always available.");
3441
John McCall81e38502010-02-16 03:57:14 +00003442 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003443 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003444 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003445 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003446 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003447 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003448 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003449 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003450 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003451 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3452 Decl->TypeForDecl = newType;
3453 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003454 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003455 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003456
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003457 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003458}
3459
Chris Lattner32d920b2007-01-26 02:01:53 +00003460/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003461/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003462QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003463ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3464 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003465 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003466
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003467 if (Canonical.isNull())
3468 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003469 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003470 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003471 Decl->TypeForDecl = newType;
3472 Types.push_back(newType);
3473 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003474}
3475
Jay Foad39c79802011-01-12 09:06:06 +00003476QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003477 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3478
Douglas Gregorec9fd132012-01-14 16:38:05 +00003479 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003480 if (PrevDecl->TypeForDecl)
3481 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3482
John McCall424cec92011-01-19 06:33:43 +00003483 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3484 Decl->TypeForDecl = newType;
3485 Types.push_back(newType);
3486 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003487}
3488
Jay Foad39c79802011-01-12 09:06:06 +00003489QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003490 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3491
Douglas Gregorec9fd132012-01-14 16:38:05 +00003492 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003493 if (PrevDecl->TypeForDecl)
3494 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3495
John McCall424cec92011-01-19 06:33:43 +00003496 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3497 Decl->TypeForDecl = newType;
3498 Types.push_back(newType);
3499 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003500}
3501
John McCall81904512011-01-06 01:58:22 +00003502QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3503 QualType modifiedType,
3504 QualType equivalentType) {
3505 llvm::FoldingSetNodeID id;
3506 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3507
Craig Topper36250ad2014-05-12 05:36:57 +00003508 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003509 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3510 if (type) return QualType(type, 0);
3511
3512 QualType canon = getCanonicalType(equivalentType);
3513 type = new (*this, TypeAlignment)
3514 AttributedType(canon, attrKind, modifiedType, equivalentType);
3515
3516 Types.push_back(type);
3517 AttributedTypes.InsertNode(type, insertPos);
3518
3519 return QualType(type, 0);
3520}
3521
John McCallcebee162009-10-18 09:09:24 +00003522/// \brief Retrieve a substitution-result type.
3523QualType
3524ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003525 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003526 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003527 && "replacement types must always be canonical");
3528
3529 llvm::FoldingSetNodeID ID;
3530 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003531 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003532 SubstTemplateTypeParmType *SubstParm
3533 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3534
3535 if (!SubstParm) {
3536 SubstParm = new (*this, TypeAlignment)
3537 SubstTemplateTypeParmType(Parm, Replacement);
3538 Types.push_back(SubstParm);
3539 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3540 }
3541
3542 return QualType(SubstParm, 0);
3543}
3544
Douglas Gregorada4b792011-01-14 02:55:32 +00003545/// \brief Retrieve a
3546QualType ASTContext::getSubstTemplateTypeParmPackType(
3547 const TemplateTypeParmType *Parm,
3548 const TemplateArgument &ArgPack) {
3549#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003550 for (const auto &P : ArgPack.pack_elements()) {
3551 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3552 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003553 }
3554#endif
3555
3556 llvm::FoldingSetNodeID ID;
3557 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003558 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003559 if (SubstTemplateTypeParmPackType *SubstParm
3560 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3561 return QualType(SubstParm, 0);
3562
3563 QualType Canon;
3564 if (!Parm->isCanonicalUnqualified()) {
3565 Canon = getCanonicalType(QualType(Parm, 0));
3566 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3567 ArgPack);
3568 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3569 }
3570
3571 SubstTemplateTypeParmPackType *SubstParm
3572 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3573 ArgPack);
3574 Types.push_back(SubstParm);
George Burgess IVb5fe8552017-06-12 17:44:30 +00003575 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
Douglas Gregorada4b792011-01-14 02:55:32 +00003576 return QualType(SubstParm, 0);
3577}
3578
Douglas Gregoreff93e02009-02-05 23:33:38 +00003579/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003580/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003581/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003582QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003583 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003584 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003585 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003586 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003587 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003588 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003589 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3590
3591 if (TypeParm)
3592 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003593
Chandler Carruth08836322011-05-01 00:51:33 +00003594 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003595 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003596 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003597
3598 TemplateTypeParmType *TypeCheck
3599 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3600 assert(!TypeCheck && "Template type parameter canonical type broken");
3601 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003602 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003603 TypeParm = new (*this, TypeAlignment)
3604 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003605
3606 Types.push_back(TypeParm);
3607 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3608
3609 return QualType(TypeParm, 0);
3610}
3611
John McCalle78aac42010-03-10 03:28:59 +00003612TypeSourceInfo *
3613ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3614 SourceLocation NameLoc,
3615 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003616 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003617 assert(!Name.getAsDependentTemplateName() &&
3618 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003619 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003620
3621 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003622 TemplateSpecializationTypeLoc TL =
3623 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003624 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003625 TL.setTemplateNameLoc(NameLoc);
3626 TL.setLAngleLoc(Args.getLAngleLoc());
3627 TL.setRAngleLoc(Args.getRAngleLoc());
3628 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3629 TL.setArgLocInfo(i, Args[i].getLocInfo());
3630 return DI;
3631}
3632
Mike Stump11289f42009-09-09 15:08:12 +00003633QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003634ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003635 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003636 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003637 assert(!Template.getAsDependentTemplateName() &&
3638 "No dependent template names here!");
John McCall6b51f282009-11-23 01:53:49 +00003639
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003640 SmallVector<TemplateArgument, 4> ArgVec;
David Majnemer6fbeee32016-07-07 04:43:07 +00003641 ArgVec.reserve(Args.size());
3642 for (const TemplateArgumentLoc &Arg : Args.arguments())
3643 ArgVec.push_back(Arg.getArgument());
John McCall0ad16662009-10-29 08:12:44 +00003644
David Majnemer6fbeee32016-07-07 04:43:07 +00003645 return getTemplateSpecializationType(Template, ArgVec, Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003646}
3647
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003648#ifndef NDEBUG
David Majnemer6fbeee32016-07-07 04:43:07 +00003649static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
3650 for (const TemplateArgument &Arg : Args)
3651 if (Arg.isPackExpansion())
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003652 return true;
3653
3654 return true;
3655}
3656#endif
3657
John McCall0ad16662009-10-29 08:12:44 +00003658QualType
3659ASTContext::getTemplateSpecializationType(TemplateName Template,
David Majnemer6fbeee32016-07-07 04:43:07 +00003660 ArrayRef<TemplateArgument> Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003661 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003662 assert(!Template.getAsDependentTemplateName() &&
3663 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003664 // Look through qualified template names.
3665 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3666 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003667
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003668 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003669 Template.getAsTemplateDecl() &&
3670 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003671 QualType CanonType;
3672 if (!Underlying.isNull())
3673 CanonType = getCanonicalType(Underlying);
3674 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003675 // We can get here with an alias template when the specialization contains
3676 // a pack expansion that does not match up with a parameter pack.
David Majnemer6fbeee32016-07-07 04:43:07 +00003677 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003678 "Caller must compute aliased type");
3679 IsTypeAlias = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00003680 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003681 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003682
Douglas Gregora8e02e72009-07-28 23:00:59 +00003683 // Allocate the (non-canonical) template specialization type, but don't
3684 // try to unique it: these types typically have location information that
3685 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003686 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
David Majnemer6fbeee32016-07-07 04:43:07 +00003687 sizeof(TemplateArgument) * Args.size() +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003688 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003689 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003690 TemplateSpecializationType *Spec
David Majnemer6fbeee32016-07-07 04:43:07 +00003691 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003692 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003693
Douglas Gregor8bf42052009-02-09 18:46:07 +00003694 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003695 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003696}
3697
David Majnemer6fbeee32016-07-07 04:43:07 +00003698QualType ASTContext::getCanonicalTemplateSpecializationType(
3699 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003700 assert(!Template.getAsDependentTemplateName() &&
3701 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003702
Douglas Gregore29139c2011-03-03 17:04:51 +00003703 // Look through qualified template names.
3704 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3705 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003706
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003707 // Build the canonical template specialization type.
3708 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003709 SmallVector<TemplateArgument, 4> CanonArgs;
David Majnemer6fbeee32016-07-07 04:43:07 +00003710 unsigned NumArgs = Args.size();
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003711 CanonArgs.reserve(NumArgs);
David Majnemer6fbeee32016-07-07 04:43:07 +00003712 for (const TemplateArgument &Arg : Args)
3713 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003714
3715 // Determine whether this canonical template specialization type already
3716 // exists.
3717 llvm::FoldingSetNodeID ID;
3718 TemplateSpecializationType::Profile(ID, CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00003719 CanonArgs, *this);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003720
Craig Topper36250ad2014-05-12 05:36:57 +00003721 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003722 TemplateSpecializationType *Spec
3723 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3724
3725 if (!Spec) {
3726 // Allocate a new canonical template specialization type.
3727 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3728 sizeof(TemplateArgument) * NumArgs),
3729 TypeAlignment);
3730 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00003731 CanonArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003732 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003733 Types.push_back(Spec);
3734 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3735 }
3736
3737 assert(Spec->isDependentType() &&
3738 "Non-dependent template-id type must have a canonical type");
3739 return QualType(Spec, 0);
3740}
3741
3742QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003743ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3744 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003745 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003746 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003747 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003748
Craig Topper36250ad2014-05-12 05:36:57 +00003749 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003750 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003751 if (T)
3752 return QualType(T, 0);
3753
Douglas Gregorc42075a2010-02-04 18:10:26 +00003754 QualType Canon = NamedType;
3755 if (!Canon.isCanonical()) {
3756 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003757 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3758 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003759 (void)CheckT;
3760 }
3761
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003762 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003763 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003764 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003765 return QualType(T, 0);
3766}
3767
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003768QualType
Jay Foad39c79802011-01-12 09:06:06 +00003769ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003770 llvm::FoldingSetNodeID ID;
3771 ParenType::Profile(ID, InnerType);
3772
Craig Topper36250ad2014-05-12 05:36:57 +00003773 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003774 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3775 if (T)
3776 return QualType(T, 0);
3777
3778 QualType Canon = InnerType;
3779 if (!Canon.isCanonical()) {
3780 Canon = getCanonicalType(InnerType);
3781 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3782 assert(!CheckT && "Paren canonical type broken");
3783 (void)CheckT;
3784 }
3785
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003786 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003787 Types.push_back(T);
3788 ParenTypes.InsertNode(T, InsertPos);
3789 return QualType(T, 0);
3790}
3791
Douglas Gregor02085352010-03-31 20:19:30 +00003792QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3793 NestedNameSpecifier *NNS,
3794 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003795 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003796 if (Canon.isNull()) {
3797 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Richard Smith74f02342017-01-19 21:00:13 +00003798 if (CanonNNS != NNS)
3799 Canon = getDependentNameType(Keyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003800 }
3801
3802 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003803 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003804
Craig Topper36250ad2014-05-12 05:36:57 +00003805 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003806 DependentNameType *T
3807 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003808 if (T)
3809 return QualType(T, 0);
3810
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003811 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003812 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003813 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003814 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003815}
3816
Mike Stump11289f42009-09-09 15:08:12 +00003817QualType
John McCallc392f372010-06-11 00:33:02 +00003818ASTContext::getDependentTemplateSpecializationType(
3819 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003820 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003821 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003822 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003823 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003824 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003825 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3826 ArgCopy.push_back(Args[I].getArgument());
David Majnemer6fbeee32016-07-07 04:43:07 +00003827 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
John McCallc392f372010-06-11 00:33:02 +00003828}
3829
3830QualType
3831ASTContext::getDependentTemplateSpecializationType(
3832 ElaboratedTypeKeyword Keyword,
3833 NestedNameSpecifier *NNS,
3834 const IdentifierInfo *Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00003835 ArrayRef<TemplateArgument> Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003836 assert((!NNS || NNS->isDependent()) &&
3837 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003838
Douglas Gregorc42075a2010-02-04 18:10:26 +00003839 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003840 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003841 Name, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003842
Craig Topper36250ad2014-05-12 05:36:57 +00003843 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003844 DependentTemplateSpecializationType *T
3845 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003846 if (T)
3847 return QualType(T, 0);
3848
John McCallc392f372010-06-11 00:33:02 +00003849 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003850
John McCallc392f372010-06-11 00:33:02 +00003851 ElaboratedTypeKeyword CanonKeyword = Keyword;
3852 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3853
3854 bool AnyNonCanonArgs = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00003855 unsigned NumArgs = Args.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003856 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003857 for (unsigned I = 0; I != NumArgs; ++I) {
3858 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3859 if (!CanonArgs[I].structurallyEquals(Args[I]))
3860 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003861 }
3862
John McCallc392f372010-06-11 00:33:02 +00003863 QualType Canon;
3864 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3865 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003866 Name,
3867 CanonArgs);
John McCallc392f372010-06-11 00:33:02 +00003868
3869 // Find the insert position again.
3870 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3871 }
3872
3873 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3874 sizeof(TemplateArgument) * NumArgs),
3875 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003876 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003877 Name, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003878 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003879 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003880 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003881}
3882
Richard Smith32918772017-02-14 00:25:28 +00003883TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
3884 TemplateArgument Arg;
3885 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3886 QualType ArgType = getTypeDeclType(TTP);
3887 if (TTP->isParameterPack())
3888 ArgType = getPackExpansionType(ArgType, None);
3889
3890 Arg = TemplateArgument(ArgType);
3891 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3892 Expr *E = new (*this) DeclRefExpr(
3893 NTTP, /*enclosing*/false,
3894 NTTP->getType().getNonLValueExprType(*this),
3895 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
3896
3897 if (NTTP->isParameterPack())
3898 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
3899 None);
3900 Arg = TemplateArgument(E);
3901 } else {
3902 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
3903 if (TTP->isParameterPack())
3904 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
3905 else
3906 Arg = TemplateArgument(TemplateName(TTP));
3907 }
3908
3909 if (Param->isTemplateParameterPack())
3910 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
3911
3912 return Arg;
3913}
3914
Richard Smith43e14d22016-12-23 02:10:11 +00003915void
3916ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
3917 SmallVectorImpl<TemplateArgument> &Args) {
3918 Args.reserve(Args.size() + Params->size());
3919
Richard Smith32918772017-02-14 00:25:28 +00003920 for (NamedDecl *Param : *Params)
3921 Args.push_back(getInjectedTemplateArg(Param));
Richard Smith43e14d22016-12-23 02:10:11 +00003922}
3923
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003924QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003925 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003926 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003927 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003928
3929 assert(Pattern->containsUnexpandedParameterPack() &&
3930 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003931 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003932 PackExpansionType *T
3933 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3934 if (T)
3935 return QualType(T, 0);
3936
3937 QualType Canon;
3938 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003939 Canon = getCanonicalType(Pattern);
3940 // The canonical type might not contain an unexpanded parameter pack, if it
3941 // contains an alias template specialization which ignores one of its
3942 // parameters.
3943 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003944 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003945
Richard Smith68eea502012-07-16 00:20:35 +00003946 // Find the insert position again, in case we inserted an element into
3947 // PackExpansionTypes and invalidated our insert position.
3948 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3949 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003950 }
3951
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003952 T = new (*this, TypeAlignment)
3953 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003954 Types.push_back(T);
3955 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003956 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003957}
3958
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003959/// CmpProtocolNames - Comparison predicate for sorting protocols
3960/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003961static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3962 ObjCProtocolDecl *const *RHS) {
3963 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003964}
3965
Craig Topper1f26d5b2016-01-03 19:43:23 +00003966static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
3967 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00003968
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003969 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3970 return false;
3971
Craig Topper1f26d5b2016-01-03 19:43:23 +00003972 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003973 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003974 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003975 return false;
3976 return true;
3977}
3978
Craig Topper6a8c1512015-10-22 01:56:18 +00003979static void
3980SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003981 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00003982 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003983
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003984 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00003985 for (ObjCProtocolDecl *&P : Protocols)
3986 P = P->getCanonicalDecl();
3987
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003988 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00003989 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
3990 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003991}
3992
John McCall8b07ec22010-05-15 11:32:37 +00003993QualType ASTContext::getObjCObjectType(QualType BaseType,
3994 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003995 unsigned NumProtocols) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003996 return getObjCObjectType(BaseType, { },
Douglas Gregorab209d82015-07-07 03:58:42 +00003997 llvm::makeArrayRef(Protocols, NumProtocols),
3998 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003999}
4000
4001QualType ASTContext::getObjCObjectType(
4002 QualType baseType,
4003 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004004 ArrayRef<ObjCProtocolDecl *> protocols,
4005 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004006 // If the base type is an interface and there aren't any protocols or
4007 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00004008 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4009 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00004010 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00004011
4012 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00004013 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00004014 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00004015 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004016 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4017 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004018
Douglas Gregore9d95f12015-07-07 03:57:35 +00004019 // Determine the type arguments to be used for canonicalization,
4020 // which may be explicitly specified here or written on the base
4021 // type.
4022 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4023 if (effectiveTypeArgs.empty()) {
4024 if (auto baseObject = baseType->getAs<ObjCObjectType>())
4025 effectiveTypeArgs = baseObject->getTypeArgs();
4026 }
John McCallfc93cf92009-10-22 22:37:11 +00004027
Douglas Gregore9d95f12015-07-07 03:57:35 +00004028 // Build the canonical type, which has the canonical base type and a
4029 // sorted-and-uniqued list of protocols and the type arguments
4030 // canonicalized.
4031 QualType canonical;
4032 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4033 effectiveTypeArgs.end(),
4034 [&](QualType type) {
4035 return type.isCanonical();
4036 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00004037 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004038 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4039 // Determine the canonical type arguments.
4040 ArrayRef<QualType> canonTypeArgs;
4041 SmallVector<QualType, 4> canonTypeArgsVec;
4042 if (!typeArgsAreCanonical) {
4043 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4044 for (auto typeArg : effectiveTypeArgs)
4045 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4046 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00004047 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004048 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00004049 }
4050
Douglas Gregore9d95f12015-07-07 03:57:35 +00004051 ArrayRef<ObjCProtocolDecl *> canonProtocols;
4052 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4053 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00004054 canonProtocolsVec.append(protocols.begin(), protocols.end());
4055 SortAndUniqueProtocols(canonProtocolsVec);
4056 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00004057 } else {
4058 canonProtocols = protocols;
4059 }
4060
4061 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004062 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004063
John McCallfc93cf92009-10-22 22:37:11 +00004064 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00004065 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4066 }
4067
Douglas Gregore9d95f12015-07-07 03:57:35 +00004068 unsigned size = sizeof(ObjCObjectTypeImpl);
4069 size += typeArgs.size() * sizeof(QualType);
4070 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4071 void *mem = Allocate(size, TypeAlignment);
John McCall8b07ec22010-05-15 11:32:37 +00004072 ObjCObjectTypeImpl *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00004073 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4074 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00004075
4076 Types.push_back(T);
4077 ObjCObjectTypes.InsertNode(T, InsertPos);
4078 return QualType(T, 0);
4079}
4080
Manman Ren3569eb52016-09-13 17:03:12 +00004081/// Apply Objective-C protocol qualifiers to the given type.
4082/// If this is for the canonical type of a type parameter, we can apply
4083/// protocol qualifiers on the ObjCObjectPointerType.
4084QualType
4085ASTContext::applyObjCProtocolQualifiers(QualType type,
4086 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4087 bool allowOnPointerType) const {
4088 hasError = false;
4089
Manman Renc5705ba2016-09-13 17:41:05 +00004090 if (const ObjCTypeParamType *objT =
4091 dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
4092 return getObjCTypeParamType(objT->getDecl(), protocols);
4093 }
4094
Manman Ren3569eb52016-09-13 17:03:12 +00004095 // Apply protocol qualifiers to ObjCObjectPointerType.
4096 if (allowOnPointerType) {
4097 if (const ObjCObjectPointerType *objPtr =
4098 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
4099 const ObjCObjectType *objT = objPtr->getObjectType();
4100 // Merge protocol lists and construct ObjCObjectType.
4101 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4102 protocolsVec.append(objT->qual_begin(),
4103 objT->qual_end());
4104 protocolsVec.append(protocols.begin(), protocols.end());
4105 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4106 type = getObjCObjectType(
4107 objT->getBaseType(),
4108 objT->getTypeArgsAsWritten(),
4109 protocols,
4110 objT->isKindOfTypeAsWritten());
4111 return getObjCObjectPointerType(type);
4112 }
4113 }
4114
4115 // Apply protocol qualifiers to ObjCObjectType.
4116 if (const ObjCObjectType *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
4117 // FIXME: Check for protocols to which the class type is already
4118 // known to conform.
4119
4120 return getObjCObjectType(objT->getBaseType(),
4121 objT->getTypeArgsAsWritten(),
4122 protocols,
4123 objT->isKindOfTypeAsWritten());
4124 }
4125
4126 // If the canonical type is ObjCObjectType, ...
4127 if (type->isObjCObjectType()) {
4128 // Silently overwrite any existing protocol qualifiers.
4129 // TODO: determine whether that's the right thing to do.
4130
4131 // FIXME: Check for protocols to which the class type is already
4132 // known to conform.
4133 return getObjCObjectType(type, { }, protocols, false);
4134 }
4135
4136 // id<protocol-list>
4137 if (type->isObjCIdType()) {
4138 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
4139 type = getObjCObjectType(ObjCBuiltinIdTy, { }, protocols,
4140 objPtr->isKindOfType());
4141 return getObjCObjectPointerType(type);
4142 }
4143
4144 // Class<protocol-list>
4145 if (type->isObjCClassType()) {
4146 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
4147 type = getObjCObjectType(ObjCBuiltinClassTy, { }, protocols,
4148 objPtr->isKindOfType());
4149 return getObjCObjectPointerType(type);
4150 }
4151
4152 hasError = true;
4153 return type;
4154}
4155
Manman Rene6be26c2016-09-13 17:25:08 +00004156QualType
4157ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
4158 ArrayRef<ObjCProtocolDecl *> protocols,
4159 QualType Canonical) const {
4160 // Look in the folding set for an existing type.
4161 llvm::FoldingSetNodeID ID;
4162 ObjCTypeParamType::Profile(ID, Decl, protocols);
4163 void *InsertPos = nullptr;
4164 if (ObjCTypeParamType *TypeParam =
4165 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4166 return QualType(TypeParam, 0);
4167
4168 if (Canonical.isNull()) {
4169 // We canonicalize to the underlying type.
4170 Canonical = getCanonicalType(Decl->getUnderlyingType());
4171 if (!protocols.empty()) {
4172 // Apply the protocol qualifers.
4173 bool hasError;
4174 Canonical = applyObjCProtocolQualifiers(Canonical, protocols, hasError,
4175 true/*allowOnPointerType*/);
4176 assert(!hasError && "Error when apply protocol qualifier to bound type");
4177 }
4178 }
4179
4180 unsigned size = sizeof(ObjCTypeParamType);
4181 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4182 void *mem = Allocate(size, TypeAlignment);
4183 ObjCTypeParamType *newType = new (mem)
4184 ObjCTypeParamType(Decl, Canonical, protocols);
4185
4186 Types.push_back(newType);
4187 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4188 return QualType(newType, 0);
4189}
4190
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004191/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4192/// protocol list adopt all protocols in QT's qualified-id protocol
4193/// list.
4194bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4195 ObjCInterfaceDecl *IC) {
4196 if (!QT->isObjCQualifiedIdType())
4197 return false;
4198
4199 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
4200 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00004201 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004202 if (!IC->ClassImplementsProtocol(Proto, false))
4203 return false;
4204 }
4205 return true;
4206 }
4207 return false;
4208}
4209
4210/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4211/// QT's qualified-id protocol list adopt all protocols in IDecl's list
4212/// of protocols.
4213bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4214 ObjCInterfaceDecl *IDecl) {
4215 if (!QT->isObjCQualifiedIdType())
4216 return false;
4217 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
4218 if (!OPT)
4219 return false;
4220 if (!IDecl->hasDefinition())
4221 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004222 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4223 CollectInheritedProtocols(IDecl, InheritedProtocols);
4224 if (InheritedProtocols.empty())
4225 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004226 // Check that if every protocol in list of id<plist> conforms to a protcol
4227 // of IDecl's, then bridge casting is ok.
4228 bool Conforms = false;
4229 for (auto *Proto : OPT->quals()) {
4230 Conforms = false;
4231 for (auto *PI : InheritedProtocols) {
4232 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4233 Conforms = true;
4234 break;
4235 }
4236 }
4237 if (!Conforms)
4238 break;
4239 }
4240 if (Conforms)
4241 return true;
4242
Aaron Ballman83731462014-03-17 16:14:00 +00004243 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004244 // If both the right and left sides have qualifiers.
4245 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00004246 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004247 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00004248 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004249 break;
4250 }
4251 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004252 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004253 }
4254 return true;
4255}
4256
John McCall8b07ec22010-05-15 11:32:37 +00004257/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4258/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00004259QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00004260 llvm::FoldingSetNodeID ID;
4261 ObjCObjectPointerType::Profile(ID, ObjectT);
4262
Craig Topper36250ad2014-05-12 05:36:57 +00004263 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004264 if (ObjCObjectPointerType *QT =
4265 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4266 return QualType(QT, 0);
4267
4268 // Find the canonical object type.
4269 QualType Canonical;
4270 if (!ObjectT.isCanonical()) {
4271 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4272
4273 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00004274 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4275 }
4276
Douglas Gregorf85bee62010-02-08 22:59:26 +00004277 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00004278 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
4279 ObjCObjectPointerType *QType =
4280 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00004281
Steve Narofffb4330f2009-06-17 22:40:22 +00004282 Types.push_back(QType);
4283 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00004284 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004285}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004286
Douglas Gregor1c283312010-08-11 12:19:30 +00004287/// getObjCInterfaceType - Return the unique reference to the type for the
4288/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004289QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4290 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00004291 if (Decl->TypeForDecl)
4292 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004293
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004294 if (PrevDecl) {
4295 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4296 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4297 return QualType(PrevDecl->TypeForDecl, 0);
4298 }
4299
Douglas Gregor7671e532011-12-16 16:34:57 +00004300 // Prefer the definition, if there is one.
4301 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4302 Decl = Def;
4303
Douglas Gregor1c283312010-08-11 12:19:30 +00004304 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
4305 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
4306 Decl->TypeForDecl = T;
4307 Types.push_back(T);
4308 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00004309}
4310
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004311/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4312/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00004313/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00004314/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00004315/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004316QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004317 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004318 if (tofExpr->isTypeDependent()) {
4319 llvm::FoldingSetNodeID ID;
4320 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004321
Craig Topper36250ad2014-05-12 05:36:57 +00004322 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004323 DependentTypeOfExprType *Canon
4324 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4325 if (Canon) {
4326 // We already have a "canonical" version of an identical, dependent
4327 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00004328 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004329 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00004330 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004331 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004332 Canon
4333 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004334 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4335 toe = Canon;
4336 }
4337 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00004338 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00004339 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00004340 }
Steve Naroffa773cd52007-08-01 18:02:17 +00004341 Types.push_back(toe);
4342 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004343}
4344
Steve Naroffa773cd52007-08-01 18:02:17 +00004345/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00004346/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00004347/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00004348/// an issue. This doesn't affect the type checker, since it operates
4349/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004350QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00004351 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00004352 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00004353 Types.push_back(tot);
4354 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004355}
4356
Richard Smith8eb1d322014-06-05 20:13:13 +00004357/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
4358/// nodes. This would never be helpful, since each such type has its own
4359/// expression, and would not give a significant memory saving, since there
4360/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00004361QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004362 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00004363
4364 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00004365 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00004366 // unique dependent type. Two such decltype-specifiers refer to the same
4367 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00004368 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004369 llvm::FoldingSetNodeID ID;
4370 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00004371
Craig Topper36250ad2014-05-12 05:36:57 +00004372 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00004373 DependentDecltypeType *Canon
4374 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00004375 if (!Canon) {
Yaron Keren633e14a2016-11-29 10:08:20 +00004376 // Build a new, canonical decltype(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004377 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004378 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004379 }
Richard Smith8eb1d322014-06-05 20:13:13 +00004380 dt = new (*this, TypeAlignment)
4381 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00004382 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00004383 dt = new (*this, TypeAlignment)
4384 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00004385 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00004386 Types.push_back(dt);
4387 return QualType(dt, 0);
4388}
4389
Alexis Hunte852b102011-05-24 22:41:36 +00004390/// getUnaryTransformationType - We don't unique these, since the memory
4391/// savings are minimal and these are rare.
4392QualType ASTContext::getUnaryTransformType(QualType BaseType,
4393 QualType UnderlyingType,
4394 UnaryTransformType::UTTKind Kind)
4395 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00004396 UnaryTransformType *ut = nullptr;
4397
4398 if (BaseType->isDependentType()) {
4399 // Look in the folding set for an existing type.
4400 llvm::FoldingSetNodeID ID;
4401 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4402
4403 void *InsertPos = nullptr;
4404 DependentUnaryTransformType *Canon
4405 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4406
4407 if (!Canon) {
4408 // Build a new, canonical __underlying_type(type) type.
4409 Canon = new (*this, TypeAlignment)
4410 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4411 Kind);
4412 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4413 }
4414 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4415 QualType(), Kind,
4416 QualType(Canon, 0));
4417 } else {
4418 QualType CanonType = getCanonicalType(UnderlyingType);
4419 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4420 UnderlyingType, Kind,
4421 CanonType);
4422 }
4423 Types.push_back(ut);
4424 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00004425}
4426
Richard Smith2a7d4812013-05-04 07:00:32 +00004427/// getAutoType - Return the uniqued reference to the 'auto' type which has been
4428/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4429/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00004430QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004431 bool IsDependent) const {
Richard Smithe301ba22015-11-11 02:02:15 +00004432 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00004433 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004434
Richard Smith2a7d4812013-05-04 07:00:32 +00004435 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00004436 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00004437 llvm::FoldingSetNodeID ID;
Richard Smithe301ba22015-11-11 02:02:15 +00004438 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00004439 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4440 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004441
Richard Smith74aeef52013-04-26 16:15:35 +00004442 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithe301ba22015-11-11 02:02:15 +00004443 Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004444 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004445 Types.push_back(AT);
4446 if (InsertPos)
4447 AutoTypes.InsertNode(AT, InsertPos);
4448 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004449}
4450
Richard Smith600b5262017-01-26 20:40:47 +00004451/// Return the uniqued reference to the deduced template specialization type
4452/// which has been deduced to the given type, or to the canonical undeduced
4453/// such type, or the canonical deduced-but-dependent such type.
4454QualType ASTContext::getDeducedTemplateSpecializationType(
4455 TemplateName Template, QualType DeducedType, bool IsDependent) const {
4456 // Look in the folding set for an existing type.
4457 void *InsertPos = nullptr;
4458 llvm::FoldingSetNodeID ID;
4459 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
4460 IsDependent);
4461 if (DeducedTemplateSpecializationType *DTST =
4462 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
4463 return QualType(DTST, 0);
4464
4465 DeducedTemplateSpecializationType *DTST = new (*this, TypeAlignment)
4466 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
4467 Types.push_back(DTST);
4468 if (InsertPos)
4469 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
4470 return QualType(DTST, 0);
4471}
4472
Eli Friedman0dfb8892011-10-06 23:00:33 +00004473/// getAtomicType - Return the uniqued reference to the atomic type for
4474/// the given value type.
4475QualType ASTContext::getAtomicType(QualType T) const {
4476 // Unique pointers, to guarantee there is only one pointer of a particular
4477 // structure.
4478 llvm::FoldingSetNodeID ID;
4479 AtomicType::Profile(ID, T);
4480
Craig Topper36250ad2014-05-12 05:36:57 +00004481 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004482 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4483 return QualType(AT, 0);
4484
4485 // If the atomic value type isn't canonical, this won't be a canonical type
4486 // either, so fill in the canonical type field.
4487 QualType Canonical;
4488 if (!T.isCanonical()) {
4489 Canonical = getAtomicType(getCanonicalType(T));
4490
4491 // Get the new insert position for the node we care about.
4492 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004493 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004494 }
4495 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4496 Types.push_back(New);
4497 AtomicTypes.InsertNode(New, InsertPos);
4498 return QualType(New, 0);
4499}
4500
Richard Smith02e85f32011-04-14 22:09:26 +00004501/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4502QualType ASTContext::getAutoDeductType() const {
4503 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004504 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00004505 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004506 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004507 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004508 return AutoDeductTy;
4509}
4510
4511/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4512QualType ASTContext::getAutoRRefDeductType() const {
4513 if (AutoRRefDeductTy.isNull())
4514 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4515 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4516 return AutoRRefDeductTy;
4517}
4518
Chris Lattnerfb072462007-01-23 05:45:31 +00004519/// getTagDeclType - Return the unique reference to the type for the
4520/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004521QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00004522 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004523 // FIXME: What is the design on getTagDeclType when it requires casting
4524 // away const? mutable?
4525 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004526}
4527
Mike Stump11289f42009-09-09 15:08:12 +00004528/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4529/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4530/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004531CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004532 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004533}
Chris Lattnerfb072462007-01-23 05:45:31 +00004534
Alexander Shaposhnikov1e898d92017-07-14 17:30:14 +00004535/// Return the unique signed counterpart of the integer type
4536/// corresponding to size_t.
4537CanQualType ASTContext::getSignedSizeType() const {
4538 return getFromTargetType(Target->getSignedSizeType());
4539}
4540
Hans Wennborg27541db2011-10-27 08:29:09 +00004541/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4542CanQualType ASTContext::getIntMaxType() const {
4543 return getFromTargetType(Target->getIntMaxType());
4544}
4545
4546/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4547CanQualType ASTContext::getUIntMaxType() const {
4548 return getFromTargetType(Target->getUIntMaxType());
4549}
4550
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004551/// getSignedWCharType - Return the type of "signed wchar_t".
4552/// Used when in C++, as a GCC extension.
4553QualType ASTContext::getSignedWCharType() const {
4554 // FIXME: derive from "Target" ?
4555 return WCharTy;
4556}
4557
4558/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4559/// Used when in C++, as a GCC extension.
4560QualType ASTContext::getUnsignedWCharType() const {
4561 // FIXME: derive from "Target" ?
4562 return UnsignedIntTy;
4563}
4564
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004565QualType ASTContext::getIntPtrType() const {
4566 return getFromTargetType(Target->getIntPtrType());
4567}
4568
4569QualType ASTContext::getUIntPtrType() const {
4570 return getCorrespondingUnsignedType(getIntPtrType());
4571}
4572
Hans Wennborg27541db2011-10-27 08:29:09 +00004573/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004574/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4575QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004576 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004577}
4578
Eli Friedman4e91899e2012-11-27 02:58:24 +00004579/// \brief Return the unique type for "pid_t" defined in
4580/// <sys/types.h>. We need this to compute the correct type for vfork().
4581QualType ASTContext::getProcessIDType() const {
4582 return getFromTargetType(Target->getProcessIDType());
4583}
4584
Chris Lattnera21ad802008-04-02 05:18:44 +00004585//===----------------------------------------------------------------------===//
4586// Type Operators
4587//===----------------------------------------------------------------------===//
4588
Jay Foad39c79802011-01-12 09:06:06 +00004589CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004590 // Push qualifiers into arrays, and then discard any remaining
4591 // qualifiers.
4592 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004593 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004594 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004595 QualType Result;
4596 if (isa<ArrayType>(Ty)) {
4597 Result = getArrayDecayedType(QualType(Ty,0));
4598 } else if (isa<FunctionType>(Ty)) {
4599 Result = getPointerType(QualType(Ty, 0));
4600 } else {
4601 Result = QualType(Ty, 0);
4602 }
4603
4604 return CanQualType::CreateUnsafe(Result);
4605}
4606
John McCall6c9dd522011-01-18 07:41:22 +00004607QualType ASTContext::getUnqualifiedArrayType(QualType type,
4608 Qualifiers &quals) {
4609 SplitQualType splitType = type.getSplitUnqualifiedType();
4610
4611 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4612 // the unqualified desugared type and then drops it on the floor.
4613 // We then have to strip that sugar back off with
4614 // getUnqualifiedDesugaredType(), which is silly.
4615 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00004616 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004617
4618 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004619 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00004620 quals = splitType.Quals;
4621 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004622 }
4623
John McCall6c9dd522011-01-18 07:41:22 +00004624 // Otherwise, recurse on the array's element type.
4625 QualType elementType = AT->getElementType();
4626 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4627
4628 // If that didn't change the element type, AT has no qualifiers, so we
4629 // can just use the results in splitType.
4630 if (elementType == unqualElementType) {
4631 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004632 quals = splitType.Quals;
4633 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004634 }
4635
4636 // Otherwise, add in the qualifiers from the outermost type, then
4637 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004638 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004639
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004640 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004641 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004642 CAT->getSizeModifier(), 0);
4643 }
4644
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004645 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004646 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004647 }
4648
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004649 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004650 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004651 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004652 VAT->getSizeModifier(),
4653 VAT->getIndexTypeCVRQualifiers(),
4654 VAT->getBracketsRange());
4655 }
4656
4657 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004658 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004659 DSAT->getSizeModifier(), 0,
4660 SourceRange());
4661}
4662
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004663/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4664/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4665/// they point to and return true. If T1 and T2 aren't pointer types
4666/// or pointer-to-member types, or if they are not similar at this
4667/// level, returns false and leaves T1 and T2 unchanged. Top-level
4668/// qualifiers on T1 and T2 are ignored. This function will typically
4669/// be called in a loop that successively "unwraps" pointer and
4670/// pointer-to-member types to compare them at each level.
4671bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4672 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4673 *T2PtrType = T2->getAs<PointerType>();
4674 if (T1PtrType && T2PtrType) {
4675 T1 = T1PtrType->getPointeeType();
4676 T2 = T2PtrType->getPointeeType();
4677 return true;
4678 }
4679
4680 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4681 *T2MPType = T2->getAs<MemberPointerType>();
4682 if (T1MPType && T2MPType &&
4683 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4684 QualType(T2MPType->getClass(), 0))) {
4685 T1 = T1MPType->getPointeeType();
4686 T2 = T2MPType->getPointeeType();
4687 return true;
4688 }
4689
David Blaikiebbafb8a2012-03-11 07:00:24 +00004690 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004691 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4692 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4693 if (T1OPType && T2OPType) {
4694 T1 = T1OPType->getPointeeType();
4695 T2 = T2OPType->getPointeeType();
4696 return true;
4697 }
4698 }
4699
4700 // FIXME: Block pointers, too?
4701
4702 return false;
4703}
4704
Jay Foad39c79802011-01-12 09:06:06 +00004705DeclarationNameInfo
4706ASTContext::getNameForTemplate(TemplateName Name,
4707 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004708 switch (Name.getKind()) {
4709 case TemplateName::QualifiedTemplate:
4710 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004711 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004712 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4713 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004714
John McCalld9dfe3a2011-06-30 08:33:18 +00004715 case TemplateName::OverloadedTemplate: {
4716 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4717 // DNInfo work in progress: CHECKME: what about DNLoc?
4718 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4719 }
4720
4721 case TemplateName::DependentTemplate: {
4722 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004723 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004724 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004725 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4726 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004727 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004728 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4729 // DNInfo work in progress: FIXME: source locations?
4730 DeclarationNameLoc DNLoc;
4731 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4732 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4733 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004734 }
4735 }
4736
John McCalld9dfe3a2011-06-30 08:33:18 +00004737 case TemplateName::SubstTemplateTemplateParm: {
4738 SubstTemplateTemplateParmStorage *subst
4739 = Name.getAsSubstTemplateTemplateParm();
4740 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4741 NameLoc);
4742 }
4743
4744 case TemplateName::SubstTemplateTemplateParmPack: {
4745 SubstTemplateTemplateParmPackStorage *subst
4746 = Name.getAsSubstTemplateTemplateParmPack();
4747 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4748 NameLoc);
4749 }
4750 }
4751
4752 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004753}
4754
Jay Foad39c79802011-01-12 09:06:06 +00004755TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004756 switch (Name.getKind()) {
4757 case TemplateName::QualifiedTemplate:
4758 case TemplateName::Template: {
4759 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004760 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004761 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004762 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4763
4764 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004765 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004766 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004767
John McCalld9dfe3a2011-06-30 08:33:18 +00004768 case TemplateName::OverloadedTemplate:
4769 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004770
John McCalld9dfe3a2011-06-30 08:33:18 +00004771 case TemplateName::DependentTemplate: {
4772 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4773 assert(DTN && "Non-dependent template names must refer to template decls.");
4774 return DTN->CanonicalTemplateName;
4775 }
4776
4777 case TemplateName::SubstTemplateTemplateParm: {
4778 SubstTemplateTemplateParmStorage *subst
4779 = Name.getAsSubstTemplateTemplateParm();
4780 return getCanonicalTemplateName(subst->getReplacement());
4781 }
4782
4783 case TemplateName::SubstTemplateTemplateParmPack: {
4784 SubstTemplateTemplateParmPackStorage *subst
4785 = Name.getAsSubstTemplateTemplateParmPack();
4786 TemplateTemplateParmDecl *canonParameter
4787 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4788 TemplateArgument canonArgPack
4789 = getCanonicalTemplateArgument(subst->getArgumentPack());
4790 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4791 }
4792 }
4793
4794 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004795}
4796
Douglas Gregoradee3e32009-11-11 23:06:43 +00004797bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4798 X = getCanonicalTemplateName(X);
4799 Y = getCanonicalTemplateName(Y);
4800 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4801}
4802
Mike Stump11289f42009-09-09 15:08:12 +00004803TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004804ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004805 switch (Arg.getKind()) {
4806 case TemplateArgument::Null:
4807 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004808
Douglas Gregora8e02e72009-07-28 23:00:59 +00004809 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004810 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004811
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004812 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004813 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004814 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004815 }
Mike Stump11289f42009-09-09 15:08:12 +00004816
Eli Friedmanb826a002012-09-26 02:36:12 +00004817 case TemplateArgument::NullPtr:
4818 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4819 /*isNullPtr*/true);
4820
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004821 case TemplateArgument::Template:
4822 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004823
4824 case TemplateArgument::TemplateExpansion:
4825 return TemplateArgument(getCanonicalTemplateName(
4826 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004827 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004828
Douglas Gregora8e02e72009-07-28 23:00:59 +00004829 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004830 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004831
Douglas Gregora8e02e72009-07-28 23:00:59 +00004832 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004833 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004834
Douglas Gregora8e02e72009-07-28 23:00:59 +00004835 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004836 if (Arg.pack_size() == 0)
4837 return Arg;
4838
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004839 TemplateArgument *CanonArgs
4840 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004841 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004842 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004843 AEnd = Arg.pack_end();
4844 A != AEnd; (void)++A, ++Idx)
4845 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004846
Benjamin Kramercce63472015-08-05 09:40:22 +00004847 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00004848 }
4849 }
4850
4851 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004852 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004853}
4854
Douglas Gregor333489b2009-03-27 23:10:48 +00004855NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004856ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004857 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004858 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004859
4860 switch (NNS->getKind()) {
4861 case NestedNameSpecifier::Identifier:
4862 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004863 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004864 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4865 NNS->getAsIdentifier());
4866
4867 case NestedNameSpecifier::Namespace:
4868 // A namespace is canonical; build a nested-name-specifier with
4869 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004870 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004871 NNS->getAsNamespace()->getOriginalNamespace());
4872
4873 case NestedNameSpecifier::NamespaceAlias:
4874 // A namespace is canonical; build a nested-name-specifier with
4875 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004876 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004877 NNS->getAsNamespaceAlias()->getNamespace()
4878 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004879
4880 case NestedNameSpecifier::TypeSpec:
4881 case NestedNameSpecifier::TypeSpecWithTemplate: {
4882 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004883
4884 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4885 // break it apart into its prefix and identifier, then reconsititute those
4886 // as the canonical nested-name-specifier. This is required to canonicalize
4887 // a dependent nested-name-specifier involving typedefs of dependent-name
4888 // types, e.g.,
4889 // typedef typename T::type T1;
4890 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004891 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4892 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004893 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004894
Eli Friedman5358a0a2012-03-03 04:09:56 +00004895 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4896 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4897 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004898 return NestedNameSpecifier::Create(*this, nullptr, false,
4899 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004900 }
4901
4902 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004903 case NestedNameSpecifier::Super:
4904 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004905 return NNS;
4906 }
4907
David Blaikie8a40f702012-01-17 06:56:22 +00004908 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004909}
4910
Jay Foad39c79802011-01-12 09:06:06 +00004911const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004912 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004913 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004914 // Handle the common positive case fast.
4915 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4916 return AT;
4917 }
Mike Stump11289f42009-09-09 15:08:12 +00004918
John McCall8ccfcb52009-09-24 19:53:00 +00004919 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004920 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004921 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004922
John McCall8ccfcb52009-09-24 19:53:00 +00004923 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004924 // implements C99 6.7.3p8: "If the specification of an array type includes
4925 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004926
Chris Lattner7adf0762008-08-04 07:31:14 +00004927 // If we get here, we either have type qualifiers on the type, or we have
4928 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004929 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004930
John McCall33ddac02011-01-19 10:06:00 +00004931 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004932 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004933
Chris Lattner7adf0762008-08-04 07:31:14 +00004934 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004935 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004936 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004937 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004938
Chris Lattner7adf0762008-08-04 07:31:14 +00004939 // Otherwise, we have an array and we have qualifiers on it. Push the
4940 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004941 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004942
Chris Lattner7adf0762008-08-04 07:31:14 +00004943 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4944 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4945 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004946 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004947 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4948 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4949 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004950 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004951
Mike Stump11289f42009-09-09 15:08:12 +00004952 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004953 = dyn_cast<DependentSizedArrayType>(ATy))
4954 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004955 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004956 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004957 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004958 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004959 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004960
Chris Lattner7adf0762008-08-04 07:31:14 +00004961 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004962 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004963 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004964 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004965 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004966 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004967}
4968
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004969QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004970 if (T->isArrayType() || T->isFunctionType())
4971 return getDecayedType(T);
4972 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004973}
4974
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004975QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004976 T = getVariableArrayDecayedType(T);
4977 T = getAdjustedParameterType(T);
4978 return T.getUnqualifiedType();
4979}
4980
David Majnemerd09a51c2015-03-03 01:50:05 +00004981QualType ASTContext::getExceptionObjectType(QualType T) const {
4982 // C++ [except.throw]p3:
4983 // A throw-expression initializes a temporary object, called the exception
4984 // object, the type of which is determined by removing any top-level
4985 // cv-qualifiers from the static type of the operand of throw and adjusting
4986 // the type from "array of T" or "function returning T" to "pointer to T"
4987 // or "pointer to function returning T", [...]
4988 T = getVariableArrayDecayedType(T);
4989 if (T->isArrayType() || T->isFunctionType())
4990 T = getDecayedType(T);
4991 return T.getUnqualifiedType();
4992}
4993
Chris Lattnera21ad802008-04-02 05:18:44 +00004994/// getArrayDecayedType - Return the properly qualified result of decaying the
4995/// specified array type to a pointer. This operation is non-trivial when
4996/// handling typedefs etc. The canonical type of "T" must be an array type,
4997/// this returns a pointer to a properly qualified element of the array.
4998///
4999/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00005000QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005001 // Get the element type with 'getAsArrayType' so that we don't lose any
5002 // typedefs in the element type of the array. This also handles propagation
5003 // of type qualifiers from the array type into the element type if present
5004 // (C99 6.7.3p8).
5005 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
5006 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00005007
Chris Lattner7adf0762008-08-04 07:31:14 +00005008 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00005009
5010 // int x[restrict 4] -> int *restrict
Jordan Rose303e2f12016-11-10 23:28:17 +00005011 QualType Result = getQualifiedType(PtrTy,
5012 PrettyArrayType->getIndexTypeQualifiers());
5013
5014 // int x[_Nullable] -> int * _Nullable
5015 if (auto Nullability = Ty->getNullability(*this)) {
5016 Result = const_cast<ASTContext *>(this)->getAttributedType(
5017 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
5018 }
5019 return Result;
Chris Lattnera21ad802008-04-02 05:18:44 +00005020}
5021
John McCall33ddac02011-01-19 10:06:00 +00005022QualType ASTContext::getBaseElementType(const ArrayType *array) const {
5023 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00005024}
5025
John McCall33ddac02011-01-19 10:06:00 +00005026QualType ASTContext::getBaseElementType(QualType type) const {
5027 Qualifiers qs;
5028 while (true) {
5029 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005030 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00005031 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00005032
John McCall33ddac02011-01-19 10:06:00 +00005033 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00005034 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00005035 }
Mike Stump11289f42009-09-09 15:08:12 +00005036
John McCall33ddac02011-01-19 10:06:00 +00005037 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00005038}
5039
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005040/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00005041uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005042ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
5043 uint64_t ElementCount = 1;
5044 do {
5045 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00005046 CA = dyn_cast_or_null<ConstantArrayType>(
5047 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005048 } while (CA);
5049 return ElementCount;
5050}
5051
Steve Naroff0af91202007-04-27 21:51:21 +00005052/// getFloatingRank - Return a relative rank for floating point types.
5053/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00005054static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00005055 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00005056 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00005057
John McCall9dd450b2009-09-21 23:43:11 +00005058 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
5059 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005060 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00005061 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00005062 case BuiltinType::Float: return FloatRank;
5063 case BuiltinType::Double: return DoubleRank;
5064 case BuiltinType::LongDouble: return LongDoubleRank;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005065 case BuiltinType::Float128: return Float128Rank;
Steve Naroffe4718892007-04-27 18:30:00 +00005066 }
5067}
5068
Mike Stump11289f42009-09-09 15:08:12 +00005069/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5070/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00005071/// 'typeDomain' is a real floating point or complex type.
5072/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005073QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
5074 QualType Domain) const {
5075 FloatingRank EltRank = getFloatingRank(Size);
5076 if (Domain->isComplexType()) {
5077 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00005078 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00005079 case FloatRank: return FloatComplexTy;
5080 case DoubleRank: return DoubleComplexTy;
5081 case LongDoubleRank: return LongDoubleComplexTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005082 case Float128Rank: return Float128ComplexTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00005083 }
Steve Naroff0af91202007-04-27 21:51:21 +00005084 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005085
5086 assert(Domain->isRealFloatingType() && "Unknown domain!");
5087 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00005088 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005089 case FloatRank: return FloatTy;
5090 case DoubleRank: return DoubleTy;
5091 case LongDoubleRank: return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005092 case Float128Rank: return Float128Ty;
Steve Naroff9091ef72007-08-27 01:27:54 +00005093 }
David Blaikief47fa302012-01-17 02:30:50 +00005094 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00005095}
5096
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005097/// getFloatingTypeOrder - Compare the rank of the two specified floating
5098/// point types, ignoring the domain of the type (i.e. 'double' ==
5099/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005100/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005101int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00005102 FloatingRank LHSR = getFloatingRank(LHS);
5103 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005104
Chris Lattnerb90739d2008-04-06 23:38:49 +00005105 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005106 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00005107 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005108 return 1;
5109 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00005110}
5111
Chris Lattner76a00cf2008-04-06 22:59:24 +00005112/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5113/// routine will assert if passed a built-in type that isn't an integer or enum,
5114/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00005115unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00005116 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00005117
Chris Lattner76a00cf2008-04-06 22:59:24 +00005118 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005119 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005120 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005121 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005122 case BuiltinType::Char_S:
5123 case BuiltinType::Char_U:
5124 case BuiltinType::SChar:
5125 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005126 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005127 case BuiltinType::Short:
5128 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005129 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005130 case BuiltinType::Int:
5131 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005132 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005133 case BuiltinType::Long:
5134 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005135 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005136 case BuiltinType::LongLong:
5137 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005138 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00005139 case BuiltinType::Int128:
5140 case BuiltinType::UInt128:
5141 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00005142 }
5143}
5144
Eli Friedman629ffb92009-08-20 04:21:42 +00005145/// \brief Whether this is a promotable bitfield reference according
5146/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5147///
5148/// \returns the type this bit-field will promote to, or NULL if no
5149/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00005150QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00005151 if (E->isTypeDependent() || E->isValueDependent())
5152 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00005153
5154 // FIXME: We should not do this unless E->refersToBitField() is true. This
5155 // matters in C where getSourceBitField() will find bit-fields for various
5156 // cases where the source expression is not a bit-field designator.
5157
John McCalld25db7e2013-05-06 21:39:12 +00005158 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00005159 if (!Field)
5160 return QualType();
5161
5162 QualType FT = Field->getType();
5163
Richard Smithcaf33902011-10-10 18:28:20 +00005164 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00005165 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00005166 // C++ [conv.prom]p5:
5167 // A prvalue for an integral bit-field can be converted to a prvalue of type
5168 // int if int can represent all the values of the bit-field; otherwise, it
5169 // can be converted to unsigned int if unsigned int can represent all the
5170 // values of the bit-field. If the bit-field is larger yet, no integral
5171 // promotion applies to it.
5172 // C11 6.3.1.1/2:
5173 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5174 // If an int can represent all values of the original type (as restricted by
5175 // the width, for a bit-field), the value is converted to an int; otherwise,
5176 // it is converted to an unsigned int.
5177 //
5178 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5179 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00005180 if (BitWidth < IntSize)
5181 return IntTy;
5182
5183 if (BitWidth == IntSize)
5184 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5185
5186 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00005187 // like the base type. GCC has some weird bugs in this area that we
5188 // deliberately do not follow (GCC follows a pre-standard resolution to
5189 // C's DR315 which treats bit-width as being part of the type, and this leaks
5190 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00005191 return QualType();
5192}
5193
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005194/// getPromotedIntegerType - Returns the type that Promotable will
5195/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5196/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00005197QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005198 assert(!Promotable.isNull());
5199 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00005200 if (const EnumType *ET = Promotable->getAs<EnumType>())
5201 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005202
5203 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
5204 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5205 // (3.9.1) can be converted to a prvalue of the first of the following
5206 // types that can represent all the values of its underlying type:
5207 // int, unsigned int, long int, unsigned long int, long long int, or
5208 // unsigned long long int [...]
5209 // FIXME: Is there some better way to compute this?
5210 if (BT->getKind() == BuiltinType::WChar_S ||
5211 BT->getKind() == BuiltinType::WChar_U ||
5212 BT->getKind() == BuiltinType::Char16 ||
5213 BT->getKind() == BuiltinType::Char32) {
5214 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5215 uint64_t FromSize = getTypeSize(BT);
5216 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5217 LongLongTy, UnsignedLongLongTy };
5218 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5219 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5220 if (FromSize < ToSize ||
5221 (FromSize == ToSize &&
5222 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5223 return PromoteTypes[Idx];
5224 }
5225 llvm_unreachable("char type should fit into long long");
5226 }
5227 }
5228
5229 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005230 if (Promotable->isSignedIntegerType())
5231 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00005232 uint64_t PromotableSize = getIntWidth(Promotable);
5233 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005234 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
5235 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5236}
5237
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005238/// \brief Recurses in pointer/array types until it finds an objc retainable
5239/// type and returns its ownership.
5240Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
5241 while (!T.isNull()) {
5242 if (T.getObjCLifetime() != Qualifiers::OCL_None)
5243 return T.getObjCLifetime();
5244 if (T->isArrayType())
5245 T = getBaseElementType(T);
5246 else if (const PointerType *PT = T->getAs<PointerType>())
5247 T = PT->getPointeeType();
5248 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00005249 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005250 else
5251 break;
5252 }
5253
5254 return Qualifiers::OCL_None;
5255}
5256
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005257static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5258 // Incomplete enum types are not treated as integer types.
5259 // FIXME: In C++, enum types are never integer types.
5260 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5261 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00005262 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005263}
5264
Mike Stump11289f42009-09-09 15:08:12 +00005265/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005266/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005267/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005268int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00005269 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5270 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005271
5272 // Unwrap enums to their underlying type.
5273 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
5274 LHSC = getIntegerTypeForEnum(ET);
5275 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
5276 RHSC = getIntegerTypeForEnum(ET);
5277
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005278 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005279
Chris Lattner76a00cf2008-04-06 22:59:24 +00005280 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5281 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00005282
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005283 unsigned LHSRank = getIntegerRank(LHSC);
5284 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00005285
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005286 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5287 if (LHSRank == RHSRank) return 0;
5288 return LHSRank > RHSRank ? 1 : -1;
5289 }
Mike Stump11289f42009-09-09 15:08:12 +00005290
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005291 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
5292 if (LHSUnsigned) {
5293 // If the unsigned [LHS] type is larger, return it.
5294 if (LHSRank >= RHSRank)
5295 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00005296
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005297 // If the signed type can represent all values of the unsigned type, it
5298 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005299 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005300 return -1;
5301 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00005302
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005303 // If the unsigned [RHS] type is larger, return it.
5304 if (RHSRank >= LHSRank)
5305 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00005306
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005307 // If the signed type can represent all values of the unsigned type, it
5308 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005309 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005310 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00005311}
Anders Carlsson98f07902007-08-17 05:31:46 +00005312
Ben Langmuirf5416742016-02-04 00:55:24 +00005313TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00005314 if (!CFConstantStringTypeDecl) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005315 assert(!CFConstantStringTagDecl &&
5316 "tag and typedef should be initialized together");
5317 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
5318 CFConstantStringTagDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00005319
Anders Carlsson9c1011c2007-11-19 00:25:30 +00005320 QualType FieldTypes[4];
Ben Langmuir4791a802016-02-25 16:36:26 +00005321 const char *FieldNames[4];
Mike Stump11289f42009-09-09 15:08:12 +00005322
Anders Carlsson98f07902007-08-17 05:31:46 +00005323 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00005324 FieldTypes[0] = getPointerType(IntTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00005325 FieldNames[0] = "isa";
Anders Carlsson9c1011c2007-11-19 00:25:30 +00005326 // int flags;
5327 FieldTypes[1] = IntTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00005328 FieldNames[1] = "flags";
Anders Carlsson98f07902007-08-17 05:31:46 +00005329 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00005330 FieldTypes[2] = getPointerType(CharTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00005331 FieldNames[2] = "str";
Anders Carlsson98f07902007-08-17 05:31:46 +00005332 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00005333 FieldTypes[3] = LongTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00005334 FieldNames[3] = "length";
Mike Stump11289f42009-09-09 15:08:12 +00005335
Anders Carlsson98f07902007-08-17 05:31:46 +00005336 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00005337 for (unsigned i = 0; i < 4; ++i) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005338 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00005339 SourceLocation(),
Ben Langmuir4791a802016-02-25 16:36:26 +00005340 SourceLocation(),
5341 &Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00005342 FieldTypes[i], /*TInfo=*/nullptr,
5343 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00005344 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00005345 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005346 Field->setAccess(AS_public);
Ben Langmuirf5416742016-02-04 00:55:24 +00005347 CFConstantStringTagDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00005348 }
5349
Ben Langmuirf5416742016-02-04 00:55:24 +00005350 CFConstantStringTagDecl->completeDefinition();
5351 // This type is designed to be compatible with NSConstantString, but cannot
5352 // use the same name, since NSConstantString is an interface.
5353 auto tagType = getTagDeclType(CFConstantStringTagDecl);
5354 CFConstantStringTypeDecl =
5355 buildImplicitTypedef(tagType, "__NSConstantString");
Anders Carlsson98f07902007-08-17 05:31:46 +00005356 }
Mike Stump11289f42009-09-09 15:08:12 +00005357
Quentin Colombet043406b2016-02-03 22:41:00 +00005358 return CFConstantStringTypeDecl;
5359}
5360
Ben Langmuirf5416742016-02-04 00:55:24 +00005361RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
5362 if (!CFConstantStringTagDecl)
5363 getCFConstantStringDecl(); // Build the tag and the typedef.
5364 return CFConstantStringTagDecl;
5365}
5366
Quentin Colombet043406b2016-02-03 22:41:00 +00005367// getCFConstantStringType - Return the type used for constant CFStrings.
5368QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00005369 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00005370}
Anders Carlsson87c149b2007-10-11 01:00:40 +00005371
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005372QualType ASTContext::getObjCSuperType() const {
5373 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005374 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005375 TUDecl->addDecl(ObjCSuperTypeDecl);
5376 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
5377 }
5378 return ObjCSuperType;
5379}
5380
Douglas Gregor512b0772009-04-23 22:29:11 +00005381void ASTContext::setCFConstantStringType(QualType T) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005382 const TypedefType *TD = T->getAs<TypedefType>();
5383 assert(TD && "Invalid CFConstantStringType");
5384 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
5385 auto TagType =
5386 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
5387 assert(TagType && "Invalid CFConstantStringType");
5388 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00005389}
5390
Jay Foad39c79802011-01-12 09:06:06 +00005391QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00005392 if (BlockDescriptorType)
5393 return getTagDeclType(BlockDescriptorType);
5394
Alp Toker2dea15b2013-12-17 01:22:38 +00005395 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005396 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005397 RD = buildImplicitRecord("__block_descriptor");
5398 RD->startDefinition();
5399
Mike Stumpd0153282009-10-20 02:12:22 +00005400 QualType FieldTypes[] = {
5401 UnsignedLongTy,
5402 UnsignedLongTy,
5403 };
5404
Craig Topperd6d31ac2013-07-15 08:24:27 +00005405 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00005406 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005407 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00005408 };
5409
5410 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005411 FieldDecl *Field = FieldDecl::Create(
5412 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005413 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5414 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005415 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005416 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00005417 }
5418
Alp Toker2dea15b2013-12-17 01:22:38 +00005419 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00005420
Alp Toker2dea15b2013-12-17 01:22:38 +00005421 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005422
5423 return getTagDeclType(BlockDescriptorType);
5424}
5425
Jay Foad39c79802011-01-12 09:06:06 +00005426QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005427 if (BlockDescriptorExtendedType)
5428 return getTagDeclType(BlockDescriptorExtendedType);
5429
Alp Toker2dea15b2013-12-17 01:22:38 +00005430 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005431 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005432 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
5433 RD->startDefinition();
5434
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005435 QualType FieldTypes[] = {
5436 UnsignedLongTy,
5437 UnsignedLongTy,
5438 getPointerType(VoidPtrTy),
5439 getPointerType(VoidPtrTy)
5440 };
5441
Craig Topperd6d31ac2013-07-15 08:24:27 +00005442 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005443 "reserved",
5444 "Size",
5445 "CopyFuncPtr",
5446 "DestroyFuncPtr"
5447 };
5448
5449 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005450 FieldDecl *Field = FieldDecl::Create(
5451 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005452 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5453 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00005454 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005455 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005456 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005457 }
5458
Alp Toker2dea15b2013-12-17 01:22:38 +00005459 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005460
Alp Toker2dea15b2013-12-17 01:22:38 +00005461 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005462 return getTagDeclType(BlockDescriptorExtendedType);
5463}
5464
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005465/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
5466/// requires copy/dispose. Note that this must match the logic
5467/// in buildByrefHelpers.
5468bool ASTContext::BlockRequiresCopying(QualType Ty,
5469 const VarDecl *D) {
5470 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
5471 const Expr *copyExpr = getBlockVarCopyInits(D);
5472 if (!copyExpr && record->hasTrivialDestructor()) return false;
5473
Mike Stump94967902009-10-21 18:16:27 +00005474 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00005475 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005476
5477 if (!Ty->isObjCRetainableType()) return false;
5478
5479 Qualifiers qs = Ty.getQualifiers();
5480
5481 // If we have lifetime, that dominates.
5482 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005483 switch (lifetime) {
5484 case Qualifiers::OCL_None: llvm_unreachable("impossible");
5485
5486 // These are just bits as far as the runtime is concerned.
5487 case Qualifiers::OCL_ExplicitNone:
5488 case Qualifiers::OCL_Autoreleasing:
5489 return false;
5490
5491 // Tell the runtime that this is ARC __weak, called by the
5492 // byref routines.
5493 case Qualifiers::OCL_Weak:
5494 // ARC __strong __block variables need to be retained.
5495 case Qualifiers::OCL_Strong:
5496 return true;
5497 }
5498 llvm_unreachable("fell out of lifetime switch!");
5499 }
5500 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
5501 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00005502}
5503
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005504bool ASTContext::getByrefLifetime(QualType Ty,
5505 Qualifiers::ObjCLifetime &LifeTime,
5506 bool &HasByrefExtendedLayout) const {
5507
5508 if (!getLangOpts().ObjC1 ||
5509 getLangOpts().getGC() != LangOptions::NonGC)
5510 return false;
5511
5512 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00005513 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005514 HasByrefExtendedLayout = true;
5515 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005516 } else if ((LifeTime = Ty.getObjCLifetime())) {
5517 // Honor the ARC qualifiers.
5518 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
5519 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005520 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00005521 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005522 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005523 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005524 return true;
5525}
5526
Douglas Gregorbab8a962011-09-08 01:46:34 +00005527TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5528 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00005529 ObjCInstanceTypeDecl =
5530 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00005531 return ObjCInstanceTypeDecl;
5532}
5533
Anders Carlsson18acd442007-10-29 06:33:42 +00005534// This returns true if a type has been typedefed to BOOL:
5535// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00005536static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00005537 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00005538 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5539 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00005540
Anders Carlssond8499822007-10-29 05:01:08 +00005541 return false;
5542}
5543
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005544/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005545/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00005546CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00005547 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5548 return CharUnits::Zero();
5549
Ken Dyck40775002010-01-11 17:06:35 +00005550 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00005551
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005552 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00005553 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00005554 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005555 // Treat arrays as pointers, since that's how they're passed in.
5556 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00005557 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00005558 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00005559}
5560
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005561bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00005562 return getTargetInfo().getCXXABI().isMicrosoft() &&
5563 VD->isStaticDataMember() &&
David Majnemerfac52432015-10-19 23:22:49 +00005564 VD->getType()->isIntegralOrEnumerationType() &&
5565 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005566}
5567
Richard Smithd9b90092016-07-02 01:32:16 +00005568ASTContext::InlineVariableDefinitionKind
5569ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
5570 if (!VD->isInline())
5571 return InlineVariableDefinitionKind::None;
5572
5573 // In almost all cases, it's a weak definition.
5574 auto *First = VD->getFirstDecl();
5575 if (!First->isConstexpr() || First->isInlineSpecified() ||
5576 !VD->isStaticDataMember())
5577 return InlineVariableDefinitionKind::Weak;
5578
5579 // If there's a file-context declaration in this translation unit, it's a
5580 // non-discardable definition.
5581 for (auto *D : VD->redecls())
5582 if (D->getLexicalDeclContext()->isFileContext())
5583 return InlineVariableDefinitionKind::Strong;
5584
5585 // If we've not seen one yet, we don't know.
5586 return InlineVariableDefinitionKind::WeakUnknown;
5587}
5588
Ken Dyck40775002010-01-11 17:06:35 +00005589static inline
5590std::string charUnitsToString(const CharUnits &CU) {
5591 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005592}
5593
John McCall351762c2011-02-07 10:33:21 +00005594/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00005595/// declaration.
John McCall351762c2011-02-07 10:33:21 +00005596std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5597 std::string S;
5598
David Chisnall950a9512009-11-17 19:33:30 +00005599 const BlockDecl *Decl = Expr->getBlockDecl();
5600 QualType BlockTy =
5601 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5602 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005603 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00005604 getObjCEncodingForMethodParameter(
5605 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5606 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005607 else
Alp Toker314cc812014-01-25 16:55:45 +00005608 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00005609 // Compute size of all parameters.
5610 // Start with computing size of a pointer in number of bytes.
5611 // FIXME: There might(should) be a better way of doing this computation!
5612 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005613 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5614 CharUnits ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005615 for (auto PI : Decl->parameters()) {
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005616 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005617 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00005618 if (sz.isZero())
5619 continue;
Ken Dyck40775002010-01-11 17:06:35 +00005620 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00005621 ParmOffset += sz;
5622 }
5623 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00005624 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00005625 // Block pointer and offset.
5626 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00005627
5628 // Argument types.
5629 ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005630 for (auto PVDecl : Decl->parameters()) {
David Chisnall950a9512009-11-17 19:33:30 +00005631 QualType PType = PVDecl->getOriginalType();
5632 if (const ArrayType *AT =
5633 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5634 // Use array's original type only if it has known number of
5635 // elements.
5636 if (!isa<ConstantArrayType>(AT))
5637 PType = PVDecl->getType();
5638 } else if (PType->isFunctionType())
5639 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005640 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005641 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5642 S, true /*Extended*/);
5643 else
5644 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00005645 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005646 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00005647 }
John McCall351762c2011-02-07 10:33:21 +00005648
5649 return S;
David Chisnall950a9512009-11-17 19:33:30 +00005650}
5651
John McCall843dfcc2016-11-29 21:57:00 +00005652std::string
5653ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
5654 std::string S;
David Chisnall50e4eba2010-12-30 14:05:53 +00005655 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00005656 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00005657 CharUnits ParmOffset;
5658 // Compute size of all parameters.
David Majnemer59f77922016-06-24 04:05:48 +00005659 for (auto PI : Decl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005660 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00005661 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005662 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005663 continue;
5664
John McCall843dfcc2016-11-29 21:57:00 +00005665 assert(sz.isPositive() &&
5666 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00005667 ParmOffset += sz;
5668 }
5669 S += charUnitsToString(ParmOffset);
5670 ParmOffset = CharUnits::Zero();
5671
5672 // Argument types.
David Majnemer59f77922016-06-24 04:05:48 +00005673 for (auto PVDecl : Decl->parameters()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005674 QualType PType = PVDecl->getOriginalType();
5675 if (const ArrayType *AT =
5676 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5677 // Use array's original type only if it has known number of
5678 // elements.
5679 if (!isa<ConstantArrayType>(AT))
5680 PType = PVDecl->getType();
5681 } else if (PType->isFunctionType())
5682 PType = PVDecl->getType();
5683 getObjCEncodingForType(PType, S);
5684 S += charUnitsToString(ParmOffset);
5685 ParmOffset += getObjCEncodingTypeSize(PType);
5686 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005687
John McCall843dfcc2016-11-29 21:57:00 +00005688 return S;
David Chisnall50e4eba2010-12-30 14:05:53 +00005689}
5690
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005691/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5692/// method parameter or return type. If Extended, include class names and
5693/// block object types.
5694void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5695 QualType T, std::string& S,
5696 bool Extended) const {
5697 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5698 getObjCEncodingForTypeQualifier(QT, S);
5699 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005700 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005701 true /*OutermostType*/,
5702 false /*EncodingProperty*/,
5703 false /*StructField*/,
5704 Extended /*EncodeBlockParameters*/,
5705 Extended /*EncodeClassNames*/);
5706}
5707
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005708/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005709/// declaration.
John McCall843dfcc2016-11-29 21:57:00 +00005710std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
5711 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005712 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005713 // Encode return type.
John McCall843dfcc2016-11-29 21:57:00 +00005714 std::string S;
Alp Toker314cc812014-01-25 16:55:45 +00005715 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5716 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005717 // Compute size of all parameters.
5718 // Start with computing size of a pointer in number of bytes.
5719 // FIXME: There might(should) be a better way of doing this computation!
5720 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005721 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005722 // The first two arguments (self and _cmd) are pointers; account for
5723 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00005724 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005725 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005726 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005727 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005728 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005729 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005730 continue;
5731
Ken Dyck40775002010-01-11 17:06:35 +00005732 assert (sz.isPositive() &&
5733 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005734 ParmOffset += sz;
5735 }
Ken Dyck40775002010-01-11 17:06:35 +00005736 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005737 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005738 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005739
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005740 // Argument types.
5741 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005742 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005743 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005744 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005745 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005746 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005747 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5748 // Use array's original type only if it has known number of
5749 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005750 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005751 PType = PVDecl->getType();
5752 } else if (PType->isFunctionType())
5753 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005754 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5755 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005756 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005757 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005758 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005759
John McCall843dfcc2016-11-29 21:57:00 +00005760 return S;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005761}
5762
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005763ObjCPropertyImplDecl *
5764ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5765 const ObjCPropertyDecl *PD,
5766 const Decl *Container) const {
5767 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005768 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005769 if (const ObjCCategoryImplDecl *CID =
5770 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005771 for (auto *PID : CID->property_impls())
5772 if (PID->getPropertyDecl() == PD)
5773 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005774 } else {
5775 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5776 for (auto *PID : OID->property_impls())
5777 if (PID->getPropertyDecl() == PD)
5778 return PID;
5779 }
5780 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005781}
5782
Daniel Dunbar4932b362008-08-28 04:38:10 +00005783/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005784/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005785/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5786/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005787/// Property attributes are stored as a comma-delimited C string. The simple
5788/// attributes readonly and bycopy are encoded as single characters. The
5789/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5790/// encoded as single characters, followed by an identifier. Property types
5791/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005792/// these attributes are defined by the following enumeration:
5793/// @code
5794/// enum PropertyAttributes {
5795/// kPropertyReadOnly = 'R', // property is read-only.
5796/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5797/// kPropertyByref = '&', // property is a reference to the value last assigned
5798/// kPropertyDynamic = 'D', // property is dynamic
5799/// kPropertyGetter = 'G', // followed by getter selector name
5800/// kPropertySetter = 'S', // followed by setter selector name
5801/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005802/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005803/// kPropertyWeak = 'W' // 'weak' property
5804/// kPropertyStrong = 'P' // property GC'able
5805/// kPropertyNonAtomic = 'N' // property non-atomic
5806/// };
5807/// @endcode
John McCall843dfcc2016-11-29 21:57:00 +00005808std::string
5809ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
5810 const Decl *Container) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005811 // Collect information from the property implementation decl(s).
5812 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005813 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005814
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005815 if (ObjCPropertyImplDecl *PropertyImpDecl =
5816 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5817 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5818 Dynamic = true;
5819 else
5820 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005821 }
5822
5823 // FIXME: This is not very efficient.
John McCall843dfcc2016-11-29 21:57:00 +00005824 std::string S = "T";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005825
5826 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005827 // GCC has some special rules regarding encoding of properties which
5828 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005829 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005830
5831 if (PD->isReadOnly()) {
5832 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005833 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5834 S += ",C";
5835 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5836 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005837 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5838 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005839 } else {
5840 switch (PD->getSetterKind()) {
5841 case ObjCPropertyDecl::Assign: break;
5842 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005843 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005844 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005845 }
5846 }
5847
5848 // It really isn't clear at all what this means, since properties
5849 // are "dynamic by default".
5850 if (Dynamic)
5851 S += ",D";
5852
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005853 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5854 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005855
Daniel Dunbar4932b362008-08-28 04:38:10 +00005856 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5857 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005858 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005859 }
5860
5861 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5862 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005863 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005864 }
5865
5866 if (SynthesizePID) {
5867 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5868 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005869 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005870 }
5871
5872 // FIXME: OBJCGC: weak & strong
John McCall843dfcc2016-11-29 21:57:00 +00005873 return S;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005874}
5875
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005876/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005877/// Another legacy compatibility encoding: 32-bit longs are encoded as
5878/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005879/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5880///
5881void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005882 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005883 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005884 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005885 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005886 else
Jay Foad39c79802011-01-12 09:06:06 +00005887 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005888 PointeeTy = IntTy;
5889 }
5890 }
5891}
5892
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005893void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005894 const FieldDecl *Field,
5895 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005896 // We follow the behavior of gcc, expanding structures which are
5897 // directly pointed to, and expanding embedded structures. Note that
5898 // these rules are sufficient to prevent recursive encoding of the
5899 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005900 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005901 true /* outermost type */, false, false,
5902 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005903}
5904
Joe Groff98ac7d22014-07-07 22:25:15 +00005905void ASTContext::getObjCEncodingForPropertyType(QualType T,
5906 std::string& S) const {
5907 // Encode result type.
5908 // GCC has some special rules regarding encoding of properties which
5909 // closely resembles encoding of ivars.
5910 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5911 true /* outermost type */,
5912 true /* encoding property */);
5913}
5914
John McCall393a78d2012-12-20 02:45:14 +00005915static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5916 BuiltinType::Kind kind) {
5917 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005918 case BuiltinType::Void: return 'v';
5919 case BuiltinType::Bool: return 'B';
5920 case BuiltinType::Char_U:
5921 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005922 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005923 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005924 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005925 case BuiltinType::UInt: return 'I';
5926 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005927 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005928 case BuiltinType::UInt128: return 'T';
5929 case BuiltinType::ULongLong: return 'Q';
5930 case BuiltinType::Char_S:
5931 case BuiltinType::SChar: return 'c';
5932 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005933 case BuiltinType::WChar_S:
5934 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005935 case BuiltinType::Int: return 'i';
5936 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005937 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005938 case BuiltinType::LongLong: return 'q';
5939 case BuiltinType::Int128: return 't';
5940 case BuiltinType::Float: return 'f';
5941 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005942 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005943 case BuiltinType::NullPtr: return '*'; // like char*
5944
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005945 case BuiltinType::Float128:
John McCall393a78d2012-12-20 02:45:14 +00005946 case BuiltinType::Half:
5947 // FIXME: potentially need @encodes for these!
5948 return ' ';
5949
5950 case BuiltinType::ObjCId:
5951 case BuiltinType::ObjCClass:
5952 case BuiltinType::ObjCSel:
5953 llvm_unreachable("@encoding ObjC primitive type");
5954
5955 // OpenCL and placeholder types don't need @encodings.
Alexey Bader954ba212016-04-08 13:40:33 +00005956#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5957 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00005958#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005959 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005960 case BuiltinType::OCLClkEvent:
5961 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005962 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00005963 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005964 case BuiltinType::Dependent:
5965#define BUILTIN_TYPE(KIND, ID)
5966#define PLACEHOLDER_TYPE(KIND, ID) \
5967 case BuiltinType::KIND:
5968#include "clang/AST/BuiltinTypes.def"
5969 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005970 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005971 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005972}
5973
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005974static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5975 EnumDecl *Enum = ET->getDecl();
5976
5977 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5978 if (!Enum->isFixed())
5979 return 'i';
5980
5981 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005982 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5983 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005984}
5985
Jay Foad39c79802011-01-12 09:06:06 +00005986static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005987 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005988 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005989 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005990 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5991 // The GNU runtime requires more information; bitfields are encoded as b,
5992 // then the offset (in bits) of the first element, then the type of the
5993 // bitfield, then the size in bits. For example, in this structure:
5994 //
5995 // struct
5996 // {
5997 // int integer;
5998 // int flags:2;
5999 // };
6000 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
6001 // runtime, but b32i2 for the GNU runtime. The reason for this extra
6002 // information is not especially sensible, but we're stuck with it for
6003 // compatibility with GCC, although providing it breaks anything that
6004 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00006005 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
Akira Hatanaka4b1c4842017-06-27 04:34:04 +00006006 uint64_t Offset;
6007
6008 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
6009 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
6010 IVD);
6011 } else {
6012 const RecordDecl *RD = FD->getParent();
6013 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
6014 Offset = RL.getFieldOffset(FD->getFieldIndex());
6015 }
6016
6017 S += llvm::utostr(Offset);
6018
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006019 if (const EnumType *ET = T->getAs<EnumType>())
6020 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00006021 else {
6022 const BuiltinType *BT = T->castAs<BuiltinType>();
6023 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
6024 }
David Chisnallb190a2c2010-06-04 01:10:52 +00006025 }
Richard Smithcaf33902011-10-10 18:28:20 +00006026 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006027}
6028
Daniel Dunbar07d07852009-10-18 21:17:35 +00006029// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006030void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
6031 bool ExpandPointedToStructures,
6032 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00006033 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006034 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006035 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006036 bool StructField,
6037 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006038 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006039 bool EncodePointerToObjCTypedef,
6040 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00006041 CanQualType CT = getCanonicalType(T);
6042 switch (CT->getTypeClass()) {
6043 case Type::Builtin:
6044 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00006045 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00006046 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00006047 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
6048 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
6049 else
6050 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00006051 return;
Mike Stump11289f42009-09-09 15:08:12 +00006052
John McCall393a78d2012-12-20 02:45:14 +00006053 case Type::Complex: {
6054 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00006055 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006056 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006057 return;
6058 }
John McCall393a78d2012-12-20 02:45:14 +00006059
6060 case Type::Atomic: {
6061 const AtomicType *AT = T->castAs<AtomicType>();
6062 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006063 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00006064 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00006065 }
John McCall393a78d2012-12-20 02:45:14 +00006066
6067 // encoding for pointer or reference types.
6068 case Type::Pointer:
6069 case Type::LValueReference:
6070 case Type::RValueReference: {
6071 QualType PointeeTy;
6072 if (isa<PointerType>(CT)) {
6073 const PointerType *PT = T->castAs<PointerType>();
6074 if (PT->isObjCSelType()) {
6075 S += ':';
6076 return;
6077 }
6078 PointeeTy = PT->getPointeeType();
6079 } else {
6080 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
6081 }
6082
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006083 bool isReadOnly = false;
6084 // For historical/compatibility reasons, the read-only qualifier of the
6085 // pointee gets emitted _before_ the '^'. The read-only qualifier of
6086 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00006087 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00006088 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006089 if (OutermostType && T.isConstQualified()) {
6090 isReadOnly = true;
6091 S += 'r';
6092 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00006093 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006094 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006095 while (P->getAs<PointerType>())
6096 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006097 if (P.isConstQualified()) {
6098 isReadOnly = true;
6099 S += 'r';
6100 }
6101 }
6102 if (isReadOnly) {
6103 // Another legacy compatibility encoding. Some ObjC qualifier and type
6104 // combinations need to be rearranged.
6105 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006106 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00006107 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006108 }
Mike Stump11289f42009-09-09 15:08:12 +00006109
Anders Carlssond8499822007-10-29 05:01:08 +00006110 if (PointeeTy->isCharType()) {
6111 // char pointer types should be encoded as '*' unless it is a
6112 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00006113 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00006114 S += '*';
6115 return;
6116 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006117 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00006118 // GCC binary compat: Need to convert "struct objc_class *" to "#".
6119 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6120 S += '#';
6121 return;
6122 }
6123 // GCC binary compat: Need to convert "struct objc_object *" to "@".
6124 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6125 S += '@';
6126 return;
6127 }
6128 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00006129 }
Anders Carlssond8499822007-10-29 05:01:08 +00006130 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006131 getLegacyIntegralTypeEncoding(PointeeTy);
6132
Mike Stump11289f42009-09-09 15:08:12 +00006133 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006134 nullptr, false, false, false, false, false, false,
6135 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006136 return;
6137 }
John McCall393a78d2012-12-20 02:45:14 +00006138
6139 case Type::ConstantArray:
6140 case Type::IncompleteArray:
6141 case Type::VariableArray: {
6142 const ArrayType *AT = cast<ArrayType>(CT);
6143
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006144 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006145 // Incomplete arrays are encoded as a pointer to the array element.
6146 S += '^';
6147
Mike Stump11289f42009-09-09 15:08:12 +00006148 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00006149 false, ExpandStructures, FD);
6150 } else {
6151 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00006152
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00006153 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6154 S += llvm::utostr(CAT->getSize().getZExtValue());
6155 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006156 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006157 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
6158 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00006159 S += '0';
6160 }
Mike Stump11289f42009-09-09 15:08:12 +00006161
6162 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006163 false, ExpandStructures, FD,
6164 false, false, false, false, false, false,
6165 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006166 S += ']';
6167 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006168 return;
6169 }
Mike Stump11289f42009-09-09 15:08:12 +00006170
John McCall393a78d2012-12-20 02:45:14 +00006171 case Type::FunctionNoProto:
6172 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00006173 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006174 return;
Mike Stump11289f42009-09-09 15:08:12 +00006175
John McCall393a78d2012-12-20 02:45:14 +00006176 case Type::Record: {
6177 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006178 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00006179 // Anonymous structures print as '?'
6180 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6181 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006182 if (ClassTemplateSpecializationDecl *Spec
6183 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
6184 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00006185 llvm::raw_string_ostream OS(S);
6186 TemplateSpecializationType::PrintTemplateArgumentList(OS,
David Majnemer6fbeee32016-07-07 04:43:07 +00006187 TemplateArgs.asArray(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00006188 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006189 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00006190 } else {
6191 S += '?';
6192 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00006193 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006194 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006195 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006196 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006197 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006198 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006199 if (FD) {
6200 S += '"';
6201 S += Field->getNameAsString();
6202 S += '"';
6203 }
Mike Stump11289f42009-09-09 15:08:12 +00006204
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006205 // Special case bit-fields.
6206 if (Field->isBitField()) {
6207 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006208 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006209 } else {
6210 QualType qt = Field->getType();
6211 getLegacyIntegralTypeEncoding(qt);
6212 getObjCEncodingForTypeImpl(qt, S, false, true,
6213 FD, /*OutermostType*/false,
6214 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006215 /*StructField*/true,
6216 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006217 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006218 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006219 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00006220 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006221 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006222 return;
6223 }
Mike Stump11289f42009-09-09 15:08:12 +00006224
John McCall393a78d2012-12-20 02:45:14 +00006225 case Type::BlockPointer: {
6226 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00006227 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006228 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00006229 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006230
6231 S += '<';
6232 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00006233 getObjCEncodingForTypeImpl(
6234 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
6235 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006236 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
6237 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006238 // Block self
6239 S += "@?";
6240 // Block parameters
6241 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00006242 for (const auto &I : FPT->param_types())
6243 getObjCEncodingForTypeImpl(
6244 I, S, ExpandPointedToStructures, ExpandStructures, FD,
6245 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006246 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
6247 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006248 }
6249 S += '>';
6250 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006251 return;
6252 }
Mike Stump11289f42009-09-09 15:08:12 +00006253
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006254 case Type::ObjCObject: {
6255 // hack to match legacy encoding of *id and *Class
6256 QualType Ty = getObjCObjectPointerType(CT);
6257 if (Ty->isObjCIdType()) {
6258 S += "{objc_object=}";
6259 return;
6260 }
6261 else if (Ty->isObjCClassType()) {
6262 S += "{objc_class=}";
6263 return;
6264 }
Galina Kistanovaf87496d2017-06-03 06:31:42 +00006265 // TODO: Double check to make sure this intentially falls through.
6266 LLVM_FALLTHROUGH;
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006267 }
6268
John McCall393a78d2012-12-20 02:45:14 +00006269 case Type::ObjCInterface: {
6270 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006271 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006272 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006273 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006274 S += OI->getObjCRuntimeNameAsString();
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006275 if (ExpandStructures) {
6276 S += '=';
6277 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6278 DeepCollectObjCIvars(OI, true, Ivars);
6279 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6280 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
6281 if (Field->isBitField())
6282 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
6283 else
6284 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
6285 false, false, false, false, false,
6286 EncodePointerToObjCTypedef,
6287 NotEncodedT);
6288 }
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006289 }
6290 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006291 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006292 }
Mike Stump11289f42009-09-09 15:08:12 +00006293
John McCall393a78d2012-12-20 02:45:14 +00006294 case Type::ObjCObjectPointer: {
6295 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006296 if (OPT->isObjCIdType()) {
6297 S += '@';
6298 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006299 }
Mike Stump11289f42009-09-09 15:08:12 +00006300
Steve Narofff0c86112009-10-28 22:03:49 +00006301 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
6302 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
6303 // Since this is a binary compatibility issue, need to consult with runtime
6304 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006305 S += '#';
6306 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006307 }
Mike Stump11289f42009-09-09 15:08:12 +00006308
Chris Lattnere7cabb92009-07-13 00:10:46 +00006309 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006310 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00006311 ExpandPointedToStructures,
6312 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006313 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006314 // Note that we do extended encoding of protocol qualifer list
6315 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006316 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00006317 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006318 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006319 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006320 S += '>';
6321 }
6322 S += '"';
6323 }
6324 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006325 }
Mike Stump11289f42009-09-09 15:08:12 +00006326
Chris Lattnere7cabb92009-07-13 00:10:46 +00006327 QualType PointeeTy = OPT->getPointeeType();
6328 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006329 isa<TypedefType>(PointeeTy.getTypePtr()) &&
6330 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006331 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00006332 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00006333 // {...};
6334 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006335 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00006336 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006337 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
6338 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6339 DeepCollectObjCIvars(OI, true, Ivars);
6340 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6341 if (cast<FieldDecl>(Ivars[i]) == FD) {
6342 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006343 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006344 S += '}';
6345 return;
6346 }
6347 }
6348 }
Mike Stump11289f42009-09-09 15:08:12 +00006349 getObjCEncodingForTypeImpl(PointeeTy, S,
6350 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00006351 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006352 false, false, false, false, false,
6353 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00006354 return;
6355 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006356
6357 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006358 if (OPT->getInterfaceDecl() &&
6359 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006360 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006361 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00006362 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006363 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006364 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00006365 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00006366 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006367 S += '"';
6368 }
6369 return;
6370 }
Mike Stump11289f42009-09-09 15:08:12 +00006371
John McCalla9e6e8d2010-05-17 23:56:34 +00006372 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00006373 // FIXME: we shoul do better than that. 'M' is available.
6374 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006375 // This matches gcc's encoding, even though technically it is insufficient.
6376 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00006377 case Type::Vector:
6378 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006379 // Until we have a coherent encoding of these three types, issue warning.
6380 { if (NotEncodedT)
6381 *NotEncodedT = T;
6382 return;
6383 }
6384
6385 // We could see an undeduced auto type here during error recovery.
6386 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00006387 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00006388 case Type::DeducedTemplateSpecialization:
Richard Smith27d807c2013-04-30 13:56:41 +00006389 return;
6390
Xiuli Pan9c14e282016-01-09 12:53:17 +00006391 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00006392#define ABSTRACT_TYPE(KIND, BASE)
6393#define TYPE(KIND, BASE)
6394#define DEPENDENT_TYPE(KIND, BASE) \
6395 case Type::KIND:
6396#define NON_CANONICAL_TYPE(KIND, BASE) \
6397 case Type::KIND:
6398#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
6399 case Type::KIND:
6400#include "clang/AST/TypeNodes.def"
6401 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00006402 }
John McCall393a78d2012-12-20 02:45:14 +00006403 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00006404}
6405
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006406void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
6407 std::string &S,
6408 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006409 bool includeVBases,
6410 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006411 assert(RDecl && "Expected non-null RecordDecl");
6412 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00006413 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006414 return;
6415
6416 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
6417 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
6418 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
6419
6420 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00006421 for (const auto &BI : CXXRec->bases()) {
6422 if (!BI.isVirtual()) {
6423 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006424 if (base->isEmpty())
6425 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006426 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006427 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6428 std::make_pair(offs, base));
6429 }
6430 }
6431 }
6432
6433 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00006434 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006435 uint64_t offs = layout.getFieldOffset(i);
6436 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00006437 std::make_pair(offs, Field));
6438 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006439 }
6440
6441 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00006442 for (const auto &BI : CXXRec->vbases()) {
6443 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006444 if (base->isEmpty())
6445 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006446 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00006447 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
6448 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00006449 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
6450 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006451 }
6452 }
6453
6454 CharUnits size;
6455 if (CXXRec) {
6456 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
6457 } else {
6458 size = layout.getSize();
6459 }
6460
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006461#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006462 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006463#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006464 std::multimap<uint64_t, NamedDecl *>::iterator
6465 CurLayObj = FieldOrBaseOffsets.begin();
6466
Douglas Gregorf5d6c742012-04-27 22:30:01 +00006467 if (CXXRec && CXXRec->isDynamicClass() &&
6468 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006469 if (FD) {
6470 S += "\"_vptr$";
6471 std::string recname = CXXRec->getNameAsString();
6472 if (recname.empty()) recname = "?";
6473 S += recname;
6474 S += '"';
6475 }
6476 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006477#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006478 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006479#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006480 }
6481
6482 if (!RDecl->hasFlexibleArrayMember()) {
6483 // Mark the end of the structure.
6484 uint64_t offs = toBits(size);
6485 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00006486 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006487 }
6488
6489 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006490#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006491 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006492 if (CurOffs < CurLayObj->first) {
6493 uint64_t padding = CurLayObj->first - CurOffs;
6494 // FIXME: There doesn't seem to be a way to indicate in the encoding that
6495 // packing/alignment of members is different that normal, in which case
6496 // the encoding will be out-of-sync with the real layout.
6497 // If the runtime switches to just consider the size of types without
6498 // taking into account alignment, we could make padding explicit in the
6499 // encoding (e.g. using arrays of chars). The encoding strings would be
6500 // longer then though.
6501 CurOffs += padding;
6502 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006503#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006504
6505 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00006506 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006507 break; // reached end of structure.
6508
6509 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
6510 // We expand the bases without their virtual bases since those are going
6511 // in the initial structure. Note that this differs from gcc which
6512 // expands virtual bases each time one is encountered in the hierarchy,
6513 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006514 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
6515 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006516 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006517#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006518 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006519#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006520 } else {
6521 FieldDecl *field = cast<FieldDecl>(dcl);
6522 if (FD) {
6523 S += '"';
6524 S += field->getNameAsString();
6525 S += '"';
6526 }
6527
6528 if (field->isBitField()) {
6529 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006530#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00006531 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006532#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006533 } else {
6534 QualType qt = field->getType();
6535 getLegacyIntegralTypeEncoding(qt);
6536 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
6537 /*OutermostType*/false,
6538 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006539 /*StructField*/true,
6540 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006541#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006542 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006543#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006544 }
6545 }
6546 }
6547}
6548
Mike Stump11289f42009-09-09 15:08:12 +00006549void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00006550 std::string& S) const {
6551 if (QT & Decl::OBJC_TQ_In)
6552 S += 'n';
6553 if (QT & Decl::OBJC_TQ_Inout)
6554 S += 'N';
6555 if (QT & Decl::OBJC_TQ_Out)
6556 S += 'o';
6557 if (QT & Decl::OBJC_TQ_Bycopy)
6558 S += 'O';
6559 if (QT & Decl::OBJC_TQ_Byref)
6560 S += 'R';
6561 if (QT & Decl::OBJC_TQ_Oneway)
6562 S += 'V';
6563}
6564
Douglas Gregor3ea72692011-08-12 05:46:01 +00006565TypedefDecl *ASTContext::getObjCIdDecl() const {
6566 if (!ObjCIdDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006567 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
Douglas Gregor3ea72692011-08-12 05:46:01 +00006568 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006569 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00006570 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00006571 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00006572}
6573
Douglas Gregor52e02802011-08-12 06:17:30 +00006574TypedefDecl *ASTContext::getObjCSelDecl() const {
6575 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006576 QualType T = getPointerType(ObjCBuiltinSelTy);
6577 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00006578 }
6579 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00006580}
6581
Douglas Gregor0a586182011-08-12 05:59:41 +00006582TypedefDecl *ASTContext::getObjCClassDecl() const {
6583 if (!ObjCClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006584 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
Douglas Gregor0a586182011-08-12 05:59:41 +00006585 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006586 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00006587 }
Douglas Gregor0a586182011-08-12 05:59:41 +00006588 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00006589}
6590
Douglas Gregord53ae832012-01-17 18:09:05 +00006591ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6592 if (!ObjCProtocolClassDecl) {
6593 ObjCProtocolClassDecl
6594 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6595 SourceLocation(),
6596 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00006597 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00006598 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00006599 SourceLocation(), true);
6600 }
6601
6602 return ObjCProtocolClassDecl;
6603}
6604
Meador Inge5d3fb222012-06-16 03:34:49 +00006605//===----------------------------------------------------------------------===//
6606// __builtin_va_list Construction Functions
6607//===----------------------------------------------------------------------===//
6608
Charles Davisc7d5c942015-09-17 20:55:33 +00006609static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6610 StringRef Name) {
6611 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006612 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00006613 return Context->buildImplicitTypedef(T, Name);
6614}
6615
6616static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6617 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6618}
6619
6620static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6621 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006622}
6623
6624static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6625 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006626 QualType T = Context->getPointerType(Context->VoidTy);
6627 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006628}
6629
Tim Northover9bb857a2013-01-31 12:13:10 +00006630static TypedefDecl *
6631CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006632 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006633 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006634 if (Context->getLangOpts().CPlusPlus) {
6635 // namespace std { struct __va_list {
6636 NamespaceDecl *NS;
6637 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6638 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00006639 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00006640 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006641 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006642 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00006643 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00006644 }
6645
6646 VaListTagDecl->startDefinition();
6647
6648 const size_t NumFields = 5;
6649 QualType FieldTypes[NumFields];
6650 const char *FieldNames[NumFields];
6651
6652 // void *__stack;
6653 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6654 FieldNames[0] = "__stack";
6655
6656 // void *__gr_top;
6657 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6658 FieldNames[1] = "__gr_top";
6659
6660 // void *__vr_top;
6661 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6662 FieldNames[2] = "__vr_top";
6663
6664 // int __gr_offs;
6665 FieldTypes[3] = Context->IntTy;
6666 FieldNames[3] = "__gr_offs";
6667
6668 // int __vr_offs;
6669 FieldTypes[4] = Context->IntTy;
6670 FieldNames[4] = "__vr_offs";
6671
6672 // Create fields
6673 for (unsigned i = 0; i < NumFields; ++i) {
6674 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6675 VaListTagDecl,
6676 SourceLocation(),
6677 SourceLocation(),
6678 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006679 FieldTypes[i], /*TInfo=*/nullptr,
6680 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00006681 /*Mutable=*/false,
6682 ICIS_NoInit);
6683 Field->setAccess(AS_public);
6684 VaListTagDecl->addDecl(Field);
6685 }
6686 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006687 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00006688 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00006689
6690 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006691 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006692}
6693
Meador Inge5d3fb222012-06-16 03:34:49 +00006694static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6695 // typedef struct __va_list_tag {
6696 RecordDecl *VaListTagDecl;
6697
Alp Toker2dea15b2013-12-17 01:22:38 +00006698 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006699 VaListTagDecl->startDefinition();
6700
6701 const size_t NumFields = 5;
6702 QualType FieldTypes[NumFields];
6703 const char *FieldNames[NumFields];
6704
6705 // unsigned char gpr;
6706 FieldTypes[0] = Context->UnsignedCharTy;
6707 FieldNames[0] = "gpr";
6708
6709 // unsigned char fpr;
6710 FieldTypes[1] = Context->UnsignedCharTy;
6711 FieldNames[1] = "fpr";
6712
6713 // unsigned short reserved;
6714 FieldTypes[2] = Context->UnsignedShortTy;
6715 FieldNames[2] = "reserved";
6716
6717 // void* overflow_arg_area;
6718 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6719 FieldNames[3] = "overflow_arg_area";
6720
6721 // void* reg_save_area;
6722 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6723 FieldNames[4] = "reg_save_area";
6724
6725 // Create fields
6726 for (unsigned i = 0; i < NumFields; ++i) {
6727 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6728 SourceLocation(),
6729 SourceLocation(),
6730 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006731 FieldTypes[i], /*TInfo=*/nullptr,
6732 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006733 /*Mutable=*/false,
6734 ICIS_NoInit);
6735 Field->setAccess(AS_public);
6736 VaListTagDecl->addDecl(Field);
6737 }
6738 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006739 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006740 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6741
6742 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006743 TypedefDecl *VaListTagTypedefDecl =
6744 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6745
Meador Inge5d3fb222012-06-16 03:34:49 +00006746 QualType VaListTagTypedefType =
6747 Context->getTypedefType(VaListTagTypedefDecl);
6748
6749 // typedef __va_list_tag __builtin_va_list[1];
6750 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6751 QualType VaListTagArrayType
6752 = Context->getConstantArrayType(VaListTagTypedefType,
6753 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006754 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006755}
6756
6757static TypedefDecl *
6758CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006759 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00006760 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006761 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006762 VaListTagDecl->startDefinition();
6763
6764 const size_t NumFields = 4;
6765 QualType FieldTypes[NumFields];
6766 const char *FieldNames[NumFields];
6767
6768 // unsigned gp_offset;
6769 FieldTypes[0] = Context->UnsignedIntTy;
6770 FieldNames[0] = "gp_offset";
6771
6772 // unsigned fp_offset;
6773 FieldTypes[1] = Context->UnsignedIntTy;
6774 FieldNames[1] = "fp_offset";
6775
6776 // void* overflow_arg_area;
6777 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6778 FieldNames[2] = "overflow_arg_area";
6779
6780 // void* reg_save_area;
6781 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6782 FieldNames[3] = "reg_save_area";
6783
6784 // Create fields
6785 for (unsigned i = 0; i < NumFields; ++i) {
6786 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6787 VaListTagDecl,
6788 SourceLocation(),
6789 SourceLocation(),
6790 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006791 FieldTypes[i], /*TInfo=*/nullptr,
6792 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006793 /*Mutable=*/false,
6794 ICIS_NoInit);
6795 Field->setAccess(AS_public);
6796 VaListTagDecl->addDecl(Field);
6797 }
6798 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006799 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006800 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6801
Richard Smith9b88a4c2015-07-27 05:40:23 +00006802 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00006803
Richard Smith9b88a4c2015-07-27 05:40:23 +00006804 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00006805 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006806 QualType VaListTagArrayType =
6807 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006808 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006809}
6810
6811static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6812 // typedef int __builtin_va_list[4];
6813 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
Yaron Kerene0bcdd42016-10-08 06:45:10 +00006814 QualType IntArrayType =
6815 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006816 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006817}
6818
Logan Chien57086ce2012-10-10 06:56:20 +00006819static TypedefDecl *
6820CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006821 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006822 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006823 if (Context->getLangOpts().CPlusPlus) {
6824 // namespace std { struct __va_list {
6825 NamespaceDecl *NS;
6826 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6827 Context->getTranslationUnitDecl(),
6828 /*Inline*/false, SourceLocation(),
6829 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006830 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006831 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006832 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006833 }
6834
6835 VaListDecl->startDefinition();
6836
6837 // void * __ap;
6838 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6839 VaListDecl,
6840 SourceLocation(),
6841 SourceLocation(),
6842 &Context->Idents.get("__ap"),
6843 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006844 /*TInfo=*/nullptr,
6845 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006846 /*Mutable=*/false,
6847 ICIS_NoInit);
6848 Field->setAccess(AS_public);
6849 VaListDecl->addDecl(Field);
6850
6851 // };
6852 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00006853 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00006854
6855 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006856 QualType T = Context->getRecordType(VaListDecl);
6857 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006858}
6859
Ulrich Weigand47445072013-05-06 16:26:41 +00006860static TypedefDecl *
6861CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006862 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00006863 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006864 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006865 VaListTagDecl->startDefinition();
6866
6867 const size_t NumFields = 4;
6868 QualType FieldTypes[NumFields];
6869 const char *FieldNames[NumFields];
6870
6871 // long __gpr;
6872 FieldTypes[0] = Context->LongTy;
6873 FieldNames[0] = "__gpr";
6874
6875 // long __fpr;
6876 FieldTypes[1] = Context->LongTy;
6877 FieldNames[1] = "__fpr";
6878
6879 // void *__overflow_arg_area;
6880 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6881 FieldNames[2] = "__overflow_arg_area";
6882
6883 // void *__reg_save_area;
6884 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6885 FieldNames[3] = "__reg_save_area";
6886
6887 // Create fields
6888 for (unsigned i = 0; i < NumFields; ++i) {
6889 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6890 VaListTagDecl,
6891 SourceLocation(),
6892 SourceLocation(),
6893 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006894 FieldTypes[i], /*TInfo=*/nullptr,
6895 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006896 /*Mutable=*/false,
6897 ICIS_NoInit);
6898 Field->setAccess(AS_public);
6899 VaListTagDecl->addDecl(Field);
6900 }
6901 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006902 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00006903 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00006904
Richard Smith9b88a4c2015-07-27 05:40:23 +00006905 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00006906
6907 // typedef __va_list_tag __builtin_va_list[1];
6908 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006909 QualType VaListTagArrayType =
6910 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006911
Alp Toker56b5cc92013-12-15 10:36:26 +00006912 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006913}
6914
Meador Inge5d3fb222012-06-16 03:34:49 +00006915static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6916 TargetInfo::BuiltinVaListKind Kind) {
6917 switch (Kind) {
6918 case TargetInfo::CharPtrBuiltinVaList:
6919 return CreateCharPtrBuiltinVaListDecl(Context);
6920 case TargetInfo::VoidPtrBuiltinVaList:
6921 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006922 case TargetInfo::AArch64ABIBuiltinVaList:
6923 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006924 case TargetInfo::PowerABIBuiltinVaList:
6925 return CreatePowerABIBuiltinVaListDecl(Context);
6926 case TargetInfo::X86_64ABIBuiltinVaList:
6927 return CreateX86_64ABIBuiltinVaListDecl(Context);
6928 case TargetInfo::PNaClABIBuiltinVaList:
6929 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006930 case TargetInfo::AAPCSABIBuiltinVaList:
6931 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006932 case TargetInfo::SystemZBuiltinVaList:
6933 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006934 }
6935
6936 llvm_unreachable("Unhandled __builtin_va_list type kind");
6937}
6938
6939TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006940 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006941 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006942 assert(BuiltinVaListDecl->isImplicit());
6943 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006944
6945 return BuiltinVaListDecl;
6946}
6947
Richard Smith9b88a4c2015-07-27 05:40:23 +00006948Decl *ASTContext::getVaListTagDecl() const {
6949 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00006950 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00006951 if (!VaListTagDecl)
6952 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00006953
Richard Smith9b88a4c2015-07-27 05:40:23 +00006954 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00006955}
6956
Charles Davisc7d5c942015-09-17 20:55:33 +00006957TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6958 if (!BuiltinMSVaListDecl)
6959 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6960
6961 return BuiltinMSVaListDecl;
6962}
6963
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006964void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006965 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006966 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006967
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006968 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006969}
6970
John McCalld28ae272009-12-02 08:04:21 +00006971/// \brief Retrieve the template name that corresponds to a non-empty
6972/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006973TemplateName
6974ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6975 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006976 unsigned size = End - Begin;
6977 assert(size > 1 && "set is not overloaded!");
6978
6979 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6980 size * sizeof(FunctionTemplateDecl*));
6981 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6982
6983 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006984 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006985 NamedDecl *D = *I;
6986 assert(isa<FunctionTemplateDecl>(D) ||
6987 (isa<UsingShadowDecl>(D) &&
6988 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6989 *Storage++ = D;
6990 }
6991
6992 return TemplateName(OT);
6993}
6994
Douglas Gregordc572a32009-03-30 22:58:21 +00006995/// \brief Retrieve the template name that represents a qualified
6996/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006997TemplateName
6998ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6999 bool TemplateKeyword,
7000 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00007001 assert(NNS && "Missing nested-name-specifier in qualified template name");
7002
Douglas Gregorc42075a2010-02-04 18:10:26 +00007003 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00007004 llvm::FoldingSetNodeID ID;
7005 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
7006
Craig Topper36250ad2014-05-12 05:36:57 +00007007 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007008 QualifiedTemplateName *QTN =
7009 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7010 if (!QTN) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007011 QTN = new (*this, alignof(QualifiedTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007012 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00007013 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
7014 }
7015
7016 return TemplateName(QTN);
7017}
7018
7019/// \brief Retrieve the template name that represents a dependent
7020/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00007021TemplateName
7022ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
7023 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00007024 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00007025 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00007026
7027 llvm::FoldingSetNodeID ID;
7028 DependentTemplateName::Profile(ID, NNS, Name);
7029
Craig Topper36250ad2014-05-12 05:36:57 +00007030 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007031 DependentTemplateName *QTN =
7032 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7033
7034 if (QTN)
7035 return TemplateName(QTN);
7036
7037 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7038 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007039 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007040 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00007041 } else {
7042 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007043 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007044 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00007045 DependentTemplateName *CheckQTN =
7046 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7047 assert(!CheckQTN && "Dependent type name canonicalization broken");
7048 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00007049 }
7050
7051 DependentTemplateNames.InsertNode(QTN, InsertPos);
7052 return TemplateName(QTN);
7053}
7054
Douglas Gregor71395fa2009-11-04 00:56:37 +00007055/// \brief Retrieve the template name that represents a dependent
7056/// template name such as \c MetaFun::template operator+.
7057TemplateName
7058ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00007059 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00007060 assert((!NNS || NNS->isDependent()) &&
7061 "Nested name specifier must be dependent");
7062
7063 llvm::FoldingSetNodeID ID;
7064 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00007065
7066 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00007067 DependentTemplateName *QTN
7068 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007069
7070 if (QTN)
7071 return TemplateName(QTN);
7072
7073 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7074 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007075 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007076 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007077 } else {
7078 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007079 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007080 DependentTemplateName(NNS, Operator, Canon);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007081
Douglas Gregorc42075a2010-02-04 18:10:26 +00007082 DependentTemplateName *CheckQTN
7083 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7084 assert(!CheckQTN && "Dependent template name canonicalization broken");
7085 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00007086 }
7087
7088 DependentTemplateNames.InsertNode(QTN, InsertPos);
7089 return TemplateName(QTN);
7090}
7091
Douglas Gregor5590be02011-01-15 06:45:20 +00007092TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00007093ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
7094 TemplateName replacement) const {
7095 llvm::FoldingSetNodeID ID;
7096 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00007097
7098 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00007099 SubstTemplateTemplateParmStorage *subst
7100 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
7101
7102 if (!subst) {
7103 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
7104 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
7105 }
7106
7107 return TemplateName(subst);
7108}
7109
7110TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00007111ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
7112 const TemplateArgument &ArgPack) const {
7113 ASTContext &Self = const_cast<ASTContext &>(*this);
7114 llvm::FoldingSetNodeID ID;
7115 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00007116
7117 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00007118 SubstTemplateTemplateParmPackStorage *Subst
7119 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
7120
7121 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00007122 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00007123 ArgPack.pack_size(),
7124 ArgPack.pack_begin());
7125 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7126 }
7127
7128 return TemplateName(Subst);
7129}
7130
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007131/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00007132/// TargetInfo, produce the corresponding type. The unsigned @p Type
7133/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00007134CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007135 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00007136 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007137 case TargetInfo::SignedChar: return SignedCharTy;
7138 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007139 case TargetInfo::SignedShort: return ShortTy;
7140 case TargetInfo::UnsignedShort: return UnsignedShortTy;
7141 case TargetInfo::SignedInt: return IntTy;
7142 case TargetInfo::UnsignedInt: return UnsignedIntTy;
7143 case TargetInfo::SignedLong: return LongTy;
7144 case TargetInfo::UnsignedLong: return UnsignedLongTy;
7145 case TargetInfo::SignedLongLong: return LongLongTy;
7146 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
7147 }
7148
David Blaikie83d382b2011-09-23 05:06:16 +00007149 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007150}
Ted Kremenek77c51b22008-07-24 23:58:27 +00007151
7152//===----------------------------------------------------------------------===//
7153// Type Predicates.
7154//===----------------------------------------------------------------------===//
7155
Fariborz Jahanian96207692009-02-18 21:49:28 +00007156/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7157/// garbage collection attribute.
7158///
John McCall553d45a2011-01-12 00:34:59 +00007159Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007160 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00007161 return Qualifiers::GCNone;
7162
David Blaikiebbafb8a2012-03-11 07:00:24 +00007163 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00007164 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7165
7166 // Default behaviour under objective-C's gc is for ObjC pointers
7167 // (or pointers to them) be treated as though they were declared
7168 // as __strong.
7169 if (GCAttrs == Qualifiers::GCNone) {
7170 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7171 return Qualifiers::Strong;
7172 else if (Ty->isPointerType())
7173 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
7174 } else {
7175 // It's not valid to set GC attributes on anything that isn't a
7176 // pointer.
7177#ifndef NDEBUG
7178 QualType CT = Ty->getCanonicalTypeInternal();
7179 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
7180 CT = AT->getElementType();
7181 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7182#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00007183 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00007184 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00007185}
7186
Chris Lattner49af6a42008-04-07 06:51:04 +00007187//===----------------------------------------------------------------------===//
7188// Type Compatibility Testing
7189//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00007190
Mike Stump11289f42009-09-09 15:08:12 +00007191/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007192/// compatible.
7193static bool areCompatVectorTypes(const VectorType *LHS,
7194 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00007195 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00007196 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00007197 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00007198}
7199
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007200bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
7201 QualType SecondVec) {
7202 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
7203 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
7204
7205 if (hasSameUnqualifiedType(FirstVec, SecondVec))
7206 return true;
7207
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007208 // Treat Neon vector types and most AltiVec vector types as if they are the
7209 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007210 const VectorType *First = FirstVec->getAs<VectorType>();
7211 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007212 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007213 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007214 First->getVectorKind() != VectorType::AltiVecPixel &&
7215 First->getVectorKind() != VectorType::AltiVecBool &&
7216 Second->getVectorKind() != VectorType::AltiVecPixel &&
7217 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007218 return true;
7219
7220 return false;
7221}
7222
Steve Naroff8e6aee52009-07-23 01:01:38 +00007223//===----------------------------------------------------------------------===//
7224// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7225//===----------------------------------------------------------------------===//
7226
7227/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7228/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00007229bool
7230ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
7231 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00007232 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007233 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00007234 for (auto *PI : rProto->protocols())
7235 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007236 return true;
7237 return false;
7238}
7239
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00007240/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
7241/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007242bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
7243 QualType rhs) {
7244 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
7245 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7246 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
7247
Aaron Ballman83731462014-03-17 16:14:00 +00007248 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007249 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007250 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007251 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
7252 match = true;
7253 break;
7254 }
7255 }
7256 if (!match)
7257 return false;
7258 }
7259 return true;
7260}
7261
Steve Naroff8e6aee52009-07-23 01:01:38 +00007262/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
7263/// ObjCQualifiedIDType.
7264bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
7265 bool compare) {
7266 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00007267 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007268 lhs->isObjCIdType() || lhs->isObjCClassType())
7269 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007270 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007271 rhs->isObjCIdType() || rhs->isObjCClassType())
7272 return true;
7273
7274 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00007275 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007276
Steve Naroff8e6aee52009-07-23 01:01:38 +00007277 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00007278
Steve Naroff8e6aee52009-07-23 01:01:38 +00007279 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00007280 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007281 // make sure we check the class hierarchy.
7282 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007283 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007284 // when comparing an id<P> on lhs with a static type on rhs,
7285 // see if static class implements all of id's protocols, directly or
7286 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007287 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007288 return false;
7289 }
7290 }
7291 // If there are no qualifiers and no interface, we have an 'id'.
7292 return true;
7293 }
Mike Stump11289f42009-09-09 15:08:12 +00007294 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007295 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007296 bool match = false;
7297
7298 // when comparing an id<P> on lhs with a static type on rhs,
7299 // see if static class implements all of id's protocols, directly or
7300 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007301 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007302 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7303 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7304 match = true;
7305 break;
7306 }
7307 }
Mike Stump11289f42009-09-09 15:08:12 +00007308 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007309 // make sure we check the class hierarchy.
7310 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007311 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007312 // when comparing an id<P> on lhs with a static type on rhs,
7313 // see if static class implements all of id's protocols, directly or
7314 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007315 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007316 match = true;
7317 break;
7318 }
7319 }
7320 }
7321 if (!match)
7322 return false;
7323 }
Mike Stump11289f42009-09-09 15:08:12 +00007324
Steve Naroff8e6aee52009-07-23 01:01:38 +00007325 return true;
7326 }
Mike Stump11289f42009-09-09 15:08:12 +00007327
Steve Naroff8e6aee52009-07-23 01:01:38 +00007328 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
7329 assert(rhsQID && "One of the LHS/RHS should be id<x>");
7330
Mike Stump11289f42009-09-09 15:08:12 +00007331 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00007332 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007333 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007334 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007335 bool match = false;
7336
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007337 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00007338 // see if static class implements all of id's protocols, directly or
7339 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007340 // First, lhs protocols in the qualifier list must be found, direct
7341 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00007342 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007343 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7344 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7345 match = true;
7346 break;
7347 }
7348 }
7349 if (!match)
7350 return false;
7351 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007352
7353 // Static class's protocols, or its super class or category protocols
7354 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
7355 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
7356 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
7357 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
7358 // This is rather dubious but matches gcc's behavior. If lhs has
7359 // no type qualifier and its class has no static protocol(s)
7360 // assume that it is mismatch.
7361 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
7362 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00007363 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007364 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007365 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007366 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7367 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7368 match = true;
7369 break;
7370 }
7371 }
7372 if (!match)
7373 return false;
7374 }
7375 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00007376 return true;
7377 }
7378 return false;
7379}
7380
Eli Friedman47f77112008-08-22 00:56:42 +00007381/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007382/// compatible for assignment from RHS to LHS. This handles validation of any
7383/// protocol qualifiers on the LHS or RHS.
7384///
Steve Naroff7cae42b2009-07-10 23:34:53 +00007385bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
7386 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00007387 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7388 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7389
Steve Naroff1329fa02009-07-15 18:40:39 +00007390 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00007391 if (LHS->isObjCUnqualifiedIdOrClass() ||
7392 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00007393 return true;
7394
Douglas Gregorab209d82015-07-07 03:58:42 +00007395 // Function object that propagates a successful result or handles
7396 // __kindof types.
7397 auto finish = [&](bool succeeded) -> bool {
7398 if (succeeded)
7399 return true;
7400
7401 if (!RHS->isKindOfType())
7402 return false;
7403
7404 // Strip off __kindof and protocol qualifiers, then check whether
7405 // we can assign the other way.
7406 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7407 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
7408 };
7409
7410 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
7411 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7412 QualType(RHSOPT,0),
7413 false));
7414 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007415
Douglas Gregorab209d82015-07-07 03:58:42 +00007416 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
7417 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
7418 QualType(RHSOPT,0)));
7419 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007420
John McCall8b07ec22010-05-15 11:32:37 +00007421 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00007422 if (LHS->getInterface() && RHS->getInterface()) {
7423 return finish(canAssignObjCInterfaces(LHS, RHS));
7424 }
Mike Stump11289f42009-09-09 15:08:12 +00007425
Steve Naroff8e6aee52009-07-23 01:01:38 +00007426 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007427}
7428
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007429/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00007430/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007431/// arguments in block literals. When passed as arguments, passing 'A*' where
7432/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
7433/// not OK. For the return type, the opposite is not OK.
7434bool ASTContext::canAssignObjCInterfacesInBlockPointer(
7435 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007436 const ObjCObjectPointerType *RHSOPT,
7437 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007438
7439 // Function object that propagates a successful result or handles
7440 // __kindof types.
7441 auto finish = [&](bool succeeded) -> bool {
7442 if (succeeded)
7443 return true;
7444
7445 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
7446 if (!Expected->isKindOfType())
7447 return false;
7448
7449 // Strip off __kindof and protocol qualifiers, then check whether
7450 // we can assign the other way.
7451 return canAssignObjCInterfacesInBlockPointer(
7452 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7453 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
7454 BlockReturnType);
7455 };
7456
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007457 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007458 return true;
7459
7460 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007461 return finish(RHSOPT->isObjCBuiltinType() ||
7462 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007463 }
7464
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007465 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00007466 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7467 QualType(RHSOPT,0),
7468 false));
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007469
7470 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
7471 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
7472 if (LHS && RHS) { // We have 2 user-defined types.
7473 if (LHS != RHS) {
7474 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007475 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007476 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007477 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007478 }
7479 else
7480 return true;
7481 }
7482 return false;
7483}
7484
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007485/// Comparison routine for Objective-C protocols to be used with
7486/// llvm::array_pod_sort.
7487static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
7488 ObjCProtocolDecl * const *rhs) {
7489 return (*lhs)->getName().compare((*rhs)->getName());
7490
7491}
7492
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007493/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007494/// of protocols inherited from two distinct objective-c pointer objects with
7495/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007496/// It is used to build composite qualifier list of the composite type of
7497/// the conditional expression involving two objective-c pointer objects.
7498static
7499void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007500 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007501 const ObjCObjectPointerType *LHSOPT,
7502 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007503 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007504
John McCall8b07ec22010-05-15 11:32:37 +00007505 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7506 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7507 assert(LHS->getInterface() && "LHS must have an interface base");
7508 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007509
7510 // Add all of the protocols for the LHS.
7511 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
7512
7513 // Start with the protocol qualifiers.
7514 for (auto proto : LHS->quals()) {
7515 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007516 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007517
7518 // Also add the protocols associated with the LHS interface.
7519 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
7520
7521 // Add all of the protocls for the RHS.
7522 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
7523
7524 // Start with the protocol qualifiers.
7525 for (auto proto : RHS->quals()) {
7526 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007527 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007528
7529 // Also add the protocols associated with the RHS interface.
7530 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
7531
7532 // Compute the intersection of the collected protocol sets.
7533 for (auto proto : LHSProtocolSet) {
7534 if (RHSProtocolSet.count(proto))
7535 IntersectionSet.push_back(proto);
7536 }
7537
7538 // Compute the set of protocols that is implied by either the common type or
7539 // the protocols within the intersection.
7540 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7541 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7542
7543 // Remove any implied protocols from the list of inherited protocols.
7544 if (!ImpliedProtocols.empty()) {
7545 IntersectionSet.erase(
7546 std::remove_if(IntersectionSet.begin(),
7547 IntersectionSet.end(),
7548 [&](ObjCProtocolDecl *proto) -> bool {
7549 return ImpliedProtocols.count(proto) > 0;
7550 }),
7551 IntersectionSet.end());
7552 }
7553
7554 // Sort the remaining protocols by name.
7555 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7556 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007557}
7558
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007559/// Determine whether the first type is a subtype of the second.
7560static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7561 QualType rhs) {
7562 // Common case: two object pointers.
7563 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7564 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7565 if (lhsOPT && rhsOPT)
7566 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7567
7568 // Two block pointers.
7569 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7570 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7571 if (lhsBlock && rhsBlock)
7572 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7573
7574 // If either is an unqualified 'id' and the other is a block, it's
7575 // acceptable.
7576 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7577 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7578 return true;
7579
7580 return false;
7581}
7582
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007583// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007584static bool sameObjCTypeArgs(ASTContext &ctx,
7585 const ObjCInterfaceDecl *iface,
7586 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00007587 ArrayRef<QualType> rhsArgs,
7588 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007589 if (lhsArgs.size() != rhsArgs.size())
7590 return false;
7591
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007592 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007593 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007594 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7595 continue;
7596
7597 switch (typeParams->begin()[i]->getVariance()) {
7598 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00007599 if (!stripKindOf ||
7600 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7601 rhsArgs[i].stripObjCKindOfType(ctx))) {
7602 return false;
7603 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007604 break;
7605
7606 case ObjCTypeParamVariance::Covariant:
7607 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7608 return false;
7609 break;
7610
7611 case ObjCTypeParamVariance::Contravariant:
7612 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7613 return false;
7614 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00007615 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007616 }
7617
7618 return true;
7619}
7620
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007621QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007622 const ObjCObjectPointerType *Lptr,
7623 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00007624 const ObjCObjectType *LHS = Lptr->getObjectType();
7625 const ObjCObjectType *RHS = Rptr->getObjectType();
7626 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7627 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007628
7629 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007630 return QualType();
Douglas Gregore83b9562015-07-07 03:57:53 +00007631
Manman Renc46f7d12016-05-06 19:35:02 +00007632 // When either LHS or RHS is a kindof type, we should return a kindof type.
7633 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
7634 // kindof(A).
7635 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
7636
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007637 // Follow the left-hand side up the class hierarchy until we either hit a
7638 // root or find the RHS. Record the ancestors in case we don't find it.
7639 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7640 LHSAncestors;
7641 while (true) {
7642 // Record this ancestor. We'll need this if the common type isn't in the
7643 // path from the LHS to the root.
7644 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00007645
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007646 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7647 // Get the type arguments.
7648 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7649 bool anyChanges = false;
7650 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7651 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007652 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7653 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007654 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007655 return QualType();
7656 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7657 // If only one has type arguments, the result will not have type
7658 // arguments.
7659 LHSTypeArgs = { };
7660 anyChanges = true;
7661 }
7662
7663 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007664 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007665 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7666 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00007667 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007668 anyChanges = true;
7669
7670 // If anything in the LHS will have changed, build a new result type.
Manman Renc46f7d12016-05-06 19:35:02 +00007671 // If we need to return a kindof type but LHS is not a kindof type, we
7672 // build a new result type.
7673 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007674 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007675 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00007676 anyKindOf || LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007677 return getObjCObjectPointerType(Result);
7678 }
7679
7680 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007681 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007682
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007683 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00007684 QualType LHSSuperType = LHS->getSuperClassType();
7685 if (LHSSuperType.isNull())
7686 break;
7687
7688 LHS = LHSSuperType->castAs<ObjCObjectType>();
7689 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007690
7691 // We didn't find anything by following the LHS to its root; now check
7692 // the RHS against the cached set of ancestors.
7693 while (true) {
7694 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7695 if (KnownLHS != LHSAncestors.end()) {
7696 LHS = KnownLHS->second;
7697
7698 // Get the type arguments.
7699 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7700 bool anyChanges = false;
7701 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7702 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007703 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7704 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007705 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007706 return QualType();
7707 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7708 // If only one has type arguments, the result will not have type
7709 // arguments.
7710 RHSTypeArgs = { };
7711 anyChanges = true;
7712 }
7713
7714 // Compute the intersection of protocols.
7715 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7716 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7717 Protocols);
7718 if (!Protocols.empty())
7719 anyChanges = true;
7720
Manman Renc46f7d12016-05-06 19:35:02 +00007721 // If we need to return a kindof type but RHS is not a kindof type, we
7722 // build a new result type.
7723 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007724 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007725 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00007726 anyKindOf || RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007727 return getObjCObjectPointerType(Result);
7728 }
7729
7730 return getObjCObjectPointerType(QualType(RHS, 0));
7731 }
7732
7733 // Find the superclass of the RHS.
7734 QualType RHSSuperType = RHS->getSuperClassType();
7735 if (RHSSuperType.isNull())
7736 break;
7737
7738 RHS = RHSSuperType->castAs<ObjCObjectType>();
7739 }
7740
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007741 return QualType();
7742}
7743
John McCall8b07ec22010-05-15 11:32:37 +00007744bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7745 const ObjCObjectType *RHS) {
7746 assert(LHS->getInterface() && "LHS is not an interface type");
7747 assert(RHS->getInterface() && "RHS is not an interface type");
7748
Chris Lattner49af6a42008-04-07 06:51:04 +00007749 // Verify that the base decls are compatible: the RHS must be a subclass of
7750 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00007751 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7752 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7753 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00007754 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007755
Douglas Gregore83b9562015-07-07 03:57:53 +00007756 // If the LHS has protocol qualifiers, determine whether all of them are
7757 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7758 // LHS).
7759 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007760 // OK if conversion of LHS to SuperClass results in narrowing of types
7761 // ; i.e., SuperClass may implement at least one of the protocols
7762 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7763 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7764 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7765 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7766 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7767 // qualifiers.
7768 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007769 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007770 // If there is no protocols associated with RHS, it is not a match.
7771 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00007772 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007773
7774 for (const auto *LHSProto : LHS->quals()) {
7775 bool SuperImplementsProtocol = false;
7776 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7777 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7778 SuperImplementsProtocol = true;
7779 break;
7780 }
7781 if (!SuperImplementsProtocol)
7782 return false;
7783 }
Chris Lattner49af6a42008-04-07 06:51:04 +00007784 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007785
7786 // If the LHS is specialized, we may need to check type arguments.
7787 if (LHS->isSpecialized()) {
7788 // Follow the superclass chain until we've matched the LHS class in the
7789 // hierarchy. This substitutes type arguments through.
7790 const ObjCObjectType *RHSSuper = RHS;
7791 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7792 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7793
7794 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007795 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007796 !sameObjCTypeArgs(*this, LHS->getInterface(),
7797 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007798 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007799 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00007800 }
7801 }
7802
7803 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00007804}
7805
Steve Naroffb7605152009-02-12 17:52:19 +00007806bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7807 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00007808 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7809 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007810
Steve Naroff7cae42b2009-07-10 23:34:53 +00007811 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00007812 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007813
7814 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7815 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00007816}
7817
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007818bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7819 return canAssignObjCInterfaces(
7820 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7821 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7822}
7823
Mike Stump11289f42009-09-09 15:08:12 +00007824/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00007825/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00007826/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00007827/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007828bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7829 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007830 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00007831 return hasSameType(LHS, RHS);
Joey Gouly5788b782016-11-18 14:10:54 +00007832
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007833 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00007834}
7835
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007836bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00007837 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007838}
7839
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007840bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7841 return !mergeTypes(LHS, RHS, true).isNull();
7842}
7843
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007844/// mergeTransparentUnionType - if T is a transparent union type and a member
7845/// of T is compatible with SubType, return the merged type, else return
7846/// QualType()
7847QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7848 bool OfBlockPointer,
7849 bool Unqualified) {
7850 if (const RecordType *UT = T->getAsUnionType()) {
7851 RecordDecl *UD = UT->getDecl();
7852 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007853 for (const auto *I : UD->fields()) {
7854 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007855 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7856 if (!MT.isNull())
7857 return MT;
7858 }
7859 }
7860 }
7861
7862 return QualType();
7863}
7864
Alp Toker9cacbab2014-01-20 20:26:09 +00007865/// mergeFunctionParameterTypes - merge two types which appear as function
7866/// parameter types
7867QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7868 bool OfBlockPointer,
7869 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007870 // GNU extension: two types are compatible if they appear as a function
7871 // argument, one of the types is a transparent union type and the other
7872 // type is compatible with a union member
7873 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7874 Unqualified);
7875 if (!lmerge.isNull())
7876 return lmerge;
7877
7878 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7879 Unqualified);
7880 if (!rmerge.isNull())
7881 return rmerge;
7882
7883 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7884}
7885
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007886QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007887 bool OfBlockPointer,
7888 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00007889 const FunctionType *lbase = lhs->getAs<FunctionType>();
7890 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007891 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7892 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00007893 bool allLTypes = true;
7894 bool allRTypes = true;
7895
7896 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007897 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00007898 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00007899 QualType RHS = rbase->getReturnType();
7900 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00007901 bool UnqualifiedResult = Unqualified;
7902 if (!UnqualifiedResult)
7903 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007904 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00007905 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007906 else
Alp Toker314cc812014-01-25 16:55:45 +00007907 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00007908 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007909 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007910
7911 if (Unqualified)
7912 retType = retType.getUnqualifiedType();
7913
Alp Toker314cc812014-01-25 16:55:45 +00007914 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7915 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007916 if (Unqualified) {
7917 LRetType = LRetType.getUnqualifiedType();
7918 RRetType = RRetType.getUnqualifiedType();
7919 }
7920
7921 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007922 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007923 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007924 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00007925
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00007926 // FIXME: double check this
7927 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7928 // rbase->getRegParmAttr() != 0 &&
7929 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00007930 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7931 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00007932
Douglas Gregor8c940862010-01-18 17:14:39 +00007933 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00007934 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00007935 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00007936
John McCall8c6b56f2010-12-15 01:06:38 +00007937 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00007938 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7939 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00007940 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7941 return QualType();
7942
John McCall31168b02011-06-15 23:02:42 +00007943 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7944 return QualType();
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00007945 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
7946 return QualType();
John McCall31168b02011-06-15 23:02:42 +00007947
John McCall8c6b56f2010-12-15 01:06:38 +00007948 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7949 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007950
Rafael Espindola8778c282012-11-29 16:09:03 +00007951 if (lbaseInfo.getNoReturn() != NoReturn)
7952 allLTypes = false;
7953 if (rbaseInfo.getNoReturn() != NoReturn)
7954 allRTypes = false;
7955
John McCall31168b02011-06-15 23:02:42 +00007956 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007957
Eli Friedman47f77112008-08-22 00:56:42 +00007958 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007959 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7960 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00007961 // Compatible functions must have the same number of parameters
7962 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00007963 return QualType();
7964
7965 // Variadic and non-variadic functions aren't compatible
7966 if (lproto->isVariadic() != rproto->isVariadic())
7967 return QualType();
7968
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007969 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7970 return QualType();
7971
John McCall18afab72016-03-01 00:49:02 +00007972 if (!doFunctionTypesMatchOnExtParameterInfos(rproto, lproto))
Fariborz Jahanian97676972011-09-28 21:52:05 +00007973 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00007974
7975 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007976 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007977 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7978 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7979 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7980 QualType paramType = mergeFunctionParameterTypes(
7981 lParamType, rParamType, OfBlockPointer, Unqualified);
7982 if (paramType.isNull())
7983 return QualType();
7984
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007985 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007986 paramType = paramType.getUnqualifiedType();
7987
7988 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007989 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007990 lParamType = lParamType.getUnqualifiedType();
7991 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007992 }
Alp Toker601b22c2014-01-21 23:35:24 +00007993
7994 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007995 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007996 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007997 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007998 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007999
Eli Friedman47f77112008-08-22 00:56:42 +00008000 if (allLTypes) return lhs;
8001 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008002
8003 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
8004 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00008005 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008006 }
8007
8008 if (lproto) allRTypes = false;
8009 if (rproto) allLTypes = false;
8010
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008011 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00008012 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008013 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00008014 if (proto->isVariadic()) return QualType();
8015 // Check that the types are compatible with the types that
8016 // would result from default argument promotions (C99 6.7.5.3p15).
8017 // The only types actually affected are promotable integer
8018 // types and floats, which would be passed as a different
8019 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00008020 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
8021 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00008022
Eli Friedman448ce402012-08-30 00:44:15 +00008023 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00008024 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00008025 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
8026 paramTy = Enum->getDecl()->getIntegerType();
8027 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00008028 return QualType();
8029 }
Alp Toker601b22c2014-01-21 23:35:24 +00008030
8031 if (paramTy->isPromotableIntegerType() ||
8032 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00008033 return QualType();
8034 }
8035
8036 if (allLTypes) return lhs;
8037 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008038
8039 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
8040 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00008041 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008042 }
8043
8044 if (allLTypes) return lhs;
8045 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00008046 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00008047}
8048
John McCall433c2e62013-03-21 00:10:07 +00008049/// Given that we have an enum type and a non-enum type, try to merge them.
8050static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
8051 QualType other, bool isBlockReturnType) {
8052 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
8053 // a signed integer type, or an unsigned integer type.
8054 // Compatibility is based on the underlying type, not the promotion
8055 // type.
8056 QualType underlyingType = ET->getDecl()->getIntegerType();
8057 if (underlyingType.isNull()) return QualType();
8058 if (Context.hasSameType(underlyingType, other))
8059 return other;
8060
8061 // In block return types, we're more permissive and accept any
8062 // integral type of the same size.
8063 if (isBlockReturnType && other->isIntegerType() &&
8064 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
8065 return other;
8066
8067 return QualType();
8068}
8069
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008070QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008071 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008072 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00008073 // C++ [expr]: If an expression initially has the type "reference to T", the
8074 // type is adjusted to "T" prior to any further analysis, the expression
8075 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008076 // expression is an lvalue unless the reference is an rvalue reference and
8077 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00008078 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
8079 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008080
8081 if (Unqualified) {
8082 LHS = LHS.getUnqualifiedType();
8083 RHS = RHS.getUnqualifiedType();
8084 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00008085
Eli Friedman47f77112008-08-22 00:56:42 +00008086 QualType LHSCan = getCanonicalType(LHS),
8087 RHSCan = getCanonicalType(RHS);
8088
8089 // If two types are identical, they are compatible.
8090 if (LHSCan == RHSCan)
8091 return LHS;
8092
John McCall8ccfcb52009-09-24 19:53:00 +00008093 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00008094 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8095 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00008096 if (LQuals != RQuals) {
8097 // If any of these qualifiers are different, we have a type
8098 // mismatch.
8099 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00008100 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
Roger Ferrer Ibanezd93add32017-02-24 08:41:09 +00008101 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
8102 LQuals.hasUnaligned() != RQuals.hasUnaligned())
John McCall8ccfcb52009-09-24 19:53:00 +00008103 return QualType();
8104
8105 // Exactly one GC qualifier difference is allowed: __strong is
8106 // okay if the other type has no GC qualifier but is an Objective
8107 // C object pointer (i.e. implicitly strong by default). We fix
8108 // this by pretending that the unqualified type was actually
8109 // qualified __strong.
8110 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8111 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8112 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8113
8114 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8115 return QualType();
8116
8117 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
8118 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
8119 }
8120 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
8121 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
8122 }
Eli Friedman47f77112008-08-22 00:56:42 +00008123 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00008124 }
8125
8126 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00008127
Eli Friedmandcca6332009-06-01 01:22:52 +00008128 Type::TypeClass LHSClass = LHSCan->getTypeClass();
8129 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00008130
Chris Lattnerfd652912008-01-14 05:45:46 +00008131 // We want to consider the two function types to be the same for these
8132 // comparisons, just force one to the other.
8133 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
8134 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00008135
8136 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00008137 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
8138 LHSClass = Type::ConstantArray;
8139 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
8140 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00008141
John McCall8b07ec22010-05-15 11:32:37 +00008142 // ObjCInterfaces are just specialized ObjCObjects.
8143 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
8144 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
8145
Nate Begemance4d7fc2008-04-18 23:10:10 +00008146 // Canonicalize ExtVector -> Vector.
8147 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
8148 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00008149
Chris Lattner95554662008-04-07 05:43:21 +00008150 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008151 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00008152 // Note that we only have special rules for turning block enum
8153 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00008154 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008155 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008156 }
John McCall9dd450b2009-09-21 23:43:11 +00008157 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008158 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008159 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008160 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00008161 if (OfBlockPointer && !BlockReturnType) {
8162 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
8163 return LHS;
8164 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
8165 return RHS;
8166 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008167
Eli Friedman47f77112008-08-22 00:56:42 +00008168 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00008169 }
Eli Friedman47f77112008-08-22 00:56:42 +00008170
Steve Naroffc6edcbd2008-01-09 22:43:08 +00008171 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008172 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008173#define TYPE(Class, Base)
8174#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00008175#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008176#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
8177#define DEPENDENT_TYPE(Class, Base) case Type::Class:
8178#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00008179 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008180
Richard Smith27d807c2013-04-30 13:56:41 +00008181 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00008182 case Type::DeducedTemplateSpecialization:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008183 case Type::LValueReference:
8184 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008185 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00008186 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008187
John McCall8b07ec22010-05-15 11:32:37 +00008188 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008189 case Type::IncompleteArray:
8190 case Type::VariableArray:
8191 case Type::FunctionProto:
8192 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00008193 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008194
Chris Lattnerfd652912008-01-14 05:45:46 +00008195 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00008196 {
8197 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008198 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
8199 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008200 if (Unqualified) {
8201 LHSPointee = LHSPointee.getUnqualifiedType();
8202 RHSPointee = RHSPointee.getUnqualifiedType();
8203 }
8204 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
8205 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00008206 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00008207 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008208 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00008209 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008210 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008211 return getPointerType(ResultType);
8212 }
Steve Naroff68e167d2008-12-10 17:49:55 +00008213 case Type::BlockPointer:
8214 {
8215 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008216 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
8217 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008218 if (Unqualified) {
8219 LHSPointee = LHSPointee.getUnqualifiedType();
8220 RHSPointee = RHSPointee.getUnqualifiedType();
8221 }
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008222 if (getLangOpts().OpenCL) {
8223 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
8224 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
8225 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
8226 // 6.12.5) thus the following check is asymmetric.
8227 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
8228 return QualType();
8229 LHSPteeQual.removeAddressSpace();
8230 RHSPteeQual.removeAddressSpace();
8231 LHSPointee =
8232 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
8233 RHSPointee =
8234 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
8235 }
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008236 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
8237 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00008238 if (ResultType.isNull()) return QualType();
8239 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8240 return LHS;
8241 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8242 return RHS;
8243 return getBlockPointerType(ResultType);
8244 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00008245 case Type::Atomic:
8246 {
8247 // Merge two pointer types, while trying to preserve typedef info
8248 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
8249 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
8250 if (Unqualified) {
8251 LHSValue = LHSValue.getUnqualifiedType();
8252 RHSValue = RHSValue.getUnqualifiedType();
8253 }
8254 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
8255 Unqualified);
8256 if (ResultType.isNull()) return QualType();
8257 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
8258 return LHS;
8259 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
8260 return RHS;
8261 return getAtomicType(ResultType);
8262 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008263 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00008264 {
8265 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
8266 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
8267 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
8268 return QualType();
8269
8270 QualType LHSElem = getAsArrayType(LHS)->getElementType();
8271 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008272 if (Unqualified) {
8273 LHSElem = LHSElem.getUnqualifiedType();
8274 RHSElem = RHSElem.getUnqualifiedType();
8275 }
8276
8277 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00008278 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00008279 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8280 return LHS;
8281 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8282 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00008283 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
8284 ArrayType::ArraySizeModifier(), 0);
8285 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
8286 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008287 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
8288 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00008289 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8290 return LHS;
8291 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8292 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008293 if (LVAT) {
8294 // FIXME: This isn't correct! But tricky to implement because
8295 // the array's size has to be the size of LHS, but the type
8296 // has to be different.
8297 return LHS;
8298 }
8299 if (RVAT) {
8300 // FIXME: This isn't correct! But tricky to implement because
8301 // the array's size has to be the size of RHS, but the type
8302 // has to be different.
8303 return RHS;
8304 }
Eli Friedman3e62c212008-08-22 01:48:21 +00008305 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
8306 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00008307 return getIncompleteArrayType(ResultType,
8308 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008309 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008310 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008311 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008312 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008313 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00008314 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00008315 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008316 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00008317 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00008318 case Type::Complex:
8319 // Distinct complex types are incompatible.
8320 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008321 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00008322 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00008323 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
8324 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00008325 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00008326 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00008327 case Type::ObjCObject: {
8328 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00008329 // FIXME: This should be type compatibility, e.g. whether
8330 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00008331 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
8332 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
8333 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00008334 return LHS;
8335
Eli Friedman47f77112008-08-22 00:56:42 +00008336 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00008337 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00008338 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008339 if (OfBlockPointer) {
8340 if (canAssignObjCInterfacesInBlockPointer(
8341 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008342 RHS->getAs<ObjCObjectPointerType>(),
8343 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00008344 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008345 return QualType();
8346 }
John McCall9dd450b2009-09-21 23:43:11 +00008347 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
8348 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00008349 return LHS;
8350
Steve Naroffc68cfcf2008-12-10 22:14:21 +00008351 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00008352 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00008353 case Type::Pipe:
8354 {
Joey Goulye3c85de2016-12-01 11:30:49 +00008355 assert(LHS != RHS &&
8356 "Equivalent pipe types should have already been handled!");
8357 return QualType();
Xiuli Pan9c14e282016-01-09 12:53:17 +00008358 }
Steve Naroff32e44c02007-10-15 20:41:53 +00008359 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008360
David Blaikie8a40f702012-01-17 06:56:22 +00008361 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00008362}
Ted Kremenekfc581a92007-10-31 17:10:13 +00008363
John McCall18afab72016-03-01 00:49:02 +00008364bool ASTContext::doFunctionTypesMatchOnExtParameterInfos(
8365 const FunctionProtoType *firstFnType,
8366 const FunctionProtoType *secondFnType) {
8367 // Fast path: if the first type doesn't have ext parameter infos,
8368 // we match if and only if they second type also doesn't have them.
8369 if (!firstFnType->hasExtParameterInfos())
8370 return !secondFnType->hasExtParameterInfos();
8371
8372 // Otherwise, we can only match if the second type has them.
8373 if (!secondFnType->hasExtParameterInfos())
Fariborz Jahanian97676972011-09-28 21:52:05 +00008374 return false;
John McCall18afab72016-03-01 00:49:02 +00008375
8376 auto firstEPI = firstFnType->getExtParameterInfos();
8377 auto secondEPI = secondFnType->getExtParameterInfos();
8378 assert(firstEPI.size() == secondEPI.size());
8379
8380 for (size_t i = 0, n = firstEPI.size(); i != n; ++i) {
8381 if (firstEPI[i] != secondEPI[i])
8382 return false;
8383 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00008384 return true;
8385}
8386
Chandler Carruth21c90602015-12-30 03:24:14 +00008387void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
8388 ObjCLayouts[CD] = nullptr;
8389}
8390
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008391/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
8392/// 'RHS' attributes and returns the merged version; including for function
8393/// return types.
8394QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
8395 QualType LHSCan = getCanonicalType(LHS),
8396 RHSCan = getCanonicalType(RHS);
8397 // If two types are identical, they are compatible.
8398 if (LHSCan == RHSCan)
8399 return LHS;
8400 if (RHSCan->isFunctionType()) {
8401 if (!LHSCan->isFunctionType())
8402 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00008403 QualType OldReturnType =
8404 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008405 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00008406 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008407 QualType ResReturnType =
8408 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
8409 if (ResReturnType.isNull())
8410 return QualType();
8411 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
8412 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
8413 // In either case, use OldReturnType to build the new function type.
8414 const FunctionType *F = LHS->getAs<FunctionType>();
8415 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008416 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8417 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00008418 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00008419 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008420 return ResultType;
8421 }
8422 }
8423 return QualType();
8424 }
8425
8426 // If the qualifiers are different, the types can still be merged.
8427 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8428 Qualifiers RQuals = RHSCan.getLocalQualifiers();
8429 if (LQuals != RQuals) {
8430 // If any of these qualifiers are different, we have a type mismatch.
8431 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
8432 LQuals.getAddressSpace() != RQuals.getAddressSpace())
8433 return QualType();
8434
8435 // Exactly one GC qualifier difference is allowed: __strong is
8436 // okay if the other type has no GC qualifier but is an Objective
8437 // C object pointer (i.e. implicitly strong by default). We fix
8438 // this by pretending that the unqualified type was actually
8439 // qualified __strong.
8440 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8441 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8442 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8443
8444 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8445 return QualType();
8446
8447 if (GC_L == Qualifiers::Strong)
8448 return LHS;
8449 if (GC_R == Qualifiers::Strong)
8450 return RHS;
8451 return QualType();
8452 }
8453
8454 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
8455 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8456 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8457 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
8458 if (ResQT == LHSBaseQT)
8459 return LHS;
8460 if (ResQT == RHSBaseQT)
8461 return RHS;
8462 }
8463 return QualType();
8464}
8465
Chris Lattner4ba0cef2008-04-07 07:01:58 +00008466//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008467// Integer Predicates
8468//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00008469
Jay Foad39c79802011-01-12 09:06:06 +00008470unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00008471 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00008472 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00008473 if (T->isBooleanType())
8474 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00008475 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008476 return (unsigned)getTypeSize(T);
8477}
8478
Abramo Bagnara13640492012-09-09 10:21:24 +00008479QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00008480 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00008481
8482 // Turn <4 x signed int> -> <4 x unsigned int>
8483 if (const VectorType *VTy = T->getAs<VectorType>())
8484 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00008485 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00008486
8487 // For enums, we return the unsigned version of the base type.
8488 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008489 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00008490
8491 const BuiltinType *BTy = T->getAs<BuiltinType>();
8492 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008493 switch (BTy->getKind()) {
8494 case BuiltinType::Char_S:
8495 case BuiltinType::SChar:
8496 return UnsignedCharTy;
8497 case BuiltinType::Short:
8498 return UnsignedShortTy;
8499 case BuiltinType::Int:
8500 return UnsignedIntTy;
8501 case BuiltinType::Long:
8502 return UnsignedLongTy;
8503 case BuiltinType::LongLong:
8504 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00008505 case BuiltinType::Int128:
8506 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008507 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008508 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008509 }
8510}
8511
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00008512ASTMutationListener::~ASTMutationListener() { }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00008513
Richard Smith1fa5d642013-05-11 05:45:24 +00008514void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
8515 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00008516
8517//===----------------------------------------------------------------------===//
8518// Builtin Type Computation
8519//===----------------------------------------------------------------------===//
8520
8521/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00008522/// pointer over the consumed characters. This returns the resultant type. If
8523/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
8524/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
8525/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008526///
8527/// RequiresICE is filled in on return to indicate whether the value is required
8528/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00008529static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00008530 ASTContext::GetBuiltinTypeError &Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00008531 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00008532 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00008533 // Modifiers.
8534 int HowLong = 0;
8535 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008536 RequiresICE = false;
Chandler Carruth45bbe012017-03-24 09:11:57 +00008537
Chris Lattnerdc226c22010-10-01 22:42:38 +00008538 // Read the prefixed modifiers first.
Eric Christopher50daf5f2017-07-10 21:28:54 +00008539 bool Done = false;
8540 #ifndef NDEBUG
8541 bool IsSpecialLong = false;
8542 #endif
Chris Lattnerecd79c62009-06-14 00:45:47 +00008543 while (!Done) {
8544 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00008545 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00008546 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008547 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00008548 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008549 case 'S':
8550 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
8551 assert(!Signed && "Can't use 'S' modifier multiple times!");
8552 Signed = true;
8553 break;
8554 case 'U':
8555 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00008556 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008557 Unsigned = true;
8558 break;
8559 case 'L':
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008560 assert(!IsSpecialLong && "Can't use 'L' with 'W' or 'N' modifiers");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008561 assert(HowLong <= 2 && "Can't have LLLL modifier");
8562 ++HowLong;
8563 break;
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008564 case 'N': {
8565 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
8566 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
8567 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00008568 #ifndef NDEBUG
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008569 IsSpecialLong = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00008570 #endif
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008571 if (Context.getTargetInfo().getLongWidth() == 32)
8572 ++HowLong;
8573 break;
8574 }
Kevin Qinad64f6d2014-02-24 02:45:03 +00008575 case 'W':
8576 // This modifier represents int64 type.
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008577 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
Kevin Qinad64f6d2014-02-24 02:45:03 +00008578 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00008579 #ifndef NDEBUG
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008580 IsSpecialLong = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00008581 #endif
Kevin Qinad64f6d2014-02-24 02:45:03 +00008582 switch (Context.getTargetInfo().getInt64Type()) {
8583 default:
8584 llvm_unreachable("Unexpected integer type");
8585 case TargetInfo::SignedLong:
8586 HowLong = 1;
8587 break;
8588 case TargetInfo::SignedLongLong:
8589 HowLong = 2;
8590 break;
8591 }
Duncan P. N. Exon Smitheae8caa2017-06-14 21:26:31 +00008592 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008593 }
8594 }
8595
8596 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00008597
Chris Lattnerecd79c62009-06-14 00:45:47 +00008598 // Read the base type.
8599 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00008600 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008601 case 'v':
8602 assert(HowLong == 0 && !Signed && !Unsigned &&
8603 "Bad modifiers used with 'v'!");
8604 Type = Context.VoidTy;
8605 break;
Jack Carter24bef982013-08-15 15:16:57 +00008606 case 'h':
8607 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00008608 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00008609 Type = Context.HalfTy;
8610 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008611 case 'f':
8612 assert(HowLong == 0 && !Signed && !Unsigned &&
8613 "Bad modifiers used with 'f'!");
8614 Type = Context.FloatTy;
8615 break;
8616 case 'd':
8617 assert(HowLong < 2 && !Signed && !Unsigned &&
8618 "Bad modifiers used with 'd'!");
8619 if (HowLong)
8620 Type = Context.LongDoubleTy;
8621 else
8622 Type = Context.DoubleTy;
8623 break;
8624 case 's':
8625 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8626 if (Unsigned)
8627 Type = Context.UnsignedShortTy;
8628 else
8629 Type = Context.ShortTy;
8630 break;
8631 case 'i':
8632 if (HowLong == 3)
8633 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8634 else if (HowLong == 2)
8635 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8636 else if (HowLong == 1)
8637 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8638 else
8639 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8640 break;
8641 case 'c':
8642 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8643 if (Signed)
8644 Type = Context.SignedCharTy;
8645 else if (Unsigned)
8646 Type = Context.UnsignedCharTy;
8647 else
8648 Type = Context.CharTy;
8649 break;
8650 case 'b': // boolean
8651 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8652 Type = Context.BoolTy;
8653 break;
8654 case 'z': // size_t.
8655 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8656 Type = Context.getSizeType();
8657 break;
Richard Smith8110c9d2016-11-29 19:45:17 +00008658 case 'w': // wchar_t.
8659 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
8660 Type = Context.getWideCharType();
8661 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008662 case 'F':
8663 Type = Context.getCFConstantStringType();
8664 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00008665 case 'G':
8666 Type = Context.getObjCIdType();
8667 break;
8668 case 'H':
8669 Type = Context.getObjCSelType();
8670 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00008671 case 'M':
8672 Type = Context.getObjCSuperType();
8673 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008674 case 'a':
8675 Type = Context.getBuiltinVaListType();
8676 assert(!Type.isNull() && "builtin va list type not initialized!");
8677 break;
8678 case 'A':
8679 // This is a "reference" to a va_list; however, what exactly
8680 // this means depends on how va_list is defined. There are two
8681 // different kinds of va_list: ones passed by value, and ones
8682 // passed by reference. An example of a by-value va_list is
8683 // x86, where va_list is a char*. An example of by-ref va_list
8684 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8685 // we want this argument to be a char*&; for x86-64, we want
8686 // it to be a __va_list_tag*.
8687 Type = Context.getBuiltinVaListType();
8688 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008689 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00008690 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008691 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00008692 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008693 break;
8694 case 'V': {
8695 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008696 unsigned NumElements = strtoul(Str, &End, 10);
8697 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008698 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00008699
Chandler Carruth45bbe012017-03-24 09:11:57 +00008700 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8701 RequiresICE, false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008702 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00008703
8704 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00008705 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00008706 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008707 break;
8708 }
Douglas Gregorfed66992012-06-07 18:08:25 +00008709 case 'E': {
8710 char *End;
8711
8712 unsigned NumElements = strtoul(Str, &End, 10);
8713 assert(End != Str && "Missing vector size");
8714
8715 Str = End;
Chandler Carruth45bbe012017-03-24 09:11:57 +00008716
Douglas Gregorfed66992012-06-07 18:08:25 +00008717 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00008718 false);
Douglas Gregorfed66992012-06-07 18:08:25 +00008719 Type = Context.getExtVectorType(ElementType, NumElements);
8720 break;
8721 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008722 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008723 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00008724 false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008725 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008726 Type = Context.getComplexType(ElementType);
8727 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00008728 }
8729 case 'Y' : {
8730 Type = Context.getPointerDiffType();
8731 break;
8732 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00008733 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00008734 Type = Context.getFILEType();
8735 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008736 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008737 return QualType();
8738 }
Mike Stump2adb4da2009-07-28 23:47:15 +00008739 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00008740 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00008741 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00008742 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00008743 else
8744 Type = Context.getjmp_bufType();
8745
Mike Stump2adb4da2009-07-28 23:47:15 +00008746 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008747 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00008748 return QualType();
8749 }
8750 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00008751 case 'K':
8752 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8753 Type = Context.getucontext_tType();
8754
8755 if (Type.isNull()) {
8756 Error = ASTContext::GE_Missing_ucontext;
8757 return QualType();
8758 }
8759 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00008760 case 'p':
8761 Type = Context.getProcessIDType();
8762 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00008763 }
Mike Stump11289f42009-09-09 15:08:12 +00008764
Chris Lattnerdc226c22010-10-01 22:42:38 +00008765 // If there are modifiers and if we're allowed to parse them, go for it.
8766 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008767 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00008768 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00008769 default: Done = true; --Str; break;
8770 case '*':
8771 case '&': {
8772 // Both pointers and references can have their pointee types
8773 // qualified with an address space.
8774 char *End;
8775 unsigned AddrSpace = strtoul(Str, &End, 10);
8776 if (End != Str && AddrSpace != 0) {
Yaxun Liu6d96f1632017-05-18 18:51:09 +00008777 Type = Context.getAddrSpaceQualType(
8778 Type, AddrSpace + LangAS::FirstTargetAddressSpace);
Chris Lattnerdc226c22010-10-01 22:42:38 +00008779 Str = End;
8780 }
8781 if (c == '*')
8782 Type = Context.getPointerType(Type);
8783 else
8784 Type = Context.getLValueReferenceType(Type);
8785 break;
8786 }
8787 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8788 case 'C':
8789 Type = Type.withConst();
8790 break;
8791 case 'D':
8792 Type = Context.getVolatileType(Type);
8793 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00008794 case 'R':
8795 Type = Type.withRestrict();
8796 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008797 }
8798 }
Chris Lattner84733392010-10-01 07:13:18 +00008799
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008800 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00008801 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00008802
Chris Lattnerecd79c62009-06-14 00:45:47 +00008803 return Type;
8804}
8805
8806/// GetBuiltinType - Return the type for the specified builtin.
Chandler Carruth45bbe012017-03-24 09:11:57 +00008807QualType ASTContext::GetBuiltinType(unsigned Id,
8808 GetBuiltinTypeError &Error,
8809 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00008810 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00008811
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008812 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00008813
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008814 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008815 Error = GE_None;
Chandler Carruth45bbe012017-03-24 09:11:57 +00008816 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8817 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008818 if (Error != GE_None)
8819 return QualType();
Chandler Carruth45bbe012017-03-24 09:11:57 +00008820
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008821 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
Chandler Carruth45bbe012017-03-24 09:11:57 +00008822
Chris Lattnerecd79c62009-06-14 00:45:47 +00008823 while (TypeStr[0] && TypeStr[0] != '.') {
Chandler Carruth45bbe012017-03-24 09:11:57 +00008824 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008825 if (Error != GE_None)
8826 return QualType();
8827
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008828 // If this argument is required to be an IntegerConstantExpression and the
8829 // caller cares, fill in the bitmask we return.
8830 if (RequiresICE && IntegerConstantArgs)
8831 *IntegerConstantArgs |= 1 << ArgTypes.size();
8832
Chris Lattnerecd79c62009-06-14 00:45:47 +00008833 // Do array -> pointer decay. The builtin should use the decayed type.
8834 if (Ty->isArrayType())
8835 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00008836
Chris Lattnerecd79c62009-06-14 00:45:47 +00008837 ArgTypes.push_back(Ty);
8838 }
8839
David Majnemerba3e5ec2015-03-13 18:26:17 +00008840 if (Id == Builtin::BI__GetExceptionInfo)
8841 return QualType();
8842
Chris Lattnerecd79c62009-06-14 00:45:47 +00008843 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8844 "'.' should only occur at end of builtin type list!");
8845
Reid Kleckner78af0702013-08-27 23:08:25 +00008846 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00008847 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8848
8849 bool Variadic = (TypeStr[0] == '.');
8850
Richard Smith836de6b2016-12-19 23:59:34 +00008851 // We really shouldn't be making a no-proto type here.
8852 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
John McCall991eb4b2010-12-21 00:44:39 +00008853 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00008854
John McCalldb40c7f2010-12-14 08:05:40 +00008855 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00008856 EPI.ExtInfo = EI;
8857 EPI.Variadic = Variadic;
Richard Smith391fb862016-10-18 07:13:55 +00008858 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
8859 EPI.ExceptionSpec.Type =
8860 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00008861
Jordan Rose5c382722013-03-08 21:51:21 +00008862 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008863}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00008864
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008865static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8866 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008867 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008868 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008869
Yaron Keren4cd211b2017-02-22 14:32:39 +00008870 GVALinkage External;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008871 switch (FD->getTemplateSpecializationKind()) {
8872 case TSK_Undeclared:
8873 case TSK_ExplicitSpecialization:
8874 External = GVA_StrongExternal;
8875 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008876
Rafael Espindola3ae00052013-05-13 00:12:11 +00008877 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008878 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008879
David Majnemerc3d07332014-05-15 06:25:57 +00008880 // C++11 [temp.explicit]p10:
8881 // [ Note: The intent is that an inline function that is the subject of
8882 // an explicit instantiation declaration will still be implicitly
8883 // instantiated when used so that the body can be considered for
8884 // inlining, but that no out-of-line copy of the inline function would be
8885 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00008886 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00008887 return GVA_AvailableExternally;
8888
Rafael Espindola3ae00052013-05-13 00:12:11 +00008889 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008890 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008891 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008892 }
8893
8894 if (!FD->isInlined())
8895 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00008896
David Majnemer3f021502015-10-08 04:53:31 +00008897 if ((!Context.getLangOpts().CPlusPlus &&
8898 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008899 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00008900 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008901 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8902
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008903 // GNU or C99 inline semantics. Determine whether this symbol should be
8904 // externally visible.
8905 if (FD->isInlineDefinitionExternallyVisible())
8906 return External;
8907
8908 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00008909 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008910 }
8911
David Majnemer54e3ba52014-04-02 23:17:29 +00008912 // Functions specified with extern and inline in -fms-compatibility mode
8913 // forcibly get emitted. While the body of the function cannot be later
8914 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00008915 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00008916 return GVA_StrongODR;
8917
David Majnemer27d69db2014-04-28 22:17:59 +00008918 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008919}
8920
Artem Belevichca2b9512016-05-02 20:30:03 +00008921static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
8922 GVALinkage L, const Decl *D) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008923 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8924 // dllexport/dllimport on inline functions.
8925 if (D->hasAttr<DLLImportAttr>()) {
8926 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8927 return GVA_AvailableExternally;
Artem Belevichca2b9512016-05-02 20:30:03 +00008928 } else if (D->hasAttr<DLLExportAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008929 if (L == GVA_DiscardableODR)
8930 return GVA_StrongODR;
Artem Belevichca2b9512016-05-02 20:30:03 +00008931 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
8932 D->hasAttr<CUDAGlobalAttr>()) {
8933 // Device-side functions with __global__ attribute must always be
8934 // visible externally so they can be launched from host.
8935 if (L == GVA_DiscardableODR || L == GVA_Internal)
8936 return GVA_StrongODR;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008937 }
8938 return L;
8939}
8940
8941GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
David Blaikie9ffe5a32017-01-30 05:00:26 +00008942 auto L = adjustGVALinkageForAttributes(
Artem Belevichca2b9512016-05-02 20:30:03 +00008943 *this, basicGVALinkageForFunction(*this, FD), FD);
David Blaikie9ffe5a32017-01-30 05:00:26 +00008944 auto EK = ExternalASTSource::EK_ReplyHazy;
8945 if (auto *Ext = getExternalSource())
David Blaikiee6b7c282017-04-11 20:46:34 +00008946 EK = Ext->hasExternalDefinitions(FD);
David Blaikie9ffe5a32017-01-30 05:00:26 +00008947 switch (EK) {
8948 case ExternalASTSource::EK_Never:
8949 if (L == GVA_DiscardableODR)
8950 return GVA_StrongODR;
8951 break;
8952 case ExternalASTSource::EK_Always:
8953 return GVA_AvailableExternally;
8954 case ExternalASTSource::EK_ReplyHazy:
8955 break;
8956 }
8957 return L;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008958}
8959
8960static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8961 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008962 if (!VD->isExternallyVisible())
8963 return GVA_Internal;
8964
David Majnemer27d69db2014-04-28 22:17:59 +00008965 if (VD->isStaticLocal()) {
David Majnemer27d69db2014-04-28 22:17:59 +00008966 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8967 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8968 LexicalContext = LexicalContext->getLexicalParent();
8969
David Blaikieeb210012017-01-27 23:11:10 +00008970 // ObjC Blocks can create local variables that don't have a FunctionDecl
8971 // LexicalContext.
8972 if (!LexicalContext)
8973 return GVA_DiscardableODR;
David Majnemer27d69db2014-04-28 22:17:59 +00008974
David Blaikieeb210012017-01-27 23:11:10 +00008975 // Otherwise, let the static local variable inherit its linkage from the
8976 // nearest enclosing function.
8977 auto StaticLocalLinkage =
8978 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
8979
8980 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
8981 // be emitted in any object with references to the symbol for the object it
8982 // contains, whether inline or out-of-line."
8983 // Similar behavior is observed with MSVC. An alternative ABI could use
8984 // StrongODR/AvailableExternally to match the function, but none are
8985 // known/supported currently.
8986 if (StaticLocalLinkage == GVA_StrongODR ||
8987 StaticLocalLinkage == GVA_AvailableExternally)
8988 return GVA_DiscardableODR;
8989 return StaticLocalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00008990 }
8991
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008992 // MSVC treats in-class initialized static data members as definitions.
8993 // By giving them non-strong linkage, out-of-line definitions won't
8994 // cause link errors.
8995 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8996 return GVA_DiscardableODR;
8997
Richard Smithd9b90092016-07-02 01:32:16 +00008998 // Most non-template variables have strong linkage; inline variables are
8999 // linkonce_odr or (occasionally, for compatibility) weak_odr.
9000 GVALinkage StrongLinkage;
9001 switch (Context.getInlineVariableDefinitionKind(VD)) {
9002 case ASTContext::InlineVariableDefinitionKind::None:
9003 StrongLinkage = GVA_StrongExternal;
9004 break;
9005 case ASTContext::InlineVariableDefinitionKind::Weak:
9006 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
Richard Smith62f19e72016-06-25 00:15:56 +00009007 StrongLinkage = GVA_DiscardableODR;
Richard Smithd9b90092016-07-02 01:32:16 +00009008 break;
9009 case ASTContext::InlineVariableDefinitionKind::Strong:
9010 StrongLinkage = GVA_StrongODR;
9011 break;
9012 }
Richard Smith62f19e72016-06-25 00:15:56 +00009013
Richard Smith8809a0c2013-09-27 20:14:12 +00009014 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009015 case TSK_Undeclared:
Richard Smith62f19e72016-06-25 00:15:56 +00009016 return StrongLinkage;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009017
David Majnemer6d1780c2015-07-17 23:36:49 +00009018 case TSK_ExplicitSpecialization:
David Majnemer3f021502015-10-08 04:53:31 +00009019 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9020 VD->isStaticDataMember()
David Majnemer6d1780c2015-07-17 23:36:49 +00009021 ? GVA_StrongODR
Richard Smith62f19e72016-06-25 00:15:56 +00009022 : StrongLinkage;
David Majnemer6d1780c2015-07-17 23:36:49 +00009023
Rafael Espindola3ae00052013-05-13 00:12:11 +00009024 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009025 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009026
David Majnemer27d69db2014-04-28 22:17:59 +00009027 case TSK_ExplicitInstantiationDeclaration:
9028 return GVA_AvailableExternally;
9029
Rafael Espindola3ae00052013-05-13 00:12:11 +00009030 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009031 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009032 }
Rafael Espindola27699c82013-05-13 14:05:53 +00009033
9034 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009035}
9036
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009037GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Artem Belevichca2b9512016-05-02 20:30:03 +00009038 return adjustGVALinkageForAttributes(
9039 *this, basicGVALinkageForVariable(*this, VD), VD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009040}
9041
David Blaikiee6b7c282017-04-11 20:46:34 +00009042bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009043 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
9044 if (!VD->isFileVarDecl())
9045 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00009046 // Global named register variables (GNU extension) are never emitted.
9047 if (VD->getStorageClass() == SC_Register)
9048 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00009049 if (VD->getDescribedVarTemplate() ||
9050 isa<VarTemplatePartialSpecializationDecl>(VD))
9051 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00009052 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9053 // We never need to emit an uninstantiated function template.
9054 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9055 return false;
Nico Weber66220292016-03-02 17:28:48 +00009056 } else if (isa<PragmaCommentDecl>(D))
9057 return true;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00009058 else if (isa<OMPThreadPrivateDecl>(D) ||
9059 D->hasAttr<OMPDeclareTargetDeclAttr>())
9060 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +00009061 else if (isa<PragmaDetectMismatchDecl>(D))
9062 return true;
Nico Weber66220292016-03-02 17:28:48 +00009063 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00009064 return !D->getDeclContext()->isDependentContext();
9065 else if (isa<OMPDeclareReductionDecl>(D))
9066 return !D->getDeclContext()->isDependentContext();
Richard Smithdc1f0422016-07-20 19:10:16 +00009067 else if (isa<ImportDecl>(D))
9068 return true;
Alexey Bataev97720002014-11-11 04:05:39 +00009069 else
Richard Smith5205a8c2013-04-01 20:22:16 +00009070 return false;
9071
9072 // If this is a member of a class template, we do not need to emit it.
9073 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009074 return false;
9075
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009076 // Weak references don't produce any output by themselves.
9077 if (D->hasAttr<WeakRefAttr>())
9078 return false;
9079
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009080 // Aliases and used decls are required.
9081 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
9082 return true;
9083
9084 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9085 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00009086 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00009087 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009088
9089 // Constructors and destructors are required.
9090 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
9091 return true;
9092
John McCall6bd2a892013-01-25 22:31:03 +00009093 // The key function for a class is required. This rule only comes
9094 // into play when inline functions can be key functions, though.
9095 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
9096 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9097 const CXXRecordDecl *RD = MD->getParent();
9098 if (MD->isOutOfLine() && RD->isDynamicClass()) {
9099 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
9100 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
9101 return true;
9102 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009103 }
9104 }
9105
David Blaikie9ffe5a32017-01-30 05:00:26 +00009106 GVALinkage Linkage = GetGVALinkageForFunction(FD);
9107
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009108 // static, static inline, always_inline, and extern inline functions can
9109 // always be deferred. Normal inline functions can be deferred in C99/C++.
9110 // Implicit template instantiations can also be deferred in C++.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009111 return !isDiscardableGVALinkage(Linkage);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009112 }
Douglas Gregor87d81242011-09-10 00:22:34 +00009113
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009114 const VarDecl *VD = cast<VarDecl>(D);
9115 assert(VD->isFileVarDecl() && "Expected file scoped var");
9116
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009117 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
9118 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009119 return false;
9120
Richard Smitha0e5e542012-11-12 21:38:00 +00009121 // Variables that can be needed in other TUs are required.
Justin Lebar606f01f2016-10-13 20:52:17 +00009122 if (!isDiscardableGVALinkage(GetGVALinkageForVariable(VD)))
Richard Smitha0e5e542012-11-12 21:38:00 +00009123 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009124
Richard Smitha0e5e542012-11-12 21:38:00 +00009125 // Variables that have destruction with side-effects are required.
9126 if (VD->getType().isDestructedType())
9127 return true;
9128
9129 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00009130 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
Richard Smith187ffb42017-01-20 01:19:46 +00009131 // We can get a value-dependent initializer during error recovery.
9132 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
Richard Smitha0e5e542012-11-12 21:38:00 +00009133 return true;
9134
Richard Smithda383632016-08-15 01:33:41 +00009135 // Likewise, variables with tuple-like bindings are required if their
9136 // bindings have side-effects.
9137 if (auto *DD = dyn_cast<DecompositionDecl>(VD))
9138 for (auto *BD : DD->bindings())
9139 if (auto *BindingVD = BD->getHoldingVar())
9140 if (DeclMustBeEmitted(BindingVD))
9141 return true;
9142
Richard Smitha0e5e542012-11-12 21:38:00 +00009143 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009144}
Charles Davis53c59df2010-08-16 03:33:14 +00009145
Reid Kleckner78af0702013-08-27 23:08:25 +00009146CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
9147 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00009148 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00009149 if (IsCXXMethod)
9150 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00009151
Alexey Bataeva7547182016-05-18 09:06:38 +00009152 switch (LangOpts.getDefaultCallingConv()) {
9153 case LangOptions::DCC_None:
9154 break;
9155 case LangOptions::DCC_CDecl:
9156 return CC_C;
9157 case LangOptions::DCC_FastCall:
9158 if (getTargetInfo().hasFeature("sse2"))
9159 return CC_X86FastCall;
9160 break;
9161 case LangOptions::DCC_StdCall:
9162 if (!IsVariadic)
9163 return CC_X86StdCall;
9164 break;
9165 case LangOptions::DCC_VectorCall:
9166 // __vectorcall cannot be applied to variadic functions.
9167 if (!IsVariadic)
9168 return CC_X86VectorCall;
9169 break;
9170 }
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00009171 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00009172}
9173
Jay Foad39c79802011-01-12 09:06:06 +00009174bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00009175 // Pass through to the C++ ABI object
9176 return ABI->isNearlyEmpty(RD);
9177}
9178
Reid Kleckner96f8f932014-02-05 17:27:08 +00009179VTableContextBase *ASTContext::getVTableContext() {
9180 if (!VTContext.get()) {
9181 if (Target->getCXXABI().isMicrosoft())
9182 VTContext.reset(new MicrosoftVTableContext(*this));
9183 else
9184 VTContext.reset(new ItaniumVTableContext(*this));
9185 }
9186 return VTContext.get();
9187}
9188
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009189MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00009190 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00009191 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00009192 case TargetCXXABI::GenericItanium:
9193 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00009194 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00009195 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00009196 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00009197 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +00009198 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009199 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00009200 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009201 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009202 }
David Blaikie83d382b2011-09-23 05:06:16 +00009203 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009204}
9205
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00009206CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00009207
9208size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00009209 return ASTRecordLayouts.getMemorySize() +
9210 llvm::capacity_in_bytes(ObjCLayouts) +
9211 llvm::capacity_in_bytes(KeyFunctions) +
9212 llvm::capacity_in_bytes(ObjCImpls) +
9213 llvm::capacity_in_bytes(BlockVarCopyInits) +
9214 llvm::capacity_in_bytes(DeclAttrs) +
9215 llvm::capacity_in_bytes(TemplateOrInstantiation) +
9216 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
9217 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
9218 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
9219 llvm::capacity_in_bytes(OverriddenMethods) +
9220 llvm::capacity_in_bytes(Types) +
9221 llvm::capacity_in_bytes(VariableArrayTypes) +
9222 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00009223}
Ted Kremenek540017e2011-10-06 05:00:56 +00009224
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009225/// getIntTypeForBitwidth -
9226/// sets integer QualTy according to specified details:
9227/// bitwidth, signed/unsigned.
9228/// Returns empty type if there is no appropriate target types.
9229QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
9230 unsigned Signed) const {
9231 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
9232 CanQualType QualTy = getFromTargetType(Ty);
9233 if (!QualTy && DestWidth == 128)
9234 return Signed ? Int128Ty : UnsignedInt128Ty;
9235 return QualTy;
9236}
9237
9238/// getRealTypeForBitwidth -
9239/// sets floating point QualTy according to specified bitwidth.
9240/// Returns empty type if there is no appropriate target types.
9241QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
9242 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
9243 switch (Ty) {
9244 case TargetInfo::Float:
9245 return FloatTy;
9246 case TargetInfo::Double:
9247 return DoubleTy;
9248 case TargetInfo::LongDouble:
9249 return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00009250 case TargetInfo::Float128:
9251 return Float128Ty;
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009252 case TargetInfo::NoFloat:
9253 return QualType();
9254 }
9255
9256 llvm_unreachable("Unhandled TargetInfo::RealType value");
9257}
9258
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009259void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
9260 if (Number > 1)
9261 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00009262}
9263
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009264unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00009265 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009266 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00009267}
9268
David Majnemer2206bf52014-03-05 08:57:59 +00009269void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
9270 if (Number > 1)
9271 StaticLocalNumbers[VD] = Number;
9272}
9273
9274unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00009275 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +00009276 return I != StaticLocalNumbers.end() ? I->second : 1;
9277}
9278
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009279MangleNumberingContext &
9280ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00009281 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
Justin Lebar20ebffc2016-10-10 16:26:19 +00009282 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
Reid Klecknerd8110b62013-09-10 20:14:30 +00009283 if (!MCtx)
9284 MCtx = createMangleNumberingContext();
9285 return *MCtx;
9286}
9287
Justin Lebar20ebffc2016-10-10 16:26:19 +00009288std::unique_ptr<MangleNumberingContext>
9289ASTContext::createMangleNumberingContext() const {
Reid Klecknerd8110b62013-09-10 20:14:30 +00009290 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00009291}
9292
David Majnemere7a818f2015-03-06 18:53:55 +00009293const CXXConstructorDecl *
9294ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
9295 return ABI->getCopyConstructorForExceptionObject(
9296 cast<CXXRecordDecl>(RD->getFirstDecl()));
9297}
9298
9299void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
9300 CXXConstructorDecl *CD) {
9301 return ABI->addCopyConstructorForExceptionObject(
9302 cast<CXXRecordDecl>(RD->getFirstDecl()),
9303 cast<CXXConstructorDecl>(CD->getFirstDecl()));
9304}
9305
David Majnemer00350522015-08-31 18:48:39 +00009306void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
9307 TypedefNameDecl *DD) {
9308 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
9309}
9310
9311TypedefNameDecl *
9312ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
9313 return ABI->getTypedefNameForUnnamedTagDecl(TD);
9314}
9315
9316void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
9317 DeclaratorDecl *DD) {
9318 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
9319}
9320
9321DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
9322 return ABI->getDeclaratorForUnnamedTagDecl(TD);
9323}
9324
Ted Kremenek540017e2011-10-06 05:00:56 +00009325void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
9326 ParamIndices[D] = index;
9327}
9328
9329unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
9330 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
9331 assert(I != ParamIndices.end() &&
9332 "ParmIndices lacks entry set by ParmVarDecl");
9333 return I->second;
9334}
Fariborz Jahanian615de762013-05-28 17:37:39 +00009335
Richard Smithe6c01442013-06-05 00:46:14 +00009336APValue *
9337ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
9338 bool MayCreate) {
9339 assert(E && E->getStorageDuration() == SD_Static &&
9340 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +00009341 if (MayCreate) {
9342 APValue *&MTVI = MaterializedTemporaryValues[E];
9343 if (!MTVI)
9344 MTVI = new (*this) APValue;
9345 return MTVI;
9346 }
Richard Smithe6c01442013-06-05 00:46:14 +00009347
David Majnemer2dcef9e2015-08-13 23:50:15 +00009348 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +00009349}
9350
Fariborz Jahanian615de762013-05-28 17:37:39 +00009351bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
9352 const llvm::Triple &T = getTargetInfo().getTriple();
9353 if (!T.isOSDarwin())
9354 return false;
9355
Bob Wilson2c82c3d2013-11-02 23:27:49 +00009356 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
9357 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
9358 return false;
9359
Fariborz Jahanian615de762013-05-28 17:37:39 +00009360 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
9361 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
9362 uint64_t Size = sizeChars.getQuantity();
9363 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
9364 unsigned Align = alignChars.getQuantity();
9365 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
9366 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
9367}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009368
9369namespace {
9370
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009371ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
9372 ASTContext::ParentMapPointers::mapped_type U) {
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009373 if (const auto *D = U.dyn_cast<const Decl *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009374 return ast_type_traits::DynTypedNode::create(*D);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009375 if (const auto *S = U.dyn_cast<const Stmt *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009376 return ast_type_traits::DynTypedNode::create(*S);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009377 return *U.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009378}
9379
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009380/// Template specializations to abstract away from pointers and TypeLocs.
9381/// @{
9382template <typename T>
9383ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
9384 return ast_type_traits::DynTypedNode::create(*Node);
9385}
9386template <>
9387ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
9388 return ast_type_traits::DynTypedNode::create(Node);
9389}
9390template <>
9391ast_type_traits::DynTypedNode
9392createDynTypedNode(const NestedNameSpecifierLoc &Node) {
9393 return ast_type_traits::DynTypedNode::create(Node);
9394}
9395/// @}
9396
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009397 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
9398 /// parents as defined by the \c RecursiveASTVisitor.
9399 ///
9400 /// Note that the relationship described here is purely in terms of AST
9401 /// traversal - there are other relationships (for example declaration context)
9402 /// in the AST that are better modeled by special matchers.
9403 ///
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00009404 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009405 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009406 public:
9407 /// \brief Builds and returns the translation unit's parent map.
9408 ///
9409 /// The caller takes ownership of the returned \c ParentMap.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009410 static std::pair<ASTContext::ParentMapPointers *,
9411 ASTContext::ParentMapOtherNodes *>
9412 buildMap(TranslationUnitDecl &TU) {
9413 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
9414 new ASTContext::ParentMapOtherNodes);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009415 Visitor.TraverseDecl(&TU);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009416 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009417 }
9418
9419 private:
9420 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
9421
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009422 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
9423 ASTContext::ParentMapOtherNodes *OtherParents)
9424 : Parents(Parents), OtherParents(OtherParents) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009425
9426 bool shouldVisitTemplateInstantiations() const {
9427 return true;
9428 }
9429 bool shouldVisitImplicitCode() const {
9430 return true;
9431 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009432
Richard Smith85838722015-11-24 03:09:01 +00009433 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
9434 typename MapTy>
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009435 bool TraverseNode(T Node, MapNodeTy MapNode,
Richard Smith85838722015-11-24 03:09:01 +00009436 BaseTraverseFn BaseTraverse, MapTy *Parents) {
Craig Topper36250ad2014-05-12 05:36:57 +00009437 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009438 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00009439 if (ParentStack.size() > 0) {
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00009440 // FIXME: Currently we add the same parent multiple times, but only
9441 // when no memoization data is available for the type.
9442 // For example when we visit all subexpressions of template
9443 // instantiations; this is suboptimal, but benign: the only way to
9444 // visit those is with hasAncestor / hasParent, and those do not create
9445 // new matches.
9446 // The plan is to enable DynTypedNode to be storable in a map or hash
9447 // map. The main problem there is to implement hash functions /
9448 // comparison operators for all types that DynTypedNode supports that
9449 // do not have pointer identity.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009450 auto &NodeOrVector = (*Parents)[MapNode];
Manuel Klimek95403e62014-05-21 13:28:59 +00009451 if (NodeOrVector.isNull()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009452 if (const auto *D = ParentStack.back().get<Decl>())
9453 NodeOrVector = D;
9454 else if (const auto *S = ParentStack.back().get<Stmt>())
9455 NodeOrVector = S;
9456 else
9457 NodeOrVector =
9458 new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009459 } else {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009460 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
9461 auto *Vector = new ASTContext::ParentVector(
9462 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
Gabor Horvath10a837a2017-04-19 15:11:10 +00009463 delete NodeOrVector
9464 .template dyn_cast<ast_type_traits::DynTypedNode *>();
Benjamin Kramer422b3ff2015-10-23 13:24:18 +00009465 NodeOrVector = Vector;
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00009466 }
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00009467
9468 auto *Vector =
9469 NodeOrVector.template get<ASTContext::ParentVector *>();
9470 // Skip duplicates for types that have memoization data.
9471 // We must check that the type has memoization data before calling
9472 // std::find() because DynTypedNode::operator== can't compare all
9473 // types.
9474 bool Found = ParentStack.back().getMemoizationData() &&
9475 std::find(Vector->begin(), Vector->end(),
9476 ParentStack.back()) != Vector->end();
9477 if (!Found)
9478 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009479 }
9480 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009481 ParentStack.push_back(createDynTypedNode(Node));
Richard Smith85838722015-11-24 03:09:01 +00009482 bool Result = BaseTraverse();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009483 ParentStack.pop_back();
9484 return Result;
9485 }
9486
9487 bool TraverseDecl(Decl *DeclNode) {
Richard Smith85838722015-11-24 03:09:01 +00009488 return TraverseNode(DeclNode, DeclNode,
9489 [&] { return VisitorBase::TraverseDecl(DeclNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009490 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009491 }
9492
9493 bool TraverseStmt(Stmt *StmtNode) {
Richard Smith85838722015-11-24 03:09:01 +00009494 return TraverseNode(StmtNode, StmtNode,
9495 [&] { return VisitorBase::TraverseStmt(StmtNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009496 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009497 }
9498
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009499 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
Richard Smith85838722015-11-24 03:09:01 +00009500 return TraverseNode(
9501 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
9502 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
9503 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009504 }
9505
9506 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
9507 return TraverseNode(
9508 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
Richard Smith85838722015-11-24 03:09:01 +00009509 [&] {
9510 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
9511 },
9512 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009513 }
9514
9515 ASTContext::ParentMapPointers *Parents;
9516 ASTContext::ParentMapOtherNodes *OtherParents;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009517 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
9518
9519 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
9520 };
9521
Eugene Zelenkod4304d22015-11-04 21:37:17 +00009522} // anonymous namespace
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009523
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009524template <typename NodeTy, typename MapTy>
9525static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
9526 const MapTy &Map) {
9527 auto I = Map.find(Node);
9528 if (I == Map.end()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009529 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009530 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009531 if (auto *V = I->second.template dyn_cast<ASTContext::ParentVector *>()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009532 return llvm::makeArrayRef(*V);
Manuel Klimek95403e62014-05-21 13:28:59 +00009533 }
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009534 return getSingleDynTypedNodeFromParentMap(I->second);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009535}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009536
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009537ASTContext::DynTypedNodeList
9538ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
9539 if (!PointerParents) {
9540 // We always need to run over the whole translation unit, as
9541 // hasAncestor can escape any subtree.
9542 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
9543 PointerParents.reset(Maps.first);
9544 OtherParents.reset(Maps.second);
9545 }
9546 if (Node.getNodeKind().hasPointerIdentity())
9547 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
9548 return getDynNodeFromMap(Node, *OtherParents);
9549}
9550
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009551bool
9552ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
9553 const ObjCMethodDecl *MethodImpl) {
9554 // No point trying to match an unavailable/deprecated mothod.
9555 if (MethodDecl->hasAttr<UnavailableAttr>()
9556 || MethodDecl->hasAttr<DeprecatedAttr>())
9557 return false;
9558 if (MethodDecl->getObjCDeclQualifier() !=
9559 MethodImpl->getObjCDeclQualifier())
9560 return false;
Alp Toker314cc812014-01-25 16:55:45 +00009561 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009562 return false;
9563
9564 if (MethodDecl->param_size() != MethodImpl->param_size())
9565 return false;
9566
9567 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
9568 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
9569 EF = MethodDecl->param_end();
9570 IM != EM && IF != EF; ++IM, ++IF) {
9571 const ParmVarDecl *DeclVar = (*IF);
9572 const ParmVarDecl *ImplVar = (*IM);
9573 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
9574 return false;
9575 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
9576 return false;
9577 }
9578 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
9579
9580}
Richard Smith053f6c62014-05-16 23:01:30 +00009581
Yaxun Liu402804b2016-12-15 08:09:08 +00009582uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
9583 unsigned AS;
9584 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
9585 AS = 0;
9586 else
9587 AS = QT->getPointeeType().getAddressSpace();
9588
9589 return getTargetInfo().getNullPointerValue(AS);
9590}
9591
Yaxun Liub34ec822017-04-11 17:24:23 +00009592unsigned ASTContext::getTargetAddressSpace(unsigned AS) const {
Yaxun Liu6d96f1632017-05-18 18:51:09 +00009593 if (AS >= LangAS::FirstTargetAddressSpace)
9594 return AS - LangAS::FirstTargetAddressSpace;
Yaxun Liub34ec822017-04-11 17:24:23 +00009595 else
9596 return (*AddrSpaceMap)[AS];
9597}
9598
Richard Smith053f6c62014-05-16 23:01:30 +00009599// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
9600// doesn't include ASTContext.h
9601template
9602clang::LazyGenerationalUpdatePtr<
9603 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
9604clang::LazyGenerationalUpdatePtr<
9605 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
9606 const clang::ASTContext &Ctx, Decl *Value);